Saturday, October 15, 2011

How to Resolve The name 'xxx' does not exist in the current context Issue

Yesterday I was working on a page which contains Ajax Toolkit Tab Container, and there were some control on the other tab.
When i build my ASP.NET (C#) project in Visual Studio 2010, i started getting this error message

"The name 'XXXX' does not exist in the current context"

Displayed and the problem is in my .aspx page. Most surprisingly I can access the control in Intellisens but while compile time it throw error. My code definitely has no problem.

After debugging and searching for a while, i noticed that problem is cause by the back up copy of the same aspx file (copy of xxxx.aspx) that i forget to exclude from the project.

The problem solved after i exclude the file from the project.

Sunday, September 25, 2011

Itrarting Bewteen Date Range using Foreach C#.

There are some situation when we want to itrate trough a range of date.
Hear is ample how you can itrates through the date range using foreach in C#

for itrating you will need to first create a function which will convert the date range in inumaration formate so that you can itrates.

For this i have created the follwing function.

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1)) yield return day;

Now you can use the code like this.

foreach (DateTime day in EachDay(strartDate, EndDate)
 //Do something


Tuesday, September 20, 2011

Hosting WCF Service in IIS

Create a WCF service

1. Create a blank solution and add a WCF Service Library project to it. For the purpose of this post, I am going to create a simple GreetingService that has a method Greet. This method accepts a single parameter name and returns a string “Hello “ appended to name

2. The following is the code for the GreetingService WCF service. We define a service contract, mark the operations in that contract that are going to be exposed to the external world and then implement the service.

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace Wcf.Samples.ServiceLibrary
    public interface IGreeting
        string Greet(string name);


using System;
using System.Collections.Generic;
using System.Text;

namespace Wcf.Samples.ServiceLibrary
   public class GreetingService : IGreeting
      #region IGreeting Members
      public string Greet(string name)
         return "Hello - " + name;

3. Now that you added the service contract and its implementation (the GreetingService), build the project.

Host the service in IIS

1. Now we create a Web site that will host the WCF service that we created in the previous section. For this, right-click the solution in the solution explorer and from the context menu, select Add -> New Web site ->WCF Service as shown in the following figure.

2. This will create a WCF Service Web site into your solution along with the standard folders that get created for a Web site project (App_Code, App_Data etc). A new type of file called Service.svc will be generated and placed into the root of the Web site project, along with the corresponding code-behind file (Service.cs). The Service.cs is provided to implement a WCF service, which then can be referred in the Service.svc file. Since we already have created the WCF service in a separate assembly, we will refer to it in the Service.svc. As such we don’t need Service.cs and hence, it can be deleted.

3. Open Service.svc file and modify the single line in it like this:

4. In the above statement we point to the fully-qualified class name that implements the service that we want to host in IIS.

5. Add the reference of the Wcf.Samples.ServiceLibrary project to the web-site project and build the web-site.

6. This completes the creation of WCF service. Now, in order to let the service communicate with the external world, we need to define the communication behavior of the service. For defining this behavior, we will use the Service Configuration tool that comes along with Visual Studio 2005.

7. From the main menu of Visual Studio 2005, select Tools -> WCF Service Configuration Editor. The WCF Configuration Editor window will open up. Select File -> Open -> Config File… from the main menu. Browse and select the Web.config file of the WCF web-site.

8. Once selected, the screen will be displayed as follows. The Web.config already has the configuration for the default service MyService under the Services node in the left-panel. Select this service and deleted it. We are going to create a new configuration for our service.

9. Right-click the Services node and select “New service” from the context menu. A service with service type NewServiceType will be created. On the right-panel, select the property “Name” and click the ellipsis. Service Type Browser will open up. Browse the bin folder of the web-site and locate the service assembly Wcf.Samples.ServiceLibrary and double-click it. The Service Type Browser dialog now will list the service “Wcf.Samples.ServiceLibrary.GreetingService” service. Select this service and click Open. This will set the service-type that we are going to configure.

10. Now for the above service, we first need to specify the end-point. Right-click Endpoints node in the left-panel of the WCF Service Configuration Editor and select “New Endpoint”. This will create a default end-point with its properties being displayed in the right-panel.

11. Set the following properties:



· Here 28053 is the port-number where the local web-server is running. You need to check your port number and enter it here appropriately.



· You can click the ellipses to open the Contract Type Browser and select the appropriate assembly and contract from the bin directory of the web-site.

12. This sets the basic communication for our service. In order to enable the service for metadata exchange (thereby allowing us the browse its wsdl), we need to set the metadata exchange properties for the service. To do this, expand the Advanced node in the left-panel, right-click Service Behaviors and select “New Service Behavior Configuration”. This will add a new Behavior Configuration by the default name NewBehavior. Behavior is a collection of attributes (here, service attributes) that can be set and applied to the service together. Right now, we are going to define a behavior that allows the metadata exchange on the service. Set the Name property of the new behavior configuration to mexBehavior.

13. In the “Behavior element extension position” (lower part of the right-panel), click “Add” button. This opens up a dialog “Adding Behavior Element Extension Sections”. Select serviceMetadata from the list and click “Add” on the dialog. This adds the extension serviceMetadata to the grid in the right-panel. Double-click the extension to open up its property-page. Set the property HttpGetEnabled to true.

14. Now that we have defined the behavior separately, we need to associate the behavior with our service. To do this, select the Wcf.Samples.ServiceLibrary.GreetingService under the Services node in the left panel. The right-panel will display its properties. Select the BehaviorConfiguration property, and select “mexBehavior” from the drop-down.

15. This sets the service configuration and allows the service to communicate with the external world. Save the configuration by selecting the menu File->Save. Close the WCF Service Configuration Editor.

16. Test that the service is hosted by running the WCF Web Site application. The following screen should be displayed.

Sunday, August 14, 2011

Placing Update Progress Control dynamically

Contextual Links

f you're using AJAX UpdateProgress control, you may find it difficuilt to set the best position where you should put it on the page, because user will not see it if he scrolls down (or up) from it. Here is a simple solution which will make your UpdateProgress more user-friendly, because it will set the position on the screen according to user's movement of the mouse. And you will prevent user to click on any button until the postback finishes execution. 

here is the code place the below code in JavaScript SCRIPT LANGUGE=JAVASCRIPT tag, ending with appropriate closing tag

    function SetProgressPosition(e)
      var posx = 0;
      var posy = 0;
       if (!e) var e = window.event;
       if (e.pageX ||  e.pageY) 
          posx = e.pageX;
          posy = e.pageY;
    else if (e.clientX || e.clientY) 
         posx = e.clientX + document.documentElement.scrollLeft;
         posy = e.clientY + document.documentElement.scrollTop;
    document.getElementById('divProgress').style.left = posx - 8 + "px";
    document.getElementById('divProgress') = posy - 8 + "px";

the on boy tag plave the code as body onmousemove="SetProgressPosition(event)"
Now place your updateProgress bar tag as (Note : each line has starting < and ending > Kidly include the same in each line)
asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100"
   div class="overlay" id="divProgress"
        Please wait...
      br /
         asp:Image GenerateEmptyAlternateText="true" ID="Image1" runat="server" ImageUrl="~/ajax-loader.gif" Style="margin-top: 7px;" /


As you can see, most important part is javascript which is responsible for the movement of the UpdateProgress. That javascript is triggered with the "onmousemove" part of the body tag. In order to set UpdateProgress style, use this styel sheet:
 border: black 1px solid;
 padding: 5px;
 z-index: 100;
 width: 100px;
 position: absolute;
 background-color: #fff;
-moz-opacity: 0.75;
 opacity: 0.75;
 filter: alpha(opacity=75);
 font-family: Tahoma;
 font-size: 11px;
 font-weight: bold;
 text-align: center;


As you can see, there is a part which makes UpdateProgress semi-transparent, which will make it look even better. 

And that's all, very simple, but very effective!
 Code in Action

How to Change your Office 2007 Product Key:

Are you looking to change a Microsoft Office 2007 product license key, serial number or CD key? One common method used to change the product key for 2007 Microsoft Office programs or suites is to uninstall or remove Microsoft Office and then reinstall the program. Another approach is to edit your registry, reset and change the product serial key without uninstalling and reinstalling 2007 Office system suites.

1. Click Start -> Run
2. Type regedit in the box and click OK
3. Navigate to the following path:
HKEY_LOCAL_MACHINE \Software\Microsoft\Office\12.0\Registration
Within Registration, there is subkey that may resemble the following:
4. Under Registration, you might find several subkeys that contain a combination of alphanumeric characters. Each key is specific to a program installed on your computer.Open each subkey to view and identify the Office product version by the ProductName registry entry in the right pane. For example:
ProductName=Microsoft Office Professional Plus 2007
Once you have located the subkey that contains the Office product you wish to change the license key for, delete the following registry entries by right clicking on the registry entry in the subkey, click Delete, and select 
7. Close regedit
8. Start Microsoft Word, Excel, Outlook or another Office application. Office 2007 should now prompt you to enter a new 25 character product key
Enter a valid product key, and click OK
9. If prompted to choose your preferred type of Microsoft Office 2007 installation, select Install Now
10. Microsoft Office 2007 should now be updated with your new CD key

Get offline maps for your Mobile (work with GPS/without GPS)

Here's a tutorial which will guide you that how to get Google Map Offline on you Java Enabled phone. This works in most of the SE phones which have Java MIDP 2.0. While writing i assume that you are already familiar with Installing games, applications and transferring files to your phone from the PC.You Need: 
A PC with internet connection.
Windows XP/Vista (not tried with others)
USB Chord of your SE phone.

Step 1:You need the application of Mini-Google-Maps (mgmaps for short)

Choose "Stable (v1.3x)" and platform "Generic"
Click on [jar] as we are going to use SE mobile phones, [jad] file is not required. You will now be asked to save the file. Please save it on your desktop (makes things easier )

Step 2:
Now we need the map "tiles" which comprise the maps used by mgmaps.
To download these, and a custom area map, you need a tool called gMapMaker. (You need MS .NET Framework v2.0 to run gMapMaker)

Step 3:

Now we need to create a map file for a custom area.
here and use the tool to create a ".map" file. Save this to your desktop too.

1. Find the area that You want to get a map of.
2. Draw a line around the area that You want mapped, by placing markers around in sequence. A single click places a marker, a click on a marker removes it. It is also possible to drag markers around after they have been placed.
3. Specify zoom levels, map type, and detail level. WARNING: The maximum detail level can freeze Your browser for upto 5 minutes, depending on the complexity of the shape and other factors.
4. Press the "Generate!" button. Wait for the script to generate everything. As a side note, Mozilla Firefox does the processing much much faster than IE does.

Be careful and do not select a huge map size. Also select a modest zoom level. Level 17 is not needed, it will just clog up your memory.
Step 4:
Now open gMapMaker.
You should see something like this (the fields may differ)
In "operating mode" select "MGMaps mode use a .map file"
Click on "Go.." You will now be asked for the .map file which was saved on the desktop. Select it. gMapMaker will now download the tiles of your map. Please be patient, this can take a while.
Step 5:
A folder should be created in "C:/Program Files/gMapMaker"(Windows XP) Or "C:/Desktop" (Windows Vista)

It will contain another folder "MGMapsCache". Copy this to your memory card or phone memory (If it has enough space)
Step 6:
Now install the application "mgmaps.jar" in your mobile phone the usual way. Start the application. Go to menu->settings->map browsing
Mark the fields of "Stored Maps" and "Offline mode"
If your maps are inside the phone memory, Put the storage path as "C:/MGMapsCache", or if your maps are in the memory card put it as "E:/MGMapsCache". Select more->save
Restart the application. Press till it shows "Google Maps"
If it does not show even after pressing repeatedly, go to menu->settings->map types. Here you will find something as "Not Available(Google)" Select it and mark "Google Maps"
The maps should now be seen.

Dwongrading form Vista to XP

Step 1.
Download the SATA Driver from your Vendor site of from Intel
Extract the file to a floppy or other location using third party tool. (Do a google for extracting) it should have the follwing files on extracted location.

Step 2. Create a folder on harddisk with same name as of XP Cd, Copy the content of our CD to your hard disk (Lets Say c:\winxp_vol)

Step 3. 
Navigate to c:\winxp_vol\i386, Open txtsetup.sif in notepad
Find [SourceDisksFiles] Scroll to he last entry of this section. Add the follwing to the last line.
Step 3. Open the txtSetup.oem from extracted folder (or Floppy Drive).
Step 4. Search for [HardwareIds.scsi.iaStor_ICH8M]
Step 5. Open txtsetup.sif and Find [HardwareIdsDatabase] Scroll to the last record under [hardwareIdsdatabase] and paste each ID so it looks like the following.
entry3 etc....

Step 6. Next we need to find [Scsi.Load] scroll down to the last entry and add the following to the bottom a[Scsi.Load]
Next Find [SCSI] scroll down to the bottom again and add the following
iastor = "Intel(R) 82801HEM SATA RAID Controller (Mobile ICH8M-E)"
iastor = "Intel(R) 82801HEM/HBM SATA AHCI Controller (Mobile ICH8M-E/M)"
iastor = "Intel(R) 82801HR/HH/HO SATA RAID Controller (Desktop ICH8R)"
iastor = "Intel(R) 82801HR/HH/HO SATA AHCI Controller (Desktop ICH8R)"
iastor = "Intel(R) 631xESB/632xESB SATA RAID Controller (Server/Workstation ESB2)"
iastor = "Intel(R) 631xESB/632xESB SATA AHCI Controller (Server/Workstation ESB2)"
iastor = "Intel(R) 82801GHM SATA RAID Controller (Mobile ICH7MDH)"
iastor = "Intel(R) 82801GR/GH SATA RAID Controller (Desktop ICH7R/DH)"
iastor = "Intel(R) 82801GR/GH SATA AHCI Controller (Desktop ICH7R/DH)"
iastor = "Intel(R) 82801GBM SATA AHCI Controller (Mobile ICH7M/DH)"
iastor = "Intel(R) 82801FR SATA RAID Controller (Desktop ICH6R)"
iastor = "Intel(R) 82801FR SATA AHCI Controller (Desktop ICH6R)"
iastor = "Intel(R) 82801FBM SATA AHCI Controller (Mobile ICH6M)"
Replacce the name of the driver with Iastor for each driver see above.

Save txtSetup.sif
Step 7. Create a folder like c:\winxp_vol\$OEM$\$1\Drivers\SATA
Copy the extracted file to this folder

Step 8. The iastor.sys need to be made into a cab. for this run the command from command prompt
Makecab C:\CDNAME\$OEM$\$1\Drivers\SATA\iastor.sys C:\CDNAME\$OEM$\$1\Drivers\SATA\iastor.sy_
you can now delete the file iastor.sys.
In the C:\CDNAME\$OEM$\$1\Drivers\SATA you should now have the following files

Step 9. Copy the iastor.sy_ into c:\winxp_vol\i386 folder.
Step 10. Open dosnet.inf in notepad (This is locted at c:\winxp_vol\i386 folder)
Step 11. FIND [Floppy.Files2] and copy the following "d1,iastor.sys" directly underneath
like so

Do the same for [Files]

Save dosnet.inf

Step 12. Open Notepad and enter

Save the file in C:\CDNAME\i386 called winnt.sifwe now have the edited CD.
Final Step. Save the contenet as bootable iso image and burn using any birning engine. Make sure to make the image as bootable XP image, You can download the boot image from Microsoft or other engine.
Insert the CD and reboot you machine now you will be able to install Windows XP without problem.
If you face any problem, Please post acomment or write to me.

Happy Installing....

How to get GPRS on windows Mobile

GPRS are most commom these days, but unfortunaltly getting GPRS on windows mobile is very tedeous. I get GPRS working on my Windows Mobile with very tedeous process.
To get the GPRS working on my phone i made a lot of call to customer care of my mobile operator, but they have no clear way to get it working on my moble, The setting send by mobile operator was not working and get discared.
So i decide to compile the step to get the GPRS working on my Windows Mobile with Vodafone India.
Here are the steps
1. Get GPRS activated on your SIM by calling the Customer Care.
2. Go to Start --> Setting
3. Tap the connections TAB.
4. Select Connection.
5. Select New Modem Connection.
6. Enter Name for connection.
7. Select a mode as Celllar line (GPRS)
8. Enter Access Point name www.
9. Click Finish.
10. Click Ok the OK to return banck to main screen.
11. Select Managemy Proxy Server.
12. Enter in the Proxy Sever Box.
13. Select Advance
14. Select HTTP and enter and port name 9201.
15. Enter and port name 9201 in WAP, Secure WAP, and SOCKS
16. Click OK.
17. Yoy are done.

Enjoy GPRS on you windows Mobile.

Detecting Post Back in Through Javascript

Some time we need to do some functionality in a page using JavaScript when page load for the first time only, The best way to do is to detect Post back and then perform the functionlaity in JavaScript.
Here is the way to achive.
Place the following code in javaScript block

 window.onload = isPostBack;    function isPostBack()    
  var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
       if(chkPostBack == 'false')
        alert('Page loaded First Time');
         alert('Post back');
Happy Coding...

How to change the Volume Licensing product key of Windows XP

Steps to change the volume licensing product key

This article describes two methods for how to change the Windows XP product key after a Volume Licensing installation to resolve the issue. One method uses the Windows Activation Wizard graphical user interface (GUI) and the other method uses a Windows Management Instrumentation (WMI) script. The Activation Wizard method is easier. However, if you must change the product key for multiple computers, the script method is more suitable.

Method 1: Use the Activation Wizard

Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
322756  ( ) How to back up and restore the registry in Windows
If you only have a few volume licensing product keys to change, you can use the Activation Wizard.

Note We recommend that you run System Restore to create a new restore point before you follow these steps.
Deactivate Windows

  1. Click Start, and then click Run.
  2. In the Open box, type regedit, and then click OK.
  3. In the navigation pane, locate and then click the following registry key:
    HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\Current Version\WPAEvents
  4. In the topic pane, right-click OOBETimer, and then click Modify.
  5. Change at least one digit of this value to deactivate Windows.
Reactivate Windows and add new product key

  1. Click Start, and then click Run.
  2. In the Open box, type the following command, and then click OK.
    %systemroot%\system32\oobe\msoobe.exe /a
  3. Click Yes, I want to telephone a customer service representative to activate Windows, and then clickNext.
  4. Click Change Product key.
  5. Type the new product key in the New key boxes, and then click Update.

    If you are returned to the previous window, click Remind me later, and then restart the computer.
  6. Repeat steps 1 and 2 to verify that Windows is activated. You receive the following message:
    Windows is already activated. Click OK to exit.
  7. Click OK.
  8. Install Windows XP Service Pack 1a or a later version of Windows XP.
If you cannot restart Windows after you install Windows XP SP1 or a later version of Windows XP, try the following steps:
  1. Restart your computer and start pressing F8 until you see the Windows Advanced Options menu.
  2. Select Last Known Good Configuration from the menu and press ENTER. This option starts Windows by using a previous good configuration.
  3. Repeat steps 1 through 8 under "Reactivate Windows and add new product key."
If you can install SP1 or a later version of Windows XP and you can restart Windows, you have resolved the issue. If the issue has not been resolved, try method 2 or see the "Next Steps" section for more troubleshooting resources.

Using CASE to transform a result set from multiple rows into a summary row

 Consider the situation where sales data is stored in a table by month. One row is stored per month with a table structure that looks like the following:
CREATE TABLE prodsales
 (product char(3),
  mnth    smallint,
  sales   money)

In this table, sales amounts (sales) are stored by month (mnth) and product code (product). The mnth column stores an integer value ranging from 1 (for January) to 12 (for December). You can use the following single SQL statement to product one row per product with 12 totals, one for each month:

SQL Statement will go like this

SELECT product,
  SUM(CASE mnth WHEN 1 THEN sales ELSE NULL END) AS jan,
  SUM(CASE mnth WHEN 2 THEN sales ELSE NULL END) AS feb,
  SUM(CASE mnth WHEN 3 THEN sales ELSE NULL END) AS mar,
  SUM(CASE mnth WHEN 4 THEN sales ELSE NULL END) AS apr,
  SUM(CASE mnth WHEN 5 THEN sales ELSE NULL END) AS may,
  SUM(CASE mnth WHEN 6 THEN sales ELSE NULL END) AS jun,
  SUM(CASE mnth WHEN 7 THEN sales ELSE NULL END) AS jul,
  SUM(CASE mnth WHEN 8 THEN sales ELSE NULL END) AS aug,
  SUM(CASE mnth WHEN 9 THEN sales ELSE NULL END) AS sep,
  SUM(CASE mnth WHEN 10 THEN sales ELSE NULL END) AS oct,
  SUM(CASE mnth WHEN 11 THEN sales ELSE NULL END) AS nov,
  SUM(CASE mnth WHEN 12 THEN sales ELSE NULL END) AS dec
FROM prodsales
GROUP BY product  
This statement will generates a row for each product with twelve monthly sales totals. The CASE expression causes the sales amount to by added to the appropriate bucket by checking the mnth column. If the month value is for the appropriate “month bucket”, then the sales amount is added using SUM; if not, then NULL is specified, thereby avoiding adding anything to the SUM. Using CASE expressions in this manner simplifies aggregation and reporting. It provides a quick way of transforming normalized data structures into the more common denormalized formats that most business users are accustomed to viewing on reports.
Happy Coding :)

Placing Google Adsense to your each post, (

Placing Google Adsense to your each post, (
When my Google Adesne approved, i had tried a lot of variation and did code alteration, so that my Adsense Ad appear in my each post. After doing a varity of code variation found a very simple way to implemet this.
To make this easy for all of you i am sharing my method with you all.
1. Get you adesnes code in any text editor, like Notepad.
2. Navigate to theme/<yourthema>/PostView.ascx
3. Edit the PostView.ascx
4. Find out the "PlaceHolder ID="BodyContent" runat="server" tag
5. Paste your Adsens Code just below this tag.(Please note that the script should after PlaceHolder tag and before the closing of div tag
6. Save the code. an dthat 's it.
Enjoy the injection of you Google Adsense Ad to your each post automatically,
Note: As this is an ASCX page you can download the page, edit on your local machine the upload to you site. No need to recompile and republish the entire site.

Method Overloading in Web Services

By default Web Services do not support ‘Method Overloading’.

When data is passed to an XML Web service it is sent in a request and when it is returned it is sent in a response. Therefore, if an XML Web service contains two or more XML Web service methods with the same name, no uniquely identification will be there. Hence it will produce error
To implement method overloading in webservices first you must set the MessageNameattribute of your webservice then set your webservice binding ConformsTo attribute toWsiProfiles.None and that’s it! Note that you can do second step in your Web.Config file for all webservices.
Below is an exaple to implement, Overloading in web service.
Modify the attribute as:
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
   Complete Code:

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
public class Service : System.Web.Services.WebService
    public Service () {

    public string HelloWorld()
        return "hello";

    [WebMethod(MessageName = "HelloWorld2")]
    public string HelloWorld(int i)
        return "Overloading";

VSTS 2010 for Architect

Designing new functionality on existing applications can be daunting.  There are always differences between the original design and the current implementation. 

The new Architecture tools within Visual Studio Team System 2010 help you understand the application you have, design new functionality you need, and validate that your design and your implementation do not deviate.

Understanding What You Have
Understanding the dependencies between parts of your application can be critical to determining where you may have problems.  Additionally, having a visual graph can help you find the best place to implement new functionality. 

You can get a big picture view of your solution by assembly, namespace, class or a custom filter in a Directed Graph Markup Language document (DGML) using the Generate Dependency Graph feature:
Generate Dependency Graph

The DGML document generated from your solution can be visualized as a Dependency Matrix, Force Directed Layout, or as a Top to Bottom layout, as shown below.  Each view can provide a different take on the structure of your project.

Top to Bottom Layout

This high-level view is a great way to understand the overall shape of your architecture, but understanding the dependencies for an area you need to change can make the difference between a fifteen-minute change and a one-hour change.  For instance, being able visualize the relationships around the Cart class can be very helpful in making changes to the shopping cart:

Cart Class 

Another valuable way of understanding how your application works is to be able to visualize the sequence of calls that happen in key sections of your application.  The Generate Sequence Diagram function, available in the code editor, will give you a view of the method calls your application makes.  Below, you can see the sequence of calls that make up the Add method implementation within the shopping cart. 

Sequence diagram 

Designing New Functionality
Now that you have a more complete understanding of your existing application, you are in a better position to add functionality.  Collaborating on design requires communicating in a standard way. Unified Modeling Language (UML) diagrams allow you to express your design in a way that others can understand.  For instance, you can build UML Component and Class diagrams that describe the existing structural elements of your design, then add new elements to the diagrams to illustrate and document your changes.  Below is how a completed Component diagram might look:

Component Diagram
A Class diagram might look like this:

Class Diagram

The Use Case diagram below enables teams to better understand and agree on the functions of the application.

Use Case Diagram 
Once you have a UML diagram, you can create or link designer elements to work items within Team Foundation Server’s (TFS) Work Item Tracking system. 

TFS Integration 

Ensuring Application Validation
Over time, the code quality of a project can degrade if bug fixes and new feature implementations are not done with overall architecture in mind.  This is where the Layer designer and Layer validation can help.  The Layer designer enables you to define the logical layers and valid communication paths between layers of your project.  Once you have associated assemblies, namespaces, and classes with layers in the Layer diagram, you can validate existing or new code against the layering constraints.  For example, in this Layer diagram, it is valid for software within thePresentation layer to have dependencies on software within the Business Logic layer.  However, since there is not a dependency line between Presentation and Resource Access, any software that attempts to take that dependency would cause a compile-time violation in the Error List.   

Layer Diagram

You can validate layer constraints from the designer surface, command line, or from within the build process. Team Build’s gated check-in process ensures that layer constraint violations never make it into source control. 

Thread safe singleton Pattern

.NET is multithreaded meaning that more than one thread can execute our Singleton concurrently. This means that we never know—and don't usually care—that our thread may be starting and stopping with other threads running in the gaps.
The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance.
Singleton is lazily - i.e. that the instance isn't created until it is first needed.
The four common characteristics of a singleton are

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

Singleton Implementation

public sealed class Singleton
    static Singleton instance=null;

    public static Singleton Instance
            if (instance==null)
                instance = new Singleton();
            return instance;

Please note that the above implementation is not thread safe. Means to say that if Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Thread safe Singleton implementation.
public sealed class Singleton
    static Singleton instance=null;
    static readonly object padlock = new object();
    public static Singleton Instance
            lock (padlock)
                if (instance==null)
                    instance = new Singleton();
                return instance;

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

thread-safety using double-check locking
public sealed class Singleton
    static Singleton instance=null;
    static readonly object padlock = new object();
    public static Singleton Instance
            if (instance==null)
                lock (padlock)
                    if (instance==null)
                        instance = new Singleton();
            return instance;

implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.
thread-safe without using locks
public sealed class Singleton
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()


    public static Singleton Instance
            return instance;
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)
fully lazy instantiation
public sealed class Singleton

    public static Singleton Instance
            return Nested.instance;
    class Nested
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()

        internal static readonly Singleton instance = new Singleton();

Related Posts Plugin for WordPress, Blogger...