C# - Singleton Pattern vs. Static Classes

Link sent to me from Justin.. as we’ve been discussing using Singleton’s in Win Services for the previous post I talked about. I’ll convert to VB later.

Original Article: http://dotnet.dzone.com/news/c-singleton-pattern-vs-static-

By Sam Allen

Problem: Store some common data in a singleton or static class about your program in an object array, which you store in a class. It saves state between usages and stores some caches, and must be initialized only once and shared in many code locations. Making a new object each time would be expensive.

Solution

This article covers the differences between the singleton design pattern and the static keyword on C# classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.

Introducing the Singleton Pattern

Our ideal solution is called the singleton design pattern. Here is an implementation of a singleton that I will use. As you know, a singleton is a single-instance object. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference.

view source

print?

01./// <summary>

02./// Sample singleton object.

03./// </summary>

04.public sealed class SiteStructure

05.{

06. /// <summary>

07. /// Possible an expensive resource we need to only store in one place.

08. /// </summary>

09. object[] _data = new object[10];

10. /// <summary>

11. /// Allocate ourselves. We have a private constructor, so no one else can.

12. /// </summary>

13. static readonly SiteStructure _instance = new SiteStructure();

14. /// <summary>

15. /// Access SiteStructure.Instance to get the singleton object.

16. /// Then call methods on that instance.

17. /// </summary>

18. public static SiteStructure Instance

19. {

20. get { return _instance; }

21. }

22. /// <summary>

23. /// This is a private constructor, meaning no outsides have access.

24. /// </summary>

25. private SiteStructure()

26. {

27. // Initialize members, etc. here.

28. }

29.}

Static Class Example

In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages, which I will elaborate on after this code block.

view source

print?

01./// <summary>

02./// Static class example. Pay heed to the static keywords.

03./// </summary>

04.static public class SiteStatic

05.{

06. /// <summary>

07. /// The data must be a static member in this example.

08. /// </summary>

09. static object[] _data = new object[10];

10. /// <summary>

11. /// C# doesn't define when this constructor is run, but it will

12. /// be run right before it is used most likely.

13. /// </summary>

14. static SiteStatic()

15. {

16. // Initialize all of our static members.

17. }

18.}

You can use static classes to store single-instance, global data. The class will be initialized at any time, but it is my experience that it is initialized lazily, meaning at the last possible moment. However, you lose control over the exact behavior of the class by using a static class.

Singleton Advantages

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

view source

print?

1.// We want to call a function with this structure as an object.

2.// Get a reference from the Instance property on the singleton.

3.{

4. SiteStructure site = SiteStructure.Instance;

5. OtherFunction(site); // Use singleton as parameter.

6.}

Interface Inheritance

In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Usually, the requirements of the interface are a subset of the object in question. Here is how we can use a singleton with an interface, which in the example is called ISiteInterface.

view source

print?

01./// <summary>

02./// Stores signatures of various important methods related to the site.

03./// </summary>

04.public interface ISiteInterface

05.{

06.};

07./// <summary>

08./// Skeleton of the singleton that inherits the interface.

09./// </summary>

10.class SiteStructure : ISiteInterface

11.{

12. // Implements all ISiteInterface methods.

13. // [omitted]

14.}

15./// <summary>

16./// Here is an example class where we use a singleton with the interface.

17./// </summary>

18.class TestClass

19.{

20. /// <summary>

21. /// Sample.

22. /// </summary>

23. public TestClass()

24. {

25. // Send singleton object to any function that can take its interface.

26. SiteStructure site = SiteStructure.Instance;

27. CustomMethod((ISiteInterface)site);

28. }

29. /// <summary>

30. /// Receives a singleton that adheres to the ISiteInterface interface.

31. /// </summary>

32. private void CustomMethod(ISiteInterface interfaceObject)

33. {

34. // Use the singleton by its interface.

35. }

36.}

Now we can reuse our singleton for any of the implementations of interface-conforming objects. There may be 1, 2, or 10. We don't need to rewrite anything over and over again. We store state more conventionally, use objects by their interfaces, and can use traditional object-oriented programming best practices.

Conclusion

Here we can reuse code and control object state much easier. This allows you greatly improved code-sharing, and a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. One good book about this topic is called C# Design Patterns and is written by Judith Bishop.

Expression Blend 3 – SketchFlow – Creating Prototypes

I’ve been dying to try and use SketchFlow with Expression Blend 3.  I do a lot of development design and ideas and screen layouts. It seems that Microsoft has developed a “tool” to allow for this. Though at first glance I’m lost and confused, maybe because I haven't applied anytime to learn it.  Found a good article from a friend on it so thought I’d post it here for my reference as well.

SketchFlow Official Site – See the screen shots to get an idea what what you can do.

SketchFlow How-to Videos – Scroll to bottom area.

Article, Using SketchFlow to Create Better Protoypes.  By Simon Guest.

http://www.infoq.com/articles/guest-simon-sketchflow

All good developers and designers that I’ve run into do some kind of prototyping. For me, prototyping is about creating a communication channel with customers, sharing ideas with stakeholders, and receiving feedback so that changes can be made early on in the development lifecycle.

RelatedVendorContent

As you’ve likely seen, prototypes can come in all kind of forms, ranging from something drawn on the back of a napkin, through to something that looks very close to the original, designed in a professional software package. Despite this variation we commonly see two different types of prototypes: Low fidelity and high fidelity. A low fidelity prototype is as raw depiction; often a whiteboard drawing or sketch that outlines a particular piece of user interface, an example of which can be seen in Figure 1.

Figure 1 - An example of a Low Fidelity Prototype showing a sign in screen

This is known as a low fidelity prototype because the primary purpose is to show a piece of functionality in its simplest form without any of the icons, colors, font selection and so forth.

The opposite is a high fidelity prototype. A high fidelity prototype, such as the one shown in Figure 2, is still a prototype in that the functionality underneath is not complete or wired up to logic, but the look and feel is closer to the finished product.

Figure 2 - An example of a High Fidelity Prototype

Both low fidelity and high fidelity prototypes have their places in the development lifecycle.

Low fidelity prototypes are typically very effective at getting user feedback as they express the raw functionality of the application without losing the user on the details. As the prototype is nothing more than a sketch, users tend to assume that it will be easy to incorporate feedback and as a result are much more open about giving feedback. With that said, there are situations where low fidelity prototypes don’t work as well. An example I’ve found is when updating the executive team at the next board meeting. Because of the rough format of the low fidelity prototype, I’ve been greeted with looks of confusion when walking into the board meeting with nothing more than a flipchart; the executives thinking “Don’t we pay you to write software?”

As you might expect, high fidelity prototypes suffer from the opposite problem. While they work well in board meetings to show what a finished product could look like, the polish that has been applied can often be too overwhelming for many users. I’ve seen examples where users have been frightened to ask for major changes in a high fidelity prototype due to the amount of work that they feel may have to be done to make a change. The user believes that because the prototype looks so close to the finished product, too much work has already gone into the application, and they often are held back in suggesting such changes. In addition, high fidelity prototypes tend to draw users into a conversation about the finer aspects of the design, such as “Shouldn’t that blue be the same shade as our company logo?” rather than focusing on the overall design of the layout.

Moreover, taking a user through any type of prototype can be very tricky, especially those users based in remote locations. Often, we’ll put together a PowerPoint deck of screenshots and send it to the user without having the ability to share the context or interactively take them through the design.

To help address some of the issues with prototyping, at MIX09 in March 2009, Microsoft announced a new technology called SketchFlow, which will ship as part of Microsoft Expression 3. As described by Group Program Manager, Christian Schormann on his blog, SketchFlow is a fun, informal, flexible, quick and powerful way to sketch and prototype rich, dynamic interactivity with Expression Blend.

In this article we’ll be exploring the functionality within SketchFlow, covering how it works in a soon-to-be-released preview edition, and looking at how such a tool could make your prototypes more usable and effective.

If you’ve heard of the Expression Blend family of products, you’ll likely know that the Expression Blend tool is marketed toward the designer community. While interaction designers will likely make up the majority of the users of Blend, I believe that the SketchFlow functionality also makes for an attractive proposition for many developers – many of whom have been prototyping for some time, using whiteboards through to creating mockups of screens in Visual Basic or other tools.

SketchFlow – Getting into the Details

Expression Blend 3 supports two different types of SketchFlow projects. One for WPF (Windows Presentation Foundation) client based applications, and one for Silverlight applications hosted within the Web browser. Both project types offer the same prototyping functionality, however the asset library offered depends on the platform chosen.

After creating a new project in Expression Blend 3, the first component that you’ll likely run across is the “Application Flow”. The Application Flow panel in Blend enables you to create a simple layout and flow for your application.

Figure 3 - A simple application flow for an online store

As shown in the above diagram, the Application Flow is used to compose a simple workflow for the navigable screens of your prototype. In the above application flow we have five boxes representing a simple online store; a storefront screen, a browse screen, a checkout screen, a sign in screen, and a shipping confirmation screen. The navigation screens are interconnected with one way or bidirectional connection lines to indicate the path that the user will take within the application.

Creating this application flow diagram automatically generates a series of blank XAML pages within Expression Blend.

Figure 4 - Creating the application flow generates a series of XAML files in the editor

With the application flow in place we can now start to add controls to each of our prototype screens.

If you’ve used any previous versions of Expression Blend you could probably guess that we could drag and drop items from the asset library to start creating the user interface.

Figure 5 - Standard controls from the asset library

You would be right, however as you can see in Figure 5, by doing this we are already heading down the path of creating a high fidelity prototype.

To help convey a more low fidelity feel, SketchFlow introduces a new XAML style called “WigglyStyles”. As you can guess from the name, this new style imitates the raw form that you may get from a whiteboard or napkin style of sketch. To add to the effect, SketchFlow also comes with two new fonts depicting a handwriting style and an architect’s sketch style. Applying controls from the WigglyStyles style to the same controls gives quite a different effect.

Figure 6 - Controls using the WigglyStyles XAML style

What’s important to note here is that these are all valid and working controls, not simply images. Edit boxes can accept text, buttons can be clicked, scrollbars can be moved, resulting in a very functional screen yet one that adheres to low fidelity visible characteristics.

Adding Navigation

Now that we have an understanding of the application flow and the styles, let’s start designing our prototype. In this article we are going to be creating a prototype for a new “InfoQ store” designed to sell a range of products branded with the infamous InfoQ logo.

Although we have defined the flow of the screens, we haven’t yet added navigation behavior. For example, when I click on the “checkout” button, I naturally want to navigate to the checkout page.

In previous versions of Expression Blend, and this equally applies to many other UI development environments, wiring up navigation often requires setting an action or event and then having to write some code to handle the navigation. While this isn’t complex for most developers, it’s not necessarily that intuitive to designers or those without a development background and in addition, adds unnecessary code that slows down the development of the prototype.

Expression Blend 3 however, treats prototype navigation somewhat differently. Rick clicking on any control brings up a new “Navigate to” context menu, as shown in Figure 7.

Figure 7 - The “Navigate to” context menu in Expression Blend

Selecting the “navigate to” screen generates an activation trigger on the control. In XAML this looks similar to the following:

<Button FontSize="20" Height="34" HorizontalAlignment="Right" Margin="0,0,8,19" Style="{StaticResource Wiggle_ButtonStyle}" VerticalAlignment="Bottom" Width="105" Content="Checkout">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<Microsoft_Expression_Prototyping_Behavior:NavigateToScreenAction TargetScreen="InfoQStoreScreens.Screen_1_1"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>

The XAML responsible for the navigation is the interaction trigger and contains an “EventName” to act as the trigger and “NavigateToScreenAction” containing the desired target screen. All of the XAML is auto-generated by the right click of the context menu and no code is required to wire this up.

Adding Composition Screens

Another area of navigation in SketchFlow is the concept of composition screens. If you have experience in Web development, you’ve probably come up against the need to have common controls on each screen. This might be a common set of tabs or buttons displayed at the top of the web page, or a common look and feel that all pages inherit.

In SketchFlow this is known as a composition screen. A composition screen is a collection of XAML objects that can be displayed in a consistent way on any navigation page. To create a composition screen, we first define a common set of controls.

Figure 8 - A common set of controls that we want to replicate on each page

As Figure 8 shows, this includes four buttons – one for returning to the home page, one for displaying the products page, one for showing the account page and one to display the shopping cart. To take these controls and add them to each page, we select all of the controls, right click and select “Make Into Composition Screen…” as shown in Figure 9.

Figure 9 - Turning these controls into a composition screen

After naming the composition screen (I’m going to call this one “TopBanner”) the controls are taken into a separate XAML file, and the composition screen is shown in the Application Flow.

Figure 10 - The composition screen as part of the application flow

As you can see in Figure 10, the TopBanner composition screen is now displayed in the application flow. (The green color differentiates the composition screen from the blue navigation screens). To bind the composition screen to the other XAML pages, we can create a relationship between the composition screen and the navigation screens.

Figure 11 - Binding the composition screen to other navigation screens that should display the common controls

Figure 11 shows how the composition screen will now be used by the storefront, browse, and checkout navigation screens.

Getting Feedback from Users

We’ve added some more controls to the InfoQ store and now feel ready to share with our users in order to get some feedback:

Figure 12 - A completed form that we’d like to share with our user for feedback

As you might imagine, hitting F5 will build and launch the application, but not as you expect. The application does launch but within the context of the SketchFlow Player, a Silverlight based navigation frame that allows the user to drive the application and add feedback during the process.

Figure 13 - The application running in the context of the SketchFlow Player

As depicted in Figure 13, the user has three ways to navigate through the prototype. The “navigate” tab to the left of the player shows the available screens in the workflow, buttons that were configured to navigate to other pages also work, and in the bottom left the user can also investigate the flow of the application by clicking on the flow tab. This displays the same representation as the application flow in the designer, as shown in Figure 14.

Figure 14 - The flow tab in the SketchFlow Player showing the application flow

While navigating through the prototype, the SketchFlow player gives the user the ability to add comments and feedback about the design in two ways: by entering feedback text into the feedback window (for example, asking questions or providing textual feedback on the prototype) and by actually drawing on the screen with an ink or highlighter control. Both text and ink feedback are shown in Figure 15.

Figure 15 - Some user feedback on the search screen for our store application

This can be very useful for the user to share details on finer elements of the design such as placement of controls or windows. This feedback is saved as a “.feedback” file which can then be uploaded to a site or emailed to the original development team. When the development team receives this feedback, it can be imported back into Expression Blend 3 and used as an overlay within the project, allowing the team to have the exact user feedback and annotations as they relate to screens in the designer.

States and Transitions

We talked about screen navigation earlier, but how about if you want to display a message or another animation that didn’t warrant creating a new page? For example, in the InfoQ Store when the user clicks on the “add cart” button, we may want to display a message confirming that an item was successfully added to the shopping cart. This doesn’t necessitate a new screen, but we do need some action to handle the response in the prototype. In SketchFlow this is known as a change of state.

States are created using the States tab to create a group of elements on a page.

Figure 16 - Two states for showing and hiding the “added to cart” message for the user

In the above example, notice how I have created two states – ShowCartMessage and HideCartMessage. I can define what happens in each of these two states. For DialogBoxShow I create a simple dialog that contains a message to indicate that the item has been added and set the opacity of the dialog to 100%, similar to the one shown in Figure 17.

Figure 17 - A simple dialog to indicate the item has been added to the cart

Likewise, for the DialogBoxHide state I set the opacity of the dialog to 0% in order to give the effect that the dialog box has been removed.

Similar to how I wired up the navigation controls earlier, I can simply right click on each of the controls to bind them to a particular state. In this example, when the user clicks on the “add to cart” button, the ShowCartMessage state is activated and the dialog is shown.

Figure 18 - Binding a state to a button control

A similar action is added to the dialog so that when the user clicks anywhere on the window, the message disappears.

Similar to the form navigation, binding to the state adds a XAML code block for each control. The behavior controlling the state is the ActivateStateAction:

<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<Microsoft_Expression_Prototyping_Behavior:ActivateStateAction TargetScreen="InfoQStoreScreens.Screen_1" TargetState="ShowCartMessage"/>
</i:EventTrigger>
</i:Interaction.Triggers>

For added effect, states also support transitions and animations. For example, if our prototype mandated that the dialog box show fade or fly in then we could create a XAML storyboard that could accommodate this. As you’ve probably guessed, everything created by SketchFlow is correctly formed XAML – there are no proprietary switches or hidden options – this means that anything that can be done in XAML can also be reflected in the prototype, even if it’s not supported in the designer.

Adding Sample Data

Up to this point, we’ve covered adding controls and navigation, but a critical element to many prototypes is the need to pull in sample data – in our example this could be a list of products that we’ll be selling through the InfoQ store.

Previous versions of Expression Blend have supported connecting to external data sources through either a direct database connection or CLR object, but wiring this up can be time consuming especially in a prototype environment. It the prototype has a chance of being rejected, it can be cumbersome to create a database, schemas, and tables in a database to handle a few sample objects.

To help overcome this Expression Blend 3 supports the ability to create sample data directly within the designer. This is achieved by adding a new sample data source in the data tab:

Figure 19 - Sample data options within Expression Blend 3

Two options are supported in the current preview; defining a new set of sample data or importing sample data from XML. The second option can be especially useful if you have an XML data representation from an internal system, for example an export from a current line of business application or even a public RSS feed.

No XML data source exists for the prototype store, so I’ll choose to define some new sample data instead.

Figure 20 - Sample data collection for our store

For the sample demo store, a simple collection of types representing the products has been created. You’ll notice that the sample data collection supports multiple data types. SKU is represented here by a text field, but the image is actual a .PNG file from disk (a directory of images can be imported into the sample data collection).

Now that we have the data structure defined, we can define the sample data for the store:

Figure 21 - Editing sample data

Note that in addition to supporting fixed values entered into the sample value dialog box, Blend also supports “automatically generated” sample data for a number of types.

Figure 22 - Automatic sample data types

This option is especially useful if you are working on a prototype that has a need to display a list of fake telephone numbers, URLs, Email addresses, etc.

With the sample data complete, the next step is to drag and drop the data collection from the data panel to the object (in this case this is the search list box) to populate the item. When the application is run, all of the data imported is usable within the prototype.

Figure 23 - Dragging and dropping the data collection to the search list box to populate the items in the prototype

You can imagine creating a new state bound to the “Search” button in this form that populates the sample data.

Documentation

I’ve run into only a few people that actually find enjoyment when creating documentation for projects - yet documentation, especially for prototypes, can be critical as it provides a record for mapping out all of the elements assets, user feedback, and states for a prototype.

If you fall into the category of not liking documentation either, one of the features in Expression Blend 3 you’ll be pleased to see is the “Export to Microsoft Word” option from the file menu.

Figure 24 - The “Export to Microsoft Word…” option

Clicking on this option generates a new Word document based on all of the elements in your prototype file.

Figure 25 - Example output

This includes application flow, screen layouts, user feedback, transitions, and states, all wrapped up with a table of contents and list of applicable figures. All this information in Word format makes it easy to then apply a template and add your own comments before sending it to your user or client for review.

Moving from Prototype to Production

At the end of the day the success of a prototype can often be measured by the success of the resulting application, which raises the question, “How do I take these prototypes into production?” When working with customers I often see two approaches.

The first answer is to throw everything away, and with existing tools this is often the case today. Frequently, a designer will create a screen mockup of an application in a tool such as Adobe Photoshop, export the complete image to JPG files, and then rely on the developer to take those JPG files and create the real application. More often than not this can lead to different interpretations between the designer and developer, especially around some of the subtleties within the design.

The second answer is to keep as much of the prototype as possible in order to re-use the assets as you move into production. Using SketchFlow, a lot of the visual assets and controls can be kept, together with replacing the navigation and application flow with a more robust framework such as MVC, switching out the states into code, handling exceptions, and so forth. There is always a balance between how much of a prototype you keep into production and how much gets thrown away, but an interactive prototyping tool makes it much easier to make those kinds of tradeoffs.

Conclusion

I hope this article has been useful for walking through some of the early capabilities in SketchFlow. Microsoft is still very early on in the preview process for Expression Blend 3, so lots of things may well change before release, but I hope you’ll agree that this new set of tools has the opportunity to help designers and developers take prototyping to the next level.

.Net – Improve garbage collection and performance

My friend Pasha, found a great article by QuestPond over at DotNetFunda that covers the theory and best practices of proper .Net garbage collection.

-----------------

Ask any developer which is the best place in a .NET class to clean unmanaged resources?, 70% of them will say the destructor. Although it looks the most promising place for cleanup it has a huge impact on performance and memory consumption. Writing clean up code in the destructor leads to double GC visits and thus affecting the performance multifold times.

In order to validate the same we will first start with bit of theory and then we will actually see how GC algorithm performance is impacted using destructor. So we will first understand the concept of generations and then we will see the finalize dispose pattern.

Is this Article worth reading ahead?

With this article you will understand how performance of GC algorithm can be improved using finalize dispose pattern. Below figure shows the comparison of what we will be achieving after this article.

Introduction and Goal

Ask any developer which is the best place in a .NET class to clean unmanaged resources?, 70% of them will say the destructor. Although it looks the most promising place for cleanup it has a huge impact on performance and memory consumption. Writing clean up code in the destructor leads to double GC visits and thus affecting the performance multifold times.
In order to validate the same we will first start with bit of theory and then we will actually see how GC algorithm performance is impacted using destructor. So we will first understand the concept of generations and then we will see the finalize dispose pattern.
I am sure this article will change your thought process regarding destructor, dispose and finalize.
Please feel free to download my free 500 question and answer eBook which covers .NET , ASP.NET , SQL Server , WCF , WPF , WWF@ http://www.questpond.com .

Assumptions

This article uses CLR profiler to profile how GC works. In case you are new to CLR profiler please do read net-best-practice-no-1-detecting-high-memory-consuming-functions-in-net-code   before you go ahead with this one.

Thanks Mr. Jeffrey Richter and Peter Sollich

Let’s start this article by first thanking Mr. Jeffery Richter for explaining in depth how garbage collection algorithm works. He has written two legendary articles about the way garbage collector work. I actually wanted to point to the MSDN magazine article written by Jeffery Richter but for some reason it’s not showing up in MSDN. So I am pointing to a different unofficial location, you can download both the articles from http://www.cs.inf.ethz.ch/ssw/files/GC_in_NET.pdf in a PDF format.
Also thanks to Mr. Peter Sollich who is the CLR Performance Architect to write such a detail help on CLR profiler. When you install the CLR profiler please do not forget to read the detail help document written by Peter Sollich. In this article we will use the CLR profiler to check how the garbage collector performance is affected using finalize.
Thanks a lot to you guys. There was no way I would have completed this article without reading articles written by you. Any time you guys pass by article please do comment on the same would love to hear from you guys.

Garbage collector – The unsung Hero

As said in the introduction writing clean up code in constructor leads to double GC visits. Many developers would like to just shrug off and say ‘Should we really worry about GC and what it does behind scenes?”. Yes, actually we should not worry about GC if you write your code properly. GC has the best algorithm to ensure that your application is not impacted. But many times the way you have written your code and assigned/cleaned memory resources in your code affects GC algorithm a lot. Sometimes this impact leads to bad performance of GC and hence bad performance for your application.
So let’s first understand what different tasks are performed by the garbage collector to allocate and clean up memory in an application.
Let’s say we have 3 classes where in class ‘A’ uses class ‘B’ and class ‘B’ uses class ‘C’.

When the first time your application starts predefined memory is allocated to the application. When the application creates these 3 objects they are assigned in the memory stack with a memory address. You can see in the below figure how the memory looks before the object creation and how it looks after object creation. In case there was an object D created it will be allocated from the address where Object C ends.

Internally GC maintains an object graph to know which objects are reachable. All objects belong to the main application root object. The root object also maintains which object is allocated on which memory address. In case an object is using other objects then that object also holds a memory address of the used object. For example in our case object A uses Object B. So object A stores the memory address of Object B.

Now let’s say Object ‘A’ is removed from memory. So the Object ‘A’ memory is assigned to Object ‘B’ and Object ‘B’ memory is assigned to object ‘C’. So the memory allocation internally looks something as shown below.

As the address pointers are updated GC also needs to ensure that his internal graph is updated with new memory addresses. So the object graph becomes something as shown below. Now that’s a bit of work for GC it needs to ensure that the object is removed from graph and the new addresses for the existing objects is updated throughout the object tree.

An application other than his own custom objects also has .NET objects which also form the part of the graph. The addresses to those objects also need to be updated. The number of objects of .NET runtime is very high. For instance below is the number of objects created for a simple console based hello world application. The numbers of objects are approximately in 1000’s. Updating pointers for each of these objects is a huge task.

Generation algorithm – Today, yesterday and day before yesterday

GC uses the concept of generations to improve performance. Concept of generation is based on the way human psychology handles tasks. Below are some points related to how tasks are handled by humans and how garbage collector algorithm works on the same lines:-
• If you decide some task today there is a high possibility of completion of those tasks.
• If some task is pending from yesterday then probably that task has gained a low priority and it can be delayed further.
• If some task is pending from day before yesterday then there is a huge probability that the task can be pending forever.
GC thinks in the same lines and has the below assumptions:-
• If the object is new then the life time of the object can be short.
• If an object is old then it can have a long life time.
So said and done GC supports three generations (Generation 0, Generation 1 and Generation 2).

Generation 0 has all the newly created objects. When the application creates objects they first come and fall in the Generation 0 bucket. A time comes when Generation 0 fills up so GC needs to run to free memory resources. So GC starts building the graph and eliminating any objects which are not used in application any more. In case GC is not able to eliminate an object from generation 0 it promotes it to generation 1. If in the coming iterations it’s not able to remove objects from generation 1 it’s promoted to generation 2. The maximum generation supported by .NET runtime is 2.
Below is a sample display of how generation objects are seen when you run CLR profiler. In case you are new to CLR profiler you can catch up the basics from net-best-practice-no-1-detecting-high-memory-consuming-functions-in-net-code

Ok, so how does generation help in optimization

As the objects are now contained in generations, GC can make a choice which generation objects he wants to clean. If you remember in the previous section we talked about the assumptions made by GC regarding object ages. GC assumes that all new objects have shorter life time. So in other words GC will mainly go through generation 0 objects more rather than going through all objects in all generations.
If clean up from generation 0 does not provide enough memory it will then move towards cleaning from generation 1 and so on. This algorithm improves GC performance to a huge extent.

Conclusion about generations

• Huge number of object in Gen 1 and 2 means memory utilization is not optimized.
• Larger the Gen 1 and Gen 2 regions GC algorithm will perform more worst.

Using finalize/destructor leads to more objects in Gen 1 and Gen 2

The C# compiler translates (renames) the destructor into Finalize. If you see the IL code using IDASM you can see that the destructor is renamed to finalize. So let’s try to understand why implementing destructor leads to more objects in gen 1 and gen 2 regions. Here’s how the process actually works:-
• When new objects are created they are moved to gen 0.
• When gen 0 fills out GC runs and tries to clear memory.
• If the objects do not have a destructor then it just cleans them up if they are not used.
• If the object has a finalize method it moves those objects to the finalization queue.
• If the objects are reachable it’s moved to the ‘Freachable’ queue. If the objects are unreachable the memory is reclaimed.
• GC work is finished for this iteration.
• Next time when GC again starts its goes to Freachable queue to check if the objects are not reachable. If the objects are not reachable from Freachable memory is claimed back.

In other words objects which have destructor can stay more time in memory.
Let’s try to see the same practically. Below is a simple class which has destructor.

class clsMyClass 
{ 
public clsMyClass()
{ 
}
~clsMyClass()
{
}
}

We will create 100 * 10000 objects and monitor the same using CLR profiler.

for (int i = 0; i < 100 * 10000; i++)
{
clsMyClass obj = new clsMyClass();
}

If you see the CLR profiler memory by address report you will see lot of objects in gen 1.

Now let’s remove the destructor and do the same exercise.

class clsMyClass 
{ 
public clsMyClass()
{ 
}
}

You can see the gen 0 has increased considerably while gen 1 and 2 are less in number.

If we see a one to one comparison it’s something as shown in the below figure.

Get rid of the destructor by using Dispose

We can get rid of the destructor by implementing our clean up code in the dispose method For that we need to implement the ‘IDisposable’ method , write our clean up code in this and call suppress finalize method as shown in the below code snippet. ‘SuppressFinalize’ dictates the GC to not call the finalize method. So the double GC call does not happen.

class clsMyClass : IDisposable
{ 
public clsMyClass()
{ 
}
~clsMyClass()
{
}

public void Dispose()
{
GC.SuppressFinalize(this);
} 
}

The client now needs to ensure that it calls the dispose method as shown below.

for (int i = 0; i < 100 ; i++)
{
clsMyClass obj = new clsMyClass();
obj.Dispose(); 
}

Below is the comparison of how Gen 0 and 1 distribution looks with constructor and with dispose. You can see there is marked improvement in gen 0 allocation which signifies good memory allocation.

What if developers forget to call Dispose?

It’s not a perfect world. We cannot ensure that the dispose method is always called from the client. So that’s where we can use Finalize / Dispose pattern as explained in the coming section.
There is a detailed implementation of this pattern at http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx.
Below is how the implementation of finalize / dispose pattern looks like.

class clsMyClass : IDisposable
{ 
public clsMyClass()
{

}

~clsMyClass()
{
// In case the client forgets to call
// Dispose , destructor will be invoked for
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free managed objects.
}
// Free unmanaged objects

}

public void Dispose()
{
Dispose(true);
// Ensure that the destructor is not called
GC.SuppressFinalize(this);
} 
}

Explanation of the code:-
• We have defined a method called as Dispose which takes a Boolean flag. This flag says is this method called from Dispose or from the destructor. If this is called from the ‘Dispose’ method then we can free both managed and unmanaged resources.
• If this method is called from the destructor then we will just free the unmanaged resources.
• In the dispose method we have suppressed the finalize and called the dispose with true.
• In the destructor we have called the dispose function with false value. In other words we assume that the GC will take care of managed resources and let’s take the destructor call to clean unmanaged resources.
In other words if the client does not call the dispose function the destructor will take care of cleaning the unmanaged resources.

Conclusion

• Do not have empty constructors in your classes.
• In case you need to clean up use finalize dispose pattern with ‘SupressFinalize’ method called.
• If there is a dispose method exposed by a class , ensure to call the same from your client code.
• Application should have more objects allocated in Gen 0 than Gen 1 and Gen 2. More objects in Gen 1 and 2 is sign of bad GC algorithm execution.

Source code

You can find the sample source code for the dispose pattern at from here

Call your Win Service from your Web Application

Some quick code snippets from my brother.  If you have a running Windows Service, you can call it from your Web Application to run a custom command. UPDATE: There’s some better VB Sample Code here and quick and easy of both the Windows Service and the ASP.Net

So you have your Win Service named “Encoder” and when you say, upload a video, you then call the Service and send it an argument value of 10.  Then in your web service when it see’s the value 10 come in, it knows to start encoding any videos uploaded. 

Here’s some sample code:

Web application must have full trust. Partial trust not allowed.

In your application: (add reference to System.ServiceProcess.dll)

System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController(“serviceName”)
controller.ExecuteCommand(commandinteger);


In your Win service here is your code:

protected override void OnCustomCommand(int commandinteger){
 
switch(commandinteger){
case 129:
//do something
break;
case 130:
//do something else
break;
}
 
}

commandinteger values must be between 128 and 256.

128 and below are system reserved.

Check the link below for msdn description
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand.aspx

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.oncustomcommand(VS.80).aspx

Found this blog post with more info, cause I’m lazy :p

http://blogs.msdn.com/kaevans/archive/2005/03/17/397505.aspx

Updated Blog Post On This Topic

SQL 2008 Enabling Change Data Capture Made Easy

Ok I was looking all over the web, and I can into “older” pre-release version of these steps, then ran into problems that just didn’t really work if I copied the steps I read about.

So quick and dirty this is my step-by-step of setting up Change Data Capture or CDC for SQL 2008. A New feature by the way in SQL 2008.

Assumptions:

  • Database is named DuFrainCashOut
  • Table I plan to audit is called CashOut, owned by dbo. So dbo.CashOut
  • All these commands are run against the database

Steps:

  1. Enable your Database. (IF YOU GET ERROR, step 1.2.1)
    1. Command:
    2. exec sys.sp_cdc_enable_db
    3. If you get an error: Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.
      1. Run this command:
      2. sp_changedbowner 'dbo'   
      3. (Of course swap out dbo with whoever the owner is)
  2. Turn on CDC for a specific table (You have to do each table)
    1. Command:
    2. EXEC sys.sp_cdc_enable_table 'dbo', 'CashOut', null, null, 1

Done. Now it’s up and running for that table.

Now you have to get the data out. When you ran the last command it created to tabular functions, fn_cdc_get_all_changes_dbo_CashOut and fn_cdc_get_net_changes_dbo_CashOut

You can select against these to get the data you need. I had a problem here because you have to use LSN numbers to get the data and I had problems getting accurate numbers. Anyway, this is what I came up with..

DECLARE @begin_time datetime 
DECLARE @end_time datetime 
DECLARE @begin_lsn binary(10)
DECLARE @end_lsn binary(10)

SET @begin_time = '2009-10-05 12:00:00.000'

SELECT @begin_lsn = sys.fn_cdc_map_time_to_lsn('smallest greater than', @begin_time);
SELECT @end_lsn = sys.fn_cdc_get_max_lsn()
SELECT * FROM cdc.fn_cdc_get_all_changes_dbo_CashOut(@begin_lsn, @end_lsn, 'all update old');

I tried the same method with @begin_lsn for @end_lsn but I kept getting null’s and gave up. This will create you two sql jobs by the way for each table you CDC for.

This is what is returned:

Column name Data type Description

__$start_lsn

binary(10)

Commit LSN associated with the change that preserves the commit order of the change. Changes committed in the same transaction share the same commit LSN value.

__$seqval

binary(10)

Sequence value used to order changes to a row within a transaction.

__$operation

int

Identifies the data manipulation language (DML) operation needed to apply the row of change data to the target data source. Can be one of the following:

1 = delete

2 = insert

3 = update (captured column values are those before the update operation). This value applies only when the row filter option 'all update old' is specified.

4 = update (captured column values are those after the update operation)

__$update_mask

varbinary(128)

A bit mask with a bit corresponding to each captured column identified for the capture instance. This value has all defined bits set to 1 when __$operation = 1 or 2. When __$operation = 3 or 4, only those bits corresponding to columns that changed are set to 1.

<captured source table columns>

varies

The remaining columns returned by the function are the captured columns identified when the capture instance was created. If no columns were specified in the captured column list, all columns in the source table are returned.

Resources:

Enabling Change Data Capture
cdc.fn_cdc_get_all_changes_<capture_instance> (Transact-SQL)
sys.fn_cdc_map_time_to_lsn (Transact-SQL)

State DropDown List

My list for project when I need a State DropDownList

Full State Names using asp:DropDownList

<asp:DropDownList ID="ddlStates" runat="server">
    <asp:ListItem Value="AL">Alabama</asp:ListItem>
    <asp:ListItem Value="AK">Alaska</asp:ListItem>
    <asp:ListItem Value="AZ">Arizona</asp:ListItem>
    <asp:ListItem Value="AR">Arkansas</asp:ListItem>
    <asp:ListItem Value="CA">California</asp:ListItem>
    <asp:ListItem Value="CO">Colorado</asp:ListItem>
    <asp:ListItem Value="CT">Connecticut</asp:ListItem>
    <asp:ListItem Value="DC">District of Columbia</asp:ListItem>
    <asp:ListItem Value="DE">Delaware</asp:ListItem>
    <asp:ListItem Value="FL">Florida</asp:ListItem>
    <asp:ListItem Value="GA">Georgia</asp:ListItem>
    <asp:ListItem Value="HI">Hawaii</asp:ListItem>
    <asp:ListItem Value="ID">Idaho</asp:ListItem>
    <asp:ListItem Value="IL">Illinois</asp:ListItem>
    <asp:ListItem Value="IN">Indiana</asp:ListItem>
    <asp:ListItem Value="IA">Iowa</asp:ListItem>
    <asp:ListItem Value="KS">Kansas</asp:ListItem>
    <asp:ListItem Value="KY">Kentucky</asp:ListItem>
    <asp:ListItem Value="LA">Louisiana</asp:ListItem>
    <asp:ListItem Value="ME">Maine</asp:ListItem>
    <asp:ListItem Value="MD">Maryland</asp:ListItem>
    <asp:ListItem Value="MA">Massachusetts</asp:ListItem>
    <asp:ListItem Value="MI">Michigan</asp:ListItem>
    <asp:ListItem Value="MN">Minnesota</asp:ListItem>
    <asp:ListItem Value="MS">Mississippi</asp:ListItem>
    <asp:ListItem Value="MO">Missouri</asp:ListItem>
    <asp:ListItem Value="MT">Montana</asp:ListItem>
    <asp:ListItem Value="NE">Nebraska</asp:ListItem>
    <asp:ListItem Value="NV">Nevada</asp:ListItem>
    <asp:ListItem Value="NH">New Hampshire</asp:ListItem>
    <asp:ListItem Value="NJ">New Jersey</asp:ListItem>
    <asp:ListItem Value="NM">New Mexico</asp:ListItem>
    <asp:ListItem Value="NY">New York</asp:ListItem>
    <asp:ListItem Value="NC">North Carolina</asp:ListItem>
    <asp:ListItem Value="ND">North Dakota</asp:ListItem>
    <asp:ListItem Value="OH">Ohio</asp:ListItem>
    <asp:ListItem Value="OK">Oklahoma</asp:ListItem>
    <asp:ListItem Value="OR">Oregon</asp:ListItem>
    <asp:ListItem Value="PA">Pennsylvania</asp:ListItem>
    <asp:ListItem Value="RI">Rhode Island</asp:ListItem>
    <asp:ListItem Value="SC">South Carolina</asp:ListItem>
    <asp:ListItem Value="SD">South Dakota</asp:ListItem>
    <asp:ListItem Value="TN">Tennessee</asp:ListItem>
    <asp:ListItem Value="TX">Texas</asp:ListItem>
    <asp:ListItem Value="UT">Utah</asp:ListItem>
    <asp:ListItem Value="VT">Vermont</asp:ListItem>
    <asp:ListItem Value="VA">Virginia</asp:ListItem>
    <asp:ListItem Value="WA">Washington</asp:ListItem>
    <asp:ListItem Value="WV">West Virginia</asp:ListItem>
    <asp:ListItem Value="WI">Wisconsin</asp:ListItem>
    <asp:ListItem Value="WY">Wyoming</asp:ListItem>
</asp:DropDownList>

asp:DropDownList with Abbreviate States

<asp:DropDownList ID="ddlStates" runat="server">
    <asp:ListItem value="AK">AK</asp:ListItem>
    <asp:ListItem value="AL">AL</asp:ListItem>
    <asp:ListItem value="AR">AR</asp:ListItem>
    <asp:ListItem value="AZ">AZ</asp:ListItem>
    <asp:ListItem value="CA">CA</asp:ListItem>
    <asp:ListItem value="CO">CO</asp:ListItem>
    <asp:ListItem value="CT">CT</asp:ListItem>
    <asp:ListItem value="DC">DC</asp:ListItem>
    <asp:ListItem value="DE">DE</asp:ListItem>
    <asp:ListItem value="FL">FL</asp:ListItem>
    <asp:ListItem value="GA">GA</asp:ListItem>
    <asp:ListItem value="HI">HI</asp:ListItem>
    <asp:ListItem value="IA">IA</asp:ListItem>
    <asp:ListItem value="ID">ID</asp:ListItem>
    <asp:ListItem value="IL">IL</asp:ListItem>
    <asp:ListItem value="IN">IN</asp:ListItem>
    <asp:ListItem value="KS">KS</asp:ListItem>
    <asp:ListItem value="KY">KY</asp:ListItem>
    <asp:ListItem value="LA">LA</asp:ListItem>
    <asp:ListItem value="MA">MA</asp:ListItem>
    <asp:ListItem value="MD">MD</asp:ListItem>
    <asp:ListItem value="ME">ME</asp:ListItem>
    <asp:ListItem value="MI">MI</asp:ListItem>
    <asp:ListItem value="MN">MN</asp:ListItem>
    <asp:ListItem value="MO">MO</asp:ListItem>
    <asp:ListItem value="MS">MS</asp:ListItem>
    <asp:ListItem value="MT">MT</asp:ListItem>
    <asp:ListItem value="NC">NC</asp:ListItem>
    <asp:ListItem value="ND">ND</asp:ListItem>
    <asp:ListItem value="NE">NE</asp:ListItem>
    <asp:ListItem value="NH">NH</asp:ListItem>
    <asp:ListItem value="NJ">NJ</asp:ListItem>
    <asp:ListItem value="NM">NM</asp:ListItem>
    <asp:ListItem value="NV">NV</asp:ListItem>
    <asp:ListItem value="NY">NY</asp:ListItem>
    <asp:ListItem value="OH">OH</asp:ListItem>
    <asp:ListItem value="OK">OK</asp:ListItem>
    <asp:ListItem value="OR">OR</asp:ListItem>
    <asp:ListItem value="PA">PA</asp:ListItem>
    <asp:ListItem value="RI">RI</asp:ListItem>
    <asp:ListItem value="SC">SC</asp:ListItem>
    <asp:ListItem value="SD">SD</asp:ListItem>
    <asp:ListItem value="TN">TN</asp:ListItem>
    <asp:ListItem value="TX">TX</asp:ListItem>
    <asp:ListItem value="UT">UT</asp:ListItem>
    <asp:ListItem value="VA">VA</asp:ListItem>
    <asp:ListItem value="VT">VT</asp:ListItem>
    <asp:ListItem value="WA">WA</asp:ListItem>
    <asp:ListItem value="WI">WI</asp:ListItem>
    <asp:ListItem value="WV">WV</asp:ListItem>
    <asp:ListItem value="WY">WY</asp:ListItem>
</asp:DropDownList>

Or if you use Telerik controls like I do… then the RadComboBox is for you

<telerik:RadComboBox ID="RadComboBox1" runat="server">
    <Items>
        <telerik:RadComboBoxItem value="AK" Text="AK" />
        <telerik:RadComboBoxItem value="AL" Text="AL" />
        <telerik:RadComboBoxItem value="AR" Text="AR" />
        <telerik:RadComboBoxItem value="AZ" Text="AZ" />
        <telerik:RadComboBoxItem value="CA" Text="CA" />
        <telerik:RadComboBoxItem value="CO" Text="CO" />
        <telerik:RadComboBoxItem value="CT" Text="CT" />
        <telerik:RadComboBoxItem value="DC" Text="DC" />
        <telerik:RadComboBoxItem value="DE" Text="DE" />
        <telerik:RadComboBoxItem value="FL" Text="FL" />
        <telerik:RadComboBoxItem value="GA" Text="GA" />
        <telerik:RadComboBoxItem value="HI" Text="HI" />
        <telerik:RadComboBoxItem value="IA" Text="IA" />
        <telerik:RadComboBoxItem value="ID" Text="ID" />
        <telerik:RadComboBoxItem value="IL" Text="IL" />
        <telerik:RadComboBoxItem value="IN" Text="IN" />
        <telerik:RadComboBoxItem value="KS" Text="KS" />
        <telerik:RadComboBoxItem value="KY" Text="KY" />
        <telerik:RadComboBoxItem value="LA" Text="LA" />
        <telerik:RadComboBoxItem value="MA" Text="MA" />
        <telerik:RadComboBoxItem value="MD" Text="MD" />
        <telerik:RadComboBoxItem value="ME" Text="ME" />
        <telerik:RadComboBoxItem value="MI" Text="MI" />
        <telerik:RadComboBoxItem value="MN" Text="MN" />
        <telerik:RadComboBoxItem value="MO" Text="MO" />
        <telerik:RadComboBoxItem value="MS" Text="MS" />
        <telerik:RadComboBoxItem value="MT" Text="MT" />
        <telerik:RadComboBoxItem value="NC" Text="NC" />
        <telerik:RadComboBoxItem value="ND" Text="ND" />
        <telerik:RadComboBoxItem value="NE" Text="NE" />
        <telerik:RadComboBoxItem value="NH" Text="NH" />
        <telerik:RadComboBoxItem value="NJ" Text="NJ" />
        <telerik:RadComboBoxItem value="NM" Text="NM" />
        <telerik:RadComboBoxItem value="NV" Text="NV" />
        <telerik:RadComboBoxItem value="NY" Text="NY" />
        <telerik:RadComboBoxItem value="OH" Text="OH" />
        <telerik:RadComboBoxItem value="OK" Text="OK" />
        <telerik:RadComboBoxItem value="OR" Text="OR" />
        <telerik:RadComboBoxItem value="PA" Text="PA" />
        <telerik:RadComboBoxItem value="RI" Text="RI" />
        <telerik:RadComboBoxItem value="SC" Text="SC" />
        <telerik:RadComboBoxItem value="SD" Text="SD" />
        <telerik:RadComboBoxItem value="TN" Text="TN" />
        <telerik:RadComboBoxItem value="TX" Text="TX" />
        <telerik:RadComboBoxItem value="UT" Text="UT" />
        <telerik:RadComboBoxItem value="VA" Text="VA" />
        <telerik:RadComboBoxItem value="VT" Text="VT" />
        <telerik:RadComboBoxItem value="WA" Text="WA" />
        <telerik:RadComboBoxItem value="WI" Text="WI" />
        <telerik:RadComboBoxItem value="WV" Text="WV" />
        <telerik:RadComboBoxItem value="WY" Text="WY" />
    </Items>
</telerik:RadComboBox>