<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TheCodeMonk &#187; Web Development</title>
	<atom:link href="http://thecodemonk.com/category/web-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://thecodemonk.com</link>
	<description>Random Thoughts of a Software Development Professional</description>
	<lastBuildDate>Mon, 02 Aug 2010 13:35:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Wrap your ASP.Net session state into a more meaningful object.</title>
		<link>http://thecodemonk.com/2009/12/08/wrap-your-asp-net-session-state-into-a-more-meaningful-object/</link>
		<comments>http://thecodemonk.com/2009/12/08/wrap-your-asp-net-session-state-into-a-more-meaningful-object/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 23:15:25 +0000</pubDate>
		<dc:creator>TheCodeMonk</dc:creator>
				<category><![CDATA[.Net Code]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://thecodemonk.com/?p=51</guid>
		<description><![CDATA[I&#8217;ve tried to eliminate as much session state as possible as I know that it can cause some issues, especially in a server farm environment. However, there are quite a few times that I just need to have it, and I really doubt this small application is going to be hosted in a farm environment. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve tried to eliminate as much session state as possible as I know that it can cause some issues, especially in a server farm environment. However, there are quite a few times that I just need to have it, and I really doubt this small application is going to be hosted in a farm environment. This application is connected to a WCF service, and I really needed to eliminate round trips without using caching since some of this data is somewhat time sensitive, but it still needs to be available across a few page views. Instead of hitting the WCF service numerous times, I save the data in session state.</p>
<p>The way most people seem to have done session state (at least in just random searches on the internet and in sample code), you see this:</p>
<pre name="code" class="C#:nogutter">
  HttpContext.Current.Session["SomeData"] = myData;
</pre>
<p>There is nothing wrong with this. It works. Is it maintainable? Sort. Is it a potential problem? YES! What happens if you do this somewhere:</p>
<pre name="code" class="C#:nogutter">
  myData = HttpContext.Current.Session["SomData"];
</pre>
<p>Obviously you are going to get a null object back and possibly an error depending on other factors. You will probably find the problem during your automated tests (you do have automated tests right?) or at minimum find it during your own testing. The problem is, sometimes things like this will slip past if they are in infrequently used parts of a system that no one bothers to check for 3 or 4 versions that pass.</p>
<p>So in searching around I found various posts on how to wrap your session state into a more manageable object so that typos don&#8217;t creep up and bite you on the backside. Some of the examples went way over what I needed to do and some were way too simple to make sense for me.</p>
<p>So here is what I did (if I happened to have stolen your code, sorry, but it happens in software).</p>
<p>First I created my Current Session class to store everything and I made it static since Session itself is a static object.</p>
<pre name="code" class="C#:nogutter">
  public static class CurrentSession
  {
    private static HttpSessionState LiveSession
    {
      get { return HttpContext.Current.Session; }
    }
  }
</pre>
<p>This simple gives me a class that has access to the current session through a private variable called LiveSession.</p>
<p>Inside this class, I created another class for the CurrentUser since I needed to track the current logged in user (this user has data from the web service, so I&#8217;m not using asp.net authentication methods).</p>
<pre name="code" class="C#:nogutter">
    public static class CurrentUser
    {
      public static bool IsLoggedIn
      {
        get
        {
          bool? logIn = GetUserItem<bool?>(UserData.LoginState);
          if (!logIn.HasValue) logIn = false;
          return (logIn.Value);
        }
        set { SetUserItem<bool>(UserData.LoginState, value); }
      }

      public static FamilyData CurrentFamily
      {
        get { return (GetUserItem<FamilyData>(UserData.Family)); }
        set { SetUserItem<FamilyData>(UserData.FamilyInfo, value); }
      }

      private static T GetUserItem<T>(UserData key)
      {
        T data = (T)LiveSession[Enum.GetName(typeof(UserData), key)];
        return (data);
      }

      private static void SetUserItem<T>(UserData key, T data)
      {
        if (data == null)
          LiveSession.Remove(Enum.GetName(typeof(UserData), key));
        else
          LiveSession[Enum.GetName(typeof(UserData), key)] = data;
      }

      public enum UserData
      {
        Family,
        LoginState
      }
    }
</pre>
<p>Now, some explanation and why I did it the way I did. I could have just made my public variable have the getter and setter access the Session object directly. My typo chances would have been minimized by the fact that it&#8217;s only in two spots that I need to type it, but there is still a chance. So I created myself an enum that I can use to specify which sets of data I am saving or retrieving. I use the enum&#8217;s string value as the session object name, so all I have to do is make sure my enums never use the same name. In my RLC (Real Life Code) I use much longer enums, like CalendarFilterMonth or CalendarFilterDay, for example. In the above example, I use LoggedInUserFamily in place of just Family. While it may be long, intellisense always gets it right for me with just a few keystrokes.</p>
<p>The GetUserItem and SetUserItem simple save and retrieve from the LiveSession object. I use Type generics to tell the functions what type I am saving and retrieving for ease of use. My type casting never has to be done now. I tell it what I want and that&#8217;s what I will get in return.</p>
<p>The best part about this, is to add more, all I need to do is copy and paste a property and change a few of the options, maybe add an enum, and now I&#8217;m done. I don&#8217;t have to worry about typo&#8217;s and I can organize my session object however I want.</p>
<p>To use it, I just do this anywhere in my application:</p>
<pre name="code" class="C#:nogutter">
  if (!CurrentSession.CurrentUser.IsLoggedIn)
     RedirectToLogin();
  else
     if (CurrentSession.CurrentUser.CurrentFamily.NeedsProfileUpdate)
        RedirectToUpdate();
</pre>
<p>Since NeedsProfileUpdate is part of my FamilyData class, I can access that directly!</p>
]]></content:encoded>
			<wfw:commentRss>http://thecodemonk.com/2009/12/08/wrap-your-asp-net-session-state-into-a-more-meaningful-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>First usage of WCF and specified fields.</title>
		<link>http://thecodemonk.com/2009/04/27/first-usage-of-wcf-and-specified-fields/</link>
		<comments>http://thecodemonk.com/2009/04/27/first-usage-of-wcf-and-specified-fields/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 19:33:52 +0000</pubDate>
		<dc:creator>TheCodeMonk</dc:creator>
				<category><![CDATA[.Net Code]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://thecodemonk.com/?p=37</guid>
		<description><![CDATA[I hadn&#8217;t done much in the past with WCF. We had built our web service with the classes .Net 2.0 form of web services and it worked well. Then one day I realized that we had no built in security other than SSL. Since we had added a lot more things to it that could [...]]]></description>
			<content:encoded><![CDATA[<p>I hadn&#8217;t done much in the past with WCF. We had built our web service with the classes .Net 2.0 form of web services and it worked well. Then one day I realized that we had no built in security other than SSL. Since we had added a lot more things to it that could do some damage if a hacker found the service address, I decided to add some basic security. Needless to say, it&#8217;s not as easy as it looks with straight web services.</p>
<p>After doing some searching, I found a few examples of using WCF and implementing custom username authentication, which is exactly what I wanted to do. </p>
<p>Getting WCF set up and running was quite easy. Porting over our web service code just meant creating my ServiceContract and DataContracts and then recompiling. I also had to set my SQL to Linq datacontext serialization mode to Unidirectional. After coding up my custom username authentication and testing it, things were going along quite smoothly.</p>
<p>Everything I had experienced with Linq to SQL serialization still applied to WCF. Relationships had to have the parent set to internal access instead of public. I did also find that the relationships seemed to need a One-To-Many in order to work right. If it was a Many-To-One or a Many-To-Many, it wasn&#8217;t being sent from the WCF service to the client. Since I was in a hurry, I left that issue on the back burner and worked around it. If I five more into it, I will post about it here.</p>
<p>The one thing I had not counted on, was the fact that if you have any fields (properties) marked as being nullable, the Add Service wizard in Visual Studio 2008 will also add a boolean field called fieldSpecified. So if you have a nullable field for, say, PhoneNumber, you will have that and PhoneNumberSpecified. If you fill in the PhoneNumber field, but do not set PhoneNumberSpecified to true, the field will not be sent to the WCF service.</p>
<p>From my little bit of research, if that Specified field is set to false, the property will not be included in the XML document sent to the WCF service. If it is set to true, it will send it whether it&#8217;s null or not. </p>
<p>Since some of our classes have quite a few fields and we have quite a bit of code to set those fields, I did not want to go through and set every one of these stupid properties to true when I set a field. I&#8217;m actually quite surprised that we even need to do this.</p>
<p>In searching for an answer, I found the long way around of writing a program to parse your service.cs (or .vb) file and inserting this code:</p>
<pre name="code" class="C#:nogutter">
  [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
  public string PhoneNumber
  {
    get
    {
      return this.PhoneNumber;
    }
    set
    {
      this.PhoneNumber = value;
      PhoneNumberSpecified = true; // Line Added
    }
  }
</pre>
<p>So, we have to add one line to each property that has a corresponding Specified field. Now I know why people wrote a utility to do this. That file will get overwritten each time you update your service reference.</p>
<p>I wasn&#8217;t too pleased I had to do this so I tried to find a better way. I finally settled on using the PropertyChanged events and some reflection to go and fill that field in.</p>
<p>To make things simple, my Linq to SQL classes all have a base class called BaseBusiness where I do validation and hold some original values so we can use the disconnected nature of the web with Linq to SQL entities. Since I did this, I can only derive my classes on the client side from the same base class. So I created my BaseBusiness class and included my PropertyChange event in there like this:</p>
<pre name="code" class="C#:nogutter">
  public partial class BaseBusiness
  {
    public void InternalPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
      if (!e.PropertyName.Contains("Specified"))
      {
        string prop = String.Format("{0}Specified", e.PropertyName);
        PropertyInfo target = this.GetType().GetProperty(prop);
        if (target != null)
        {
          PropertyInfo src = this.GetType().GetProperty(e.PropertyName);
          bool currentValue = (bool)target.GetValue(sender, null);
          bool hasValue = (src.GetValue(sender, null) == null ? false : true);
          if (currentValue != hasValue)
            target.SetValue(sender, hasValue, null);
        }
      }
    }
  }
</pre>
<p>This is pretty straight forward so far. I check to see if the field is already set to what it should be so I don&#8217;t make any unneccesary calls. Note that I use sender as the object I am using the GetValue and SetValue on. This is because the event is in a base class and wouldn&#8217;t be the right object to use for reflection since the properties would be one level up (or down, depending of where you stand).</p>
<p>Now the only step left is to write it up in the data classes. Which is nothing more than this:</p>
<pre name="code" class="C#:nogutter">
public partial class MyDataClass : BaseBusiness
{
  public MyDataClass()
  {
    this.PropertyChanged += InternalPropertyChanged;
  }

  ~MyDataClass()
  {
    this.PropertyChanged -= InternalPropertyChanged;
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thecodemonk.com/2009/04/27/first-usage-of-wcf-and-specified-fields/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why excellent vendor support matters.</title>
		<link>http://thecodemonk.com/2009/03/20/why-excellent-vendor-support-matters/</link>
		<comments>http://thecodemonk.com/2009/03/20/why-excellent-vendor-support-matters/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 17:29:20 +0000</pubDate>
		<dc:creator>TheCodeMonk</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Windows Development]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://thecodemonk.com/?p=31</guid>
		<description><![CDATA[We have been having some strange problems on production installs. Things like screens clearing when they shouldn&#8217;t, applications slowing down when they didn&#8217;t before, and people&#8217;s computers running slower and slower until they close our application. When I was finally informed of this, I knew it had to be memory leaks. So I fired up [...]]]></description>
			<content:encoded><![CDATA[<p>We have been having some strange problems on production installs. Things like screens clearing when they shouldn&#8217;t, applications slowing down when they didn&#8217;t before, and people&#8217;s computers running slower and slower until they close our application. When I was finally informed of this, I knew it had to be memory leaks.</p>
<p>So I fired up the excellent <a href="http://memprofiler.com">MemProfiler</a>, I started digging into the issues. Aside from some of the other stupidity I was doing, I found a problem with a vendor&#8217;s component. We use <a href="http://devexpress.com/">Developers Express</a> controls for EVERYTHING and we love them, not just the controls, but the company. When I found this issue with XtraReports not being GC&#8217;d after a dispose, I immediately created a small sample for them and submitted a ticket.</p>
<p>Less than 2 days later, they already have it fixed and ready to rock in the latest version. Not only am I impressed, but I am put at ease knowing that if a problem comes up, they are there to not only fix it, but fix it quickly and get it out to people.</p>
<p>This also happened a few months ago when their ASPxThemeDeployer wouldn&#8217;t work on my x64 Vista machine. I peeked at their code and saw why. Reported it and the VERY NEXT DAY they had a solution to the problem and pushed out an update.</p>
<p>I don&#8217;t have to worry. I know I am taken care of.</p>
<p>Thanks guys!</p>
]]></content:encoded>
			<wfw:commentRss>http://thecodemonk.com/2009/03/20/why-excellent-vendor-support-matters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Linq to SQL in web services</title>
		<link>http://thecodemonk.com/2009/03/02/linq-to-sql-in-web-services/</link>
		<comments>http://thecodemonk.com/2009/03/02/linq-to-sql-in-web-services/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 23:26:20 +0000</pubDate>
		<dc:creator>TheCodeMonk</dc:creator>
				<category><![CDATA[.Net Code]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[linq]]></category>

		<guid isPermaLink="false">http://thecodemonk.com/?p=23</guid>
		<description><![CDATA[Quite a while ago, I investigated the use of Linq to SQL in our one web service component that feeds a CMS that we package with out software. In my initial investigations, every time I would send an entity through the web service, I would get a circular reference error. This made sense since each [...]]]></description>
			<content:encoded><![CDATA[<p>Quite a while ago, I investigated the use of Linq to SQL in our one web service component that feeds a CMS that we package with out software. In my initial investigations, every time I would send an entity through the web service, I would get a circular reference error. This made sense since each relationship is bidirectional. If I have a family entity that has a relationship to a person entity, that person entity also has a reference to the family entity. This goes on infinitely. Those relationships are nice because you can grab one single person and then get data out of the family entity without having to do any joins or write a separate query. So what do you do? </p>
<p>There are a couple of options. </p>
<p>1. Make the data context serialization unidirectional. This will turn off all relationships. You will have to manually do your joins using Linq when the data reaches the other side of the transaction.</p>
<p>2. Change the parent access modifier of the relationship to Friend (VB) or Internal (C#). This leaves the child relationships intact but removes the parent relationships. There would no longer be a family relationship in the person entity. </p>
<p>I prefer option 2 simply because then I don&#8217;t have to rejoin my data every time I fetch it. I don&#8217;t need those child to parent relationships because I can build around it by making my web service functions return the family instead of just returning a person, even if I just request the person.</p>
<p>The next issue that I ran into was the updating existing records. Since adding new records takes a detached object and just inserts it as new, that isn&#8217;t an issue. The problem comes in the concurrency tracking that Linq to SQL uses. You either time stamp your record, or you allow it to check previous fields for concurrency. We don&#8217;t use the time stamp method. The way that most things work in the SQL world is that when you save, you either overwrite what is currently in the table, or you get an concurrency error that makes you input everything over again after getting a refresh from the database. This is not the way we like it. We like a merge scenario where I can make a couple changes to the record and someone else can make some other changes and we the save is made, both our changes make it to the database.</p>
<p>So, how do you fix this? It&#8217;s easy with Linq to SQL. It already has the merge saving built in, unlike ADO.Net. (The Entity Framework will do this as well if you set it up right.) Even though Linq to SQL already supports the saving, this won&#8217;t work in web services. The problem is that during serialization, the entity loses it&#8217;s data context. It&#8217;s the data context that actually tracks the changes in the record, not the entity itself. So once the data context loses it&#8217;s entity (gets detached), it has to be reattached in order to do the save. The problem with this is that the data context no longer knows what has changed in this entity, so it cannot do any concurrency validation. The key is to use the Attach method and fill in two of it&#8217;s parameters, one for current entity and one for the original entity. There are a couple ways you can do this, but I choose to add a base class where I could store the serialized entity (complete with children) and ship it back and forth.</p>
<p>No matter how you slice it, you are going to have the overhead of change tracking eating up bandwidth to and from the web service to the calling application. This can either be incredibly apparent by holding your original values in the session state and just passing it back to the web service, or you can serialize it in the entity object and just pull it out later. I use this method for simplicity. I actually just make a business class (actually, I already had one because all my validation is stored there in a generic, fun sort of way that allows it to just interact with IDataError) and in that business class, I just add a object holder and some functions to set the original value.</p>
<p>Here is a small sample of the base business class:</p>
<pre name="code" class="vb.net:nogutter">
Imports System.Xml.Serialization

Public Class BaseBusiness

  Private original As Object

  Public Sub SetOriginalValue(ByVal _OriginalValue As Object, ByVal originalType As System.Type)
    Dim sb As New StringBuilder()
    Using strw As New System.IO.StringWriter(sb)
      Dim SXO As New XmlSerializer(originalType)
      SXO.Serialize(strw, _OriginalValue)
      original = sb.ToString()
    End Using
  End Sub

  Public Function HasOriginalValue() As Boolean
    Dim bOriginal As Boolean = False
    If original IsNot Nothing Then
      bOriginal = True
    End If
    Return bOriginal
  End Function

  Public Function GetOriginalValue(ByVal originalType As System.Type) As Object
    If HasOriginalValue() Then
      Dim sXml As String = CStr(original)
      Dim fam As Object
      Using strr As New System.IO.StringReader(sXml)
        Dim SXO As New XmlSerializer(originalType)
        fam = SXO.Deserialize(strr)
        Return (fam)
      End Using
    Else
      Return (Nothing)
    End If
  End Function
End Class
</pre>
<p>Notice the use of System.Type, this allows me to pass in any data type and serialize it on the fly without having to have special code in my entity class. This makes it appropriate for any class I need to track changes in, even in the entity framework if I so desire.</p>
<p>Here is the top level entity class where I use it:</p>
<pre name="code" class="vb.net:nogutter">
Imports System.Xml.Serialization

Partial Class Family
  Inherits BaseBusiness

  Private Sub OnLoaded()
    OriginalValue = Me
  End Sub

  Public Property OriginalValue() As Family
    Get
      Return CType((Me.GetOriginalValue(GetType(Family))), Family)
    End Get
    Set(ByVal value As Family)
      Me.SetOriginalValue(value, GetType(Family))
    End Set
  End Property
End Class
</pre>
<p>That is the only code that will need to be in the entity class in order for it to work. The best part of this is when the data gets shipped back and forth, it&#8217;s always accessible as the original entity, not a serialized XML string.</p>
<p>This was just a quick test I did when investigating this stuff today. Eventually, I am going to try to minimize the code in both classes some more and see if I can even strip out the XML Serialization to string and just store it as binary data. </p>
]]></content:encoded>
			<wfw:commentRss>http://thecodemonk.com/2009/03/02/linq-to-sql-in-web-services/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>ASP.Net MVC versus Web Forms</title>
		<link>http://thecodemonk.com/2009/02/05/aspnet-mvc-versus-web-forms/</link>
		<comments>http://thecodemonk.com/2009/02/05/aspnet-mvc-versus-web-forms/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 03:53:08 +0000</pubDate>
		<dc:creator>TheCodeMonk</dc:creator>
				<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://thecodemonk.com/?p=20</guid>
		<description><![CDATA[ASP.Net MVC is an awesome concept, and works great. It just has a little way to go in the UI department.]]></description>
			<content:encoded><![CDATA[<p>We are going to be converting a fairly good sized project over to ASP.Net soon. The process of planning has already started. I have been investigating our options and trying to decide what would work best for us.</p>
<p>I checked out ASP.Net MVC first because that seems to be all the rage right now. I can definitely see why people are excited. I had a fully functioning site up and running in no time. It&#8217;s definitely a great framework and introduces a lot of very nice features. I love the testability it introduces into the whole equation, even the view.</p>
<p>What I don&#8217;t like, is the fact that it doesn&#8217;t support 3rd party controls. With the exception of Telerik and possibly Infragistics, others are SOL right now until the component vendors get their components up to speed. I know Jeff Handley had posted a few articles about extending the base controls, but I&#8217;m talking about some serious controls, like Dev Express&#8217;s grids and asp editors. I know there are options, but we will never ditch Dev Express. They have been too good to us. When I can e-mail the CTO with an off the wall management question and have him respond within 8 hours, and submit a message to a general e-mail with some questions about their plans and get a phone call from them within 8 hours, that&#8217;s not only a company that makes a great product, but a company that cares (shameless plug for you guys Julian and Mehul).</p>
<p>So I started to investigate other options. When searching for some silverlight info, one of my dudes discovered Visual WebGui. Visual WebGui was pretty slick. You drag and drop onto what looks like a Windows Form and where you drop it is where it renders when viewed through IE or Firefox. They also had a small tutorial on how to take a regular Windows forms application and quickly convert it to a full blown ASP.Net web application. This would have been awesome, except we don&#8217;t use Windows Forms controls for anything, not even our forms. Everything is from Dev Express, so it doesn&#8217;t convert so hotly. I did some more research and you can get those 3rd party controls to work, but it&#8217;s not the greatest or easiest to work with. Their quick solution would eventually turn into a code nightmare. So much for that.</p>
<p>Looks like it&#8217;s time to dig out the new routing engine in ASP.Net and start wiring up some of my own code. I really wanted to use MVC, but if the UI is going to suck, our users will absolutely hate us.</p>
]]></content:encoded>
			<wfw:commentRss>http://thecodemonk.com/2009/02/05/aspnet-mvc-versus-web-forms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
