Visual Studio 2008 and .NET Framework 3.5 Service Pack 1


Both the Visual Studio 2008 and .NET Framework 3.5 Service Pack 1 are now available for download here and here respectively. They are really not a normal Service Pack as they not only fix bugs, but they also add a lot of new features that are not related to security. Please note that the Visual Studio 2008 SP1 includes the .NET Framework 3.5 SP1.

author: Jonas Stawski | posted @ Tuesday, August 12, 2008 11:35 AM | Feedback (0)

Generic IsNull Helper Method


When you use DataReaders you have to check for DBNull.Value on every field that could have a possible null value to make sure you don't get an exception. Therefore your code ends up having a lot of these:

if (dr["Colunm1"] != DBNull.Value)
    SomeStringVariable = dr["Column1"].ToString();
 
//or using inline if
 
SomeStringVariable = (dr["Column1"] != DBNull.Value ? dr["Column1"].ToString() : String.Empty);
If dr("Column1") is DBNull.Value Then
    SomeStringValue = dr("Column1").ToString()
End If

The other day I got tired of it so I decided to take advantage of Generics and write a generic method:

private static T IsNull<T>(object o) 
{ 
    T retValue = default(T); 
    if (o != DBNull.Value) { 
        retValue = (T)o; 
    } 
    
    return retValue; 
} 
Private Shared Function IsNull(Of T)(ByVal o As Object) As T
    Dim retValue As T = Nothing
    If o IsNot DBNull.Value Then
        retValue = CType(o, T)
    End If
 
    Return retValue
End Function

You then use this method like this:

IntVariable = IsNull<int>(dr["IntColumn"]); 
StringVariable = IsNull<string>(dr["StringColumn"]); 
IntVariable = IsNull(Of Integer)(dr("IntColumn"))
StringVariable = IsNull(Of String)(dr("StringColumn"))

Of course you can use any type you need.

Happy programming!

author: Jonas Stawski | posted @ Wednesday, August 06, 2008 3:57 PM | Feedback (0)

Why Tech Green Initiative?


The other day I started the Tech Green Initiative and I want to continue pushing it. I had someone tell me he didn't know you can recycle the printer cartridges so in that sense I made at least one person aware of something green. The other day they sent me this video which I would like to share with you. It is entitled "The Story of Stuff". It speaks for itself.

author: Jonas Stawski | posted @ Thursday, July 31, 2008 10:55 AM | Feedback (0)

Randy Pausch, An Inspiration


Randy Pausch, a Computer Science professor at Carnegie Mellon University, died 5 days ago after being diagnosed with pancreatic cancer. The reason why I'm blogging this is not because he died, but because of his inspirational last lecture:

 

Happy Living!

author: Jonas Stawski | posted @ Wednesday, July 30, 2008 2:30 PM | Feedback (0)

Using Brackets with StringBuilder AppendFormat


I was in need of using some brackets with the AppendFormat of the StringBuilder class, but the brackets are a special character for the AppendFormat. The function uses the brackets to indicate variable placement. So in the code below the {0} will be replaced with the value of the variable name.

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Hello, my name is {0}", name);
Dim SB As New StringBuilder() 
SB.AppendFormat("Hello, my name is {0}", Name) 

If you want to add a bracket to the StringBuilder and you also want to use the AppendFormat then you need to escape it by doing double brackets {{ or }}.

sb.AppendFormat("Hello, my name is {0} and these are brackets: {{ }}", name);
SB.AppendFormat("Hello, my name is {0} and these are brackets: {{ }}", Name)

 

Happy Programming!

author: Jonas Stawski | posted @ Tuesday, July 29, 2008 8:01 PM | Feedback (0)

Tech Green Initiative


I have been into the Go Green Initiative for about 2 months now. I have been watching Planet Green way too much and I always felt like I had to do something about it. I feel like making green changes in my home is not good enough and that I have to reach the masses somehow. So this blog post is the official introduction of the Tech Green Initiative (TGI). The purpose of the Tech Green Initiative is to help the conservation and improvement of the natural environment with anything that is, in one way or another, related to technology. TGI stretches from the reuse of printer paper to the creation of a more efficient CPU. TGI does not intend to replace the current Green movement; however, it is meant to complement it.

So without further a do I present my TGI list:

  • I have my computers to automatically hibernate at 12 AM and to automatically start at 6 AM. This way I conserver energy and have the computer up and running for when I start work.
  • I recycle paper by printing double sided or reuse previously printed paper to print on the blank side. This way I can conserve paper and save some trees.
  • I resend my empty HP printer cartridge back to Hewlett Packard for recycling. More on this here.
  • I print on fast draft to save ink and that way conserve plastic cartridges.

And here is my upcoming TGI changes:

  • Undervolting my computers.
  • Create a Wind Turbine to power my laptops.

I will continue to update on my ongoing efforts to conserve and improve our earth.

Do you have your own TGI list? Why not blog about it? Don't have a blog? Leave a comment here...

author: Jonas Stawski | posted @ Monday, July 28, 2008 1:54 AM | Feedback (0)

Tampa User Experience (TUX) User Group


My colleague and ex coworker, Jay Kimble from the Run Time is starting a new User Group in Tampa called "Tampa User Experience" with Bill Reiss, Shawn Cady, and Perry Panagopoulos. Their first meeting will be on September 10th, 2008 and it will about MS Ajax Scripting by Jay Kimble. Jay usually charges for this session and he will give it for free. Plus there will be Pizza and a raffle for an MSDN Universal Subscription. It is a great opportunity to network and win some prices, so if you are in the Tampa area I don't see a reason to miss this meeting.

author: Jonas Stawski | posted @ Friday, July 18, 2008 11:15 AM | Feedback (0)

Make Your Business Layer a Data Component


One of the cool features of ASP.NET 2.0 is the new Object Data Source, which lets you bind your business entities/objects to your ASP.NET controls. What I hate about this control is imagethat when you open the dropdown you get a list of all the classes that are referenced in your project, which in some cases in can be a lot of them. If you check the Show only data components box then most of the time the dropdown empties out.

So how do you get your business layer classes to show as Data Components? All you have to do is add the attribute DataObject to the class. According to the MSDN documentation: "Identifies a type as an object suitable for binding to an ObjectDataSource object."

 

 

 

[DataObject]
public class manager
{
  //methods go here
}
<DataObject()> _
Public Class Manager
   'Methods go here
End Class

If your Business Layer is in a separate layer (project) from your UI then you will need to recompile. Now when you check image"Show only data components" you get a smaller list with your Business Layer class.

Furthermore, you can decorate your methods with the DataObjectMethod attribute which "Identifies a data operation method exposed by a type, what type of operation the method performs, and whether the method is the default data method."

 

 

[DataObjectMethod(DataObjectMethodType.Select, false)]
public static List<User> GetUsers()
{
    //Implementation goes here
}
<DataObjectMethod(DataObjectMethodType.Select, false)> _
Public Shared Function GetUsers() as List(Of User)
    'Implementation goes here
End Function

Happy Data Binding!

author: Jonas Stawski | posted @ Monday, July 14, 2008 11:05 AM | Feedback (2)

LINQ To SQL Generic Detach


Anyone who has been trying to use LINQ To SQL with ASP.NET would know of the problems of dealing with state. Since LINQ To SQL does require to maintain state of the entities and the DataContext, the stateless behavior of the web leaves us with a lot of problems that we have to deal with. One of the patterns I have seen over and over again is to keep the entity in memory (through cache, session, viewstate, etc) during postbacks, create a new context, and reattach the entity to the new context. The problem with that is that the entity still holds some information that it was previously created by another datacontext and the moment you want to attach it an exception is thrown. People have been dealing with this problem by detaching the entity and the way you do that is by setting all the Association Properties to default(EntityRef<PropertyType>). So people are extending all their entities and creating a Detach method which detaches each Association Property one by one. So now maintainability is a pain in the you know what. The moment you add a new association you will have to remember to detach it in the Detach method.

After looking at the code created by LINQ to SQL I noticed the following:

private void Initialize()
{
    this._SalesOrderDetails = new EntitySet<SalesOrderDetail>(new Action<SalesOrderDetail>(this.attach_SalesOrderDetails), new Action<SalesOrderDetail>(this.detach_SalesOrderDetails));
    this._SalesPerson = default(EntityRef<SalesPerson>);
    OnCreated();
}

That's exactly what we need to detach each entity: reinitialize it again. So you can simply fully detach an entity by calling the Initialize method which SqlMetal automatically generates for us. So next time we modify our model and add a new association SqlMetal or Visual Studio will recreate the Initialize method with all the initialization of all the associations for us, which solves the maintainability problem.

A huge warning is that if you are using the partial method OnCreated on your partial class the method will be invoked again.

To go a little further you can extend every entity by creating a partial class and make it inherit from a base class. I called it BaseEntity. This base class can have a Detach method which can invoke the Initialize method of it's inheritor through reflection by doing this:

GetType().GetMethod("Initialize", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(this, null);

Please note that reflection does add overhead, but I think this solution uses the least amount of reflection possible to accomplish something that will otherwise require a lot of maintainability.

I am working on an article on how to use LINQ to SQL in an N-Tier environment with ASP.NET (without WCF). So keep posted as I will notify everyone when the article is published.

Happy Programming!

author: Jonas Stawski | posted @ Wednesday, July 09, 2008 12:05 AM | Feedback (1)

Component Art Web.UI Client Script Deployment


I was doing some research on Component Art's Web.UI suite and I came across this post by Milos. Basically Component Art added a new feature in the 2007.2 version to allow all the client script references to be downloaded all at once. Why? Because the roundtrip during the request for the scripts adds a lot of overhead. The problem with this is that now all the Web.UI scripts are downloaded with one big request, which according to Milos is about 300K. They resolve the size issue by allowing you to specify which scripts to get based on your needs. So if you only use the menu, then you would only get the scripts necessary for the menu and thus avoiding the extra overhead. Please note this is an application level change so if you're going to specify which scripts to get then you must select all the controls used on your application.

Milos also explains how to set your app to use the new feature. I tried it out and of course it didn't work for me. Why? Because I'm running IIS 7 under Windows Vista. What's the difference? IIS 7 uses the HTTP Handlers in another section of the web.config, so if you're using Windows Vista add the HTTP Handler under <systen.webServer><handlers> section. And if you're like me where your production server is running IIS 6, then add the handler in both sections.

So I decided to give it a shot to see if there was any performance increase so I fired up FireFox and FireBug and inspected the network traffic. Without the new feature turned on I had 22 requests with a total of 314 KB worth of data and it took 159 ms.

image

The results with the new feature turned on are very promising. I'm only bringing down the scripts for the Menu, Grid, and Upload controls. The request goes down to 137 ms and there are only 11 requests (half of what it used to be) with a total of 101 KB.

image

Please note that on the first screen shot (feature turned off) there 11 requests to WebResource.axd. This is the handler used by ASP.NET Ajax and the Web.UI utilizes the ScriptManager to register the ComponentArt scripts. In the second screen shot (feature turned on) there is only one request to ComponentArtScript.axd which weights 73 KB in total and that request is the one that gets the script files.

So not only will your application respond faster, but you will also save a ton on bandwidth.

This is a very cool implementation from the guys at Component Art and I think they are doing a great job with their controls, keep up the good work!

author: Jonas Stawski | posted @ Monday, July 07, 2008 2:28 PM | Feedback (0)