Search This Blog

Dec 19, 2012

SqlParameter in

I have a web service, so the handler is called multiple times concurrently all the time.

Inside I create SqlConnection and SqlCommand. I have to execute about 7 different commands. Different commands require various parameters, so I just add them once:

How to Add Meta Description and Keywords to Blogger:

How to Add Meta Description and Keywords to Blogger:
  •     Login to your blogger blog
  •     Goto Design and after that Edit Html
  •     Add the following code
<meta content=’your description here’ name=’description’/>

<meta content=’your keywords here’ name=’keywords’/>

Click Save Template. Now you added meta tags to your blogger blog. The description and keywords will be showed on every posts.

How to Add Unique Meta Description and Keywords to Blogger:

Just Change the code like this :-
Add Meta Description:

<meta expr:content=’data:blog.pageName + data:blog.title + data:blog.pageName’ name=’Description’/>

The above code will add your Blog post’s title and Blog title as your Meta description of blog posts.
Add Meta Keywords:

<meta expr:content=’data:blog.pageName + data:blog.title + data:blog.pageName’ name=’Keywords’/>

The above code will add your Blog post’s title and Blog title as your post’s Meta Keywords.

The unique meta description / keywords / tags for blogger blog should improve your blog post’s search engine rankings. But, keep in mind don’t add many title tag in your meta description. Because, this may be  irritate your post.

How to connect to an external SQL server database in ASP.NET / VB.NET / .NET

Connecting to databases in .NET is different if you are coming from other languages such as PHP. To connect to a database in ASP.NET / .NET in general, you use "Connection Strings" that essentially is the connection information to the database.

First and foremost, in your code behind file within an ASP.NET application (or simply the .vb or .cs file of your .NET desktop application), you will need to first import the namespace that has the relevant database-related classes and methods, etc.

Dec 7, 2012

Static classes

C# 2.0 now supports static classes. Here are static classes properties.

1) A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator.
2) A static class is a sealed class. That means you cannot inherit any class from a static class.
3) A static class can have static members only. Having non-static member will generate a compiler error.
4) A static class is less resource consuming and faster to compile and execute.

C# Event Handlers and Delegates

C# Event Handlers and Delegates in ASP .Net with Web User Controls

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Create event handlers and their delegates in the user control, fire them from the methods tied to the internal controls protected events, and define the methods that will handle the new events in the page (see code below).

This article should help as a general how to on event handlers and delegates in C# as well as propose a different way to handle cross page methods in your ASP .Net website from a web user control or other page.

Dec 2, 2012

How to migrate your ASP.NET site to the Azure cloud

Cloud computing is one of the hot topics of 2011 with those willing to make the jump to a cloud-based solution finding financial savings in this new approach as well as, in many cases, better fault tolerance and a more responsive service turnaround in many cases. However, what many developers may not realise is just how straightforward it can be to migrate a web site from a local or hosted server into the cloud.

To demonstrate, this article will show you how to upgrade and deploy an existing ASP.NET 3.5 or 4.0 web application to the Windows Azure cloud platform.

We will cover:
  1. The SDKs and tools to be installed on your machine before you can continue
  2. How to set up your Windows Azure instance in preparation for the application
  3. How to alter the application so that it will function in the cloud
  4. How to deploy the application to Windows Azure

Nov 30, 2012

String.Format in Asp.Net (PART-2)

Culture Information

string.format also provides a method which accepts a CultureInfo argument, as an IFormatProvider. This is important when trying to write portable and localisable code, as, for example, month names will change according to the local culture of the machine you are running on. Rather than simply call the standard String.Format you should consider always calling the overloaded culture method. If you don't need to specify a culture you can use the System.Globalization.CultureInfo.InvariantCulture. This will then default your formatting to English, as opposed to the culture of the current thread.

String.Format in Asp.Net (PART-1)

Formatting Strings

There's not much formatting that can be applied to a string. Only the padding / alignment formatting options can be applied. These options are also available to every argument, regardless of type.
example output
String.Format("--{0,10}--", "test"); --      test--
String.Format("--{0,-10}--", "test"); --test      --

ArrayList in

The ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.

The following code creates a new ArrayList object named books and three items are added:
  ArrayList books = new ArrayList();

Nov 29, 2012

How to create MVC (model view controller) views faster by using HTML helper classes

MVC using HTML helper classes 

<table width="50%" runat="server" id="tbl1">
    <td>Student Id:</td>
    <td><asp:TextBox runat="server" ID="txt1"></asp:TextBox></td></tr>
    <td>Student Name:</td>
    <td><asp:TextBox runat="server" ID="txt2"></asp:TextBox></td></tr>
    <td>Student Percentage:</td>
    <td><asp:TextBox runat="server" ID="txt3"></asp:TextBox></td></tr>
    <td colspan="2" align="center"><asp:Button ID="Button1" runat="server" Text="Button" /></td>

How to pass data from controllers to views in ASP.NET MVC ?

The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purpose.

As an ASP.NET developer your choice would be to use session variables, view state or some other ASP.NET session management object.

How to create a simple ASP.NET MVC data entry screen?

Creating simple MVC data entry screen

Every project small or big has data entry screens. In this lab we will create a simple customer data entry screen as shown in the below figure.

As soon as the end user enters detail and submits data it redirects to a screen as shown below. If he enters amount less than 100 it displays normal customer or else it displays privileged customer.

Basic MVC

The Model

Models are the main component of your app, which is usually; what is stored and retrieve from the database, in our app, it will the tweet info and text.

The View

Views are the date in formatted form, delivered to the user. Here it will be the HTML pages.

The Controller

Controllers are the components that respond to all user requests, decide the appropriate response; which might be render a view, redirect to other URI or many other things.

Pros and Cons
  • Pros
It has many pros, but these are the most remarkable:
  1. Full control over the HTML, CSS, and JavaScript code, helping you to write clean, standards-compliant markup
  2. It's Extensible which means that you can use a default component, or reconfigure it, or even use another component
  3. HTTP friendly, it gives you total control over the requests passing between browser and server
  4. Testability of MVC makes it simple to unit test the logic that is specific to a page, by testing controller methods
  • Cons
It does not really have many cons compared to its pros:
  1. The lake of drag and drop component in WebForms, despite that JQuery and other JavaScipt library overcome this problem
  2. It's not as easy as WebForms, you should understand the role of each component individually and all of them together.

Nov 28, 2012

How to create a simple model in ASP.NET MVC and display the same?(PART-4)

Step1:- Create a simple class file

The first step is to create a simple customer model which is nothing but a class with 3 properties code, name and amount. Create a simple ASP.NET MVC project, right click on the model folder and click on add new item as shown in the below figure.

Nov 26, 2012


MVC stands for "Model-View-Controller", which is a very old (but still very useful) design pattern. This design pattern will split your application in 3 different parts ("model", "view", "controller"). "Seperation of concern" is one of it´s main benefits.

Nov 25, 2012

MVC 2 - Dropdownlist with JSON

I setup the Database and LinqToSql classes for my app. The table structure is MeterTypes > MeterCollections > MeterUsages. Where a MeterType is the top level (ie. Electricity, Gas, Waste, etc.) the MeterCollections are the next level down (a MeterType may contain many of these, for Electricity I have Peak and Off-Peak) and MeterUsage is the actual usage on a meter for that MeterCollection.

OOPS Concepts (PART-2)

Multiple inheritance

Multiple inheritance is the possibility that a child class can have multiple parents. Human beings have always two parents, so a child will have characteristics from both parents.

In OOP, multiple inheritance might become difficult to handle because it allows ambiguity for the compiler. There are programming languages such as C++ that allow multiple inheritance; however, other

programming languages such as Java and the .NET Framework languages do not allow multiple inheritance. Multiple inheritance can be emulated in .NET using Multiple Interface Inheritance.

Popup window

Here I am going make custom model popup with using JQuery. Its looks very Attractive rather than the simple alert box in Asp.Net.

In my application, i would like to use the popup window concept. When the user clciks a button, a popup window should appear, with a textbox to enter a value. on closing the popup window, the user entered value should get saved into a table.

Nov 24, 2012


The query optimizer uses the statistics to create the query plan to improve the query performance. The query optimizer automatically generates the necessary statistics to build high quality query plan to improve the performance of the query.

Session State in Asp.Net

Session State

Sometimes you want your web page to 'stay alive'. That is, if a user is filling out a complicated form, you do not want the session to time out before they are finished. The user could get very angry and rightfully so: You might even get yelled at!

Creating a Tag Cloud for Your ASP.NET Blog


Most of the blogs display a set of tags or keywords in the form of a Tag Cloud. A tag cloud presents the keywords in font sizes proportional to the number of blog posts having that tag. If you are using some blogging website or using some open source blogging engine you already have a tag cloud ready. However, if you are building your own blog engine or website you will need to build the tag cloud on your own. This article shows how to do just that.

What is a multicast delegate?

A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is thrown

decimal and numeric (Transact-SQL)

Decimal and numeric

Numeric data types that have fixed precision and scale.

decimal [ (p[ ,s] )] and numeric[ (p[ ,s] )]
  • Fixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 +1 through 10^38 - 1. The ISO synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.
  • p (precision)
  • The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.
  • s (scale)
  • The maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.
Precision Storage bytes

1 - 9       5

10-19     9

20-28    13

29-38    17

As per my understanding NUMERIC(18, 10) column would take 18 decimal digits to the left of the decimal point and 10 to the right.


SELECT CAST(1234567891234567.34 AS NUMERIC(18,2))  --Works
SELECT CAST(1234567891234567.34 AS NUMERIC(18,10)) --fails with Arithmetic overflow error

it is clear that, in the first case from the statement NUMERIC(18,2) the total digits are 18 and 16 digits are available to the left of decimal, whereas 1234567891234567 are 16 digits. Hence, there is no error.
In the second case, from the statement NUMERIC(18,10), 8 digits are available to the left of decimal, but 1234567891234567 are 16 digits which is more than 8 digits. Hence, Arithmetic overflow error occurs.

Nov 18, 2012

A simple ASP.NET MVC example to demonstrate Model, View and Controller

MVC Tutorial (PART-1)

The Model

Models are the main component of your app, which is usually; what is stored and retrieve from the database, in our app, it will the tweet info and text.

The View

Views are the date in formatted form, delivered to the user. Here it will be the HTML pages.

The Controller

Controllers are the components that respond to all user requests, decide the appropriate response; which might be render a view, redirect to other URI or many other things.

Pros and Cons

It has many pros, but these are the most remarkable:
  • Full control over the HTML, CSS, and JavaScript code, helping you to write clean, standards-compliant markup
  • It's Extensible which means that you can use a default component, or reconfigure it, or even use another component
  • HTTP friendly, it gives you total control over the requests passing between browser and server
  • Testability of MVC makes it simple to unit test the logic that is specific to a page, by testing controller methods

It does not really have many cons compared to its pros:
  • The lake of drag and drop component in WebForms, despite that JQuery and other JavaScipt library overcome this problem
  • It's not as easy as WebForms, you should understand the role of each component individually and all of them together.

Nov 16, 2012

Interface class

Sometimes it is simple and helpful to define a class that does nothing but defines a standardised interface that can be used by other classes to make sure the implementation follows a standard set of input and output paramaters. Also this approach results in faster code runs and more maintainable code.

The interface class can only be approached by using a pointer to the virtual table that exposes the methods in the interface. Interface does not come by itself, it usually comes with an inherited class that implements the exposed method in the interface. Such a class that implements the interface exposed methods is often called a co-class.

OOPS Concept with Real-world example


OOP is Nothing but Object Oriented Programming.According to Wikipedia,  Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs.

Asp.Net Tutorial (PART-15)

Displaying Information

The ASP.NET Framework includes two controls you can use to display text in a page: the Label control and the Literal control. Whereas the Literal control simply displays text, the Label control supports several additional formatting properties.

Nov 15, 2012

Web Server Controls vs. HTML Server Controls

One of the first possible points of confusion when learning to build web forms is "what is the difference between a Web Server Control and an HTML Server Control?" This probably stems largely from the fact that most of the Web and HTML Server Controls don’t differ much – for example, the Label Web Server Control operates almost identically to the Label HTML Server Control. However, there are some subtle differences between the two.

Nov 14, 2012

Adding Code to the Event Handler (PART-14)

Adding code to the event handler is, well, exactly as you would expect it to be. Place the cursor in the space between Protected Sub Button1_Click(…) and End Sub and type the appropriate code in. For

now, all the code will do is change the text of the label (Label1) to, you guessed it, "Hello world!". Type in the following code, and pause after you type the period:

Nov 11, 2012

.Net C# How to dynamically add controls to a form

Dynamically Adding Controls to a Windows Form

I have a project right now who’s requirements are to dynamically create sections on a form, dynamically create items in those sections (checkboxes, text boxes, etc), and store the values entered in those boxes in a database.

Now this is no small task, but it had me thinking. It’s been a while since I wrote something that used dynamic controls. Since I’m writing the code anyway I thought I would share the technical details as to how you too can create your own controls on the fly, and hook up the events, and read the data. So many web demo’s seem to show the first and miss the next two (which would be the same as missing the point entirely..)

Nov 10, 2012

Create Html Table Dynamically

The following code dynamically creates a table with five rows and four cells per
row, sets their colors and text, and shows all this on the page. The interesting detail is that no control tags are declared in the .aspx file. Instead, everything is generated programmatically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class DynamicTable : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        HtmlTable table1 = new HtmlTable();

        // Set the table's formatting-related properties.
        table1.Border = 1;
        table1.CellPadding = 0;
        table1.CellSpacing = 0;
        table1.BorderColor = "red";

        // Start adding content to the table.
        HtmlTableRow row;
        HtmlTableCell cell;
        for (int i = 1; i <= 3; i++)
            // Create a new row and set its background color.
            row = new HtmlTableRow();
            row.BgColor = (i % 2 == 0 ? "lightgreen" : "lightgray");
            for (int j = 1; j <= 5; j++)
                // Create a cell and set its text.
                cell = new HtmlTableCell();
                cell.InnerHtml = "Row: " + i.ToString() + "<br />Cell: " + j.ToString();
                // Add the cell to the current row.

            // Add the row to the table.

        // Add the table to the page.



Keywords are the words which are language specific. A keyword is an essential part of a language definition. These words cannot be used as identifiers. Identifiers are nothing but names given to various entities used in a program. The examples of keywords are event, byte, break, using, class..etc

Identifiers are program-defined tokens. Identifiers are names of various program elements like classes, methods, variables, namespaces, interfaces...etc. in the code that uniquely identify an element. Now let us see what these entities are.

Linq To Sql Demo


    <add key="constr" value="Data Source = machine/server;
    Initial Catalog=DatabaseName;User ID=userid; password=password"/>
  <add name="TradeplusConnectionString" connectionString="Data Source = machine/server;Initial Catalog=DatabaseName;User ID=userid; password=password"
       providerName="System.Data.SqlClient" />

UpdateProgress in Asp.Net

One of the problems with Ajax, is the fact that since it's asynchronus and in the background, the browser will not show you any status. With fast servers and fast methods, this is not a big problem, but whenever you have a method which takes up a bit of time, the user is very likely to get impatient.

Fortunately, ASP.NET AJAX solves this problem for us as well, with a nice control called UpdateProgress. It will use your own template to show that an asynchronus method is working. Have a look at the following example, which will show the control in action. It will be explained afterwards.

Nov 9, 2012

Create an override for a datagrid within a user control(WPF)


        <toolkit:DataGrid  ItemsSource="{Binding Source={StaticResource DocumentsVS}}" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False"
                FontSize="16" Name="_dgDocuments" Style="{StaticResource EklektosDataGridStyle}" . . . >


<local:MyDataGrid x:Name="dataGrid"/>

In case you want to override the OnCreateAutomationPeer of your dataGrid, you have to subclass the dataGrid -

public class MyDataGrid : DataGrid
    protected override AutomationPeer OnCreateAutomationPeer()
        return null;

And in constructor of your UserControl -

public CDocumentChecklistView()
    AutomationPeer a = UIElementAutomationPeer.CreatePeerForElement(dataGrid);

Nov 8, 2012

IList Generic Interface

IList Generic Interface represents a collection of objects that can be individually accessed by index.

This example demonstrates how to use IList Generic Interface to store data.
IList Generic Interface represents a collection of objects that can be individually accessed by index.
First, you will need to import the System.Collections.Generic namespace.
using System.Collections.Generic;

MenuStrip in C#

The MenuStrip class is the foundation of menus functionality in Windows Forms. If you have worked with menus in .NET 1.0 and 2.0, you must be familiar with the MainMenu control. In .NET 3.5 and 4.0, the MainMenu control is replaced with the MenuStrip control.

Creating a MenuStrip

We can create a MenuStrip control using a Forms designer at design-time or using the MenuStrip class in code at run-time or dynamically.

To create a MenuStrip control at design-time, you simply drag and drop a MenuStrip control from Toolbox to a Form in Visual Studio. After you drag and drop a MenuStrip on a Form, the MenuStrip1 is added to the Form and looks like Figure 1. Once a MenuStrip is on the Form, you can add menu items and set its properties and events.

Basic differences between Oracle and SQL Server

most obvious differences are:

  • The FIRST biggest difference: Transaction control. In Oracle EVERYTHING is a transaction and it is not permanent until you COMMIT. In SQL Server, there is (by default) no transaction control. An error half way through a stored procedure WILL NOT ROLLBACK the DDL in previous steps.

Obviously, if you wrap the TSQL DML in BEGIN TRANSACTION and COMMIT then it will roll back but this is rare in SQL Server code I've seen.

  • The SECOND biggest difference: MVCC. In SQL Server and Oracle is different. SQL Server will allow dirty reads, and writes can block reads in MS SQL (Again, it's configurable but the default in SQL Server is for performance and not read consistency, unlike Oracle where read consistency is default and unbendable.

Also consider:

  • When you setup an Oracle server, you tend to have one database with many "users/schemas", and tablespaces that are shared by all your users. SQL Server has separate databases that do not share disk files.
  • SQL Server uses "logins" to give you access to the SQL Server instance and each database has "users" that map to a login to get individual access to the tables and views etc.
  • Typically, all the objects in a database are owned by dbo.
  • TSQL is similar to PL/SQL, but (in my opinion) less powerful. You may need to simplify your SQL to get it to work as well as you'd expect in Oracle.
  • The SQL Server Management Studio (2008 SP1) is fantastic!
  • If you like Oracle, all the "getting under the hood" and "explain plan optimisation" then this training and experience will work well for you against guy's who just code straight SQL Server TSQL and expect the server to perform fast by magic.
  • SQL Server does not have packages. This might start off as a bonus (PL/SQL packages can be a PITA) but eventually you'll start to get a big nest of similarly named stored procedures in the database and you'll wish there was a way you could organise and group then them better.

Dynamically populate drop-down that is part of form array

I will show you the HTML code, this code consist of two dropdownlist / combo box (two <select> element) with the second <select> element disabled and will be enabled if we choose something from the first <select> element. Here the HTML code (dnmddl.htm):

Nov 7, 2012

DockPanel in Silverlight

If you have used docking Windows in previous versions of .NET, the DockPanel is used to provide that functionality in WPF and Silverlight. The DockPanel is not a part of Silverlight 2. It is a part of Silverlight Toolkit but I am sure it will be a part of the next version of Silverlight.

The DockPanel control is a layout control that acts as a container for child controls. The DockPanel allows child controls to dock in left, right, top, or bottom sides of the panel.

Using Settings in C#


The .NET Framework 2.0 allows you to create and access values that are persisted between application execution sessions. These values are called settings. Settings can represent user preferences, or valuable information the application needs to use. For example, you might create a series of settings that store user preferences for the color scheme of an application. Or you might store the connection string that specifies a database that your application uses. Settings allow you to both persist information that is critical to the application outside of the code, and to create profiles that store the preferences of individual users.

While Visual Basic 2005 has provided an easily discoverable mechanism for accessing settings using the My namespace, there is no analogous namespace in Visual C# 2005, and thus settings are somewhat more difficult to access. Nonetheless, C# users can still use settings by accessing the Properties namespace. In the course of this article, you will learn the difference between application and user settings, how to create new settings at design time, how to access settings at run time, and even how to incorporate multiple sets of settings into your application.

How To Keep ASP.NET ViewState On The Server

During recent few engagements with my customers I've noticed  VIewState is extensively [unintentionally] used. ViewState is on by default. The result is heavy weight Html that round trips on the network. This causes slow response time and high network utilization that affects another applications using the same network.

How to remove ViewState from the network completely while taking an advantage if its functionality at same time?

Introduction to Styles in WPF


First of all you have to create a new WPF  Project  for that you can do as following.

Nov 5, 2012

How to create a countdown timer application using C# and WinForms

In this tutorial I will explain how to create a countdown application in C#. For this application I did not declare any additional namespaces.

StatusBar in c# Windows Application

StatusBar Example

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace StatusBarExample
  /// <summary>
  /// Summary description for StatusBarExample.
  /// </summary>
  public class StatusBarExample : System.Windows.Forms.Form
    internal System.Windows.Forms.StatusBar statusBar;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    public StatusBarExample()
      // Required for Windows Form Designer support

      // TODO: Add any constructor code after InitializeComponent call

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
      if( disposing )
        if (components != null)
      base.Dispose( disposing );

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
      this.statusBar = new System.Windows.Forms.StatusBar();
      // statusBar
      this.statusBar.Location = new System.Drawing.Point(0, 138);
      this.statusBar.Name = "statusBar";
      this.statusBar.ShowPanels = true;
      this.statusBar.Size = new System.Drawing.Size(292, 24);
      this.statusBar.SizingGrip = false;
      this.statusBar.TabIndex = 1;
      // StatusBarExample
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
      this.ClientSize = new System.Drawing.Size(292, 162);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
      this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.Name = "StatusBarExample";
      this.Text = "StatusBar Example";
      this.Load += new System.EventHandler(this.StatusBarExample_Load);


    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
      Application.Run(new StatusBarExample());

    private void StatusBarExample_Load(object sender, System.EventArgs e)
      StatusBarPanel pnlStatus = new StatusBarPanel();
      pnlStatus.Text = "Ready";
      pnlStatus.Icon = new Icon(Application.StartupPath + "\\active.ico");
      pnlStatus.AutoSize = StatusBarPanelAutoSize.Contents;

      StatusBarPanel pnlConnection = new StatusBarPanel();
      pnlConnection.Text = "Connected to " + "localhost";
      pnlConnection.AutoSize = StatusBarPanelAutoSize.Spring;



Oct 31, 2012

Viewing and Editing the Server-Side Code

Visual Basic and client-side JavaScript programmers will certainly be familiar with the concept of events and event-driven programming. Most ASP programmers will probably have come across the event-driven programming paradigm as well. It is very important that you understand the event-driven programming model, as all ASP.NET applications revolve around this principle.

Building a Simple Web Form

This section is intended to demonstrate how to build a simple Web Form and also to explain some of how ASP.NET Web Forms work from the inside out. Along the way, you’ll be introduced to several new elements of the Visual Studio IDE.

Oct 30, 2012

Server Explorer

The Server Explorer in VS .NET may look very familiar to users of Visual InterDev. Visual InterDev shipped with a feature allowing developers to access and manipulate remote data sources, all in an integrated part of the IDE. The Server Explorer in VS .NET provides this functionality and adds a whole lot of its own. A full list of resources that you can access with the Server Explorer follows.

Class View

The Class View is displayed by selecting the Class View option from the View menu. The Class View shows all the classes that apply to the project, including those in the project’s References and Web References, as well as classes that the project itself owns (each Web Form is in itself a class).

The Class View is a powerful tool and provides a constructive and useful overview of a solution. Members of classes, such as methods and properties, are represented as child nodes in the Class View treeview, and their respective scopes are shown through the use of icons.


The name “HTML view” is not entirely accurate. This view, which you access by clicking the HTML button at the bottom of the Web Form Designer as shown in Figure 4-5, shows the UI code for a Web Form. This code is primarily HTML, although there are several important differences between the UI code and vanilla HTML, which will be clearer later in this chapter and in the next chapter. Figure 4-6 shows the HTML view.

Exploring the IDE

The best way to familiarize yourself with some of the features of VS .NET is to have a hands-on tour. Visual Studio has a very substantial feature set, however, there are many features of Visual Studio that are commonly used and offer a great productivity boost if used effectively. This section aims to introduce those common items.   

Oct 29, 2012

Progressive Clock in C# windows Application


The dialog box on this exercise displays three progress bars: one holds the value of the current hour, another holds the value of the minutes in the current hour, the last displays the seconds of the current minute. We also use a label on the right side of each progress bar to display its corresponding value.

The Free Office WPF Ribbon

So you want to use a Ribbon toolbar similar to Microsoft Word in your applications, but you don’t want to purchase one from a third party. Well if you haven’t heard already, you can get a free one directly from Microsoft. Yes, you heard me correctly, FREE, and FROM MICROSOFT. So where do you get this free Ribbon control? sending email with zip file as attachment (PART-12)

In this article I would like to explain how to send the compressed or zip document as an email attachments. You can find the c# source code sample how to send the email with zip format. If you are sending the html attachment or some JavaScript there might be change attachment get corrupted. If you are using the outlook web access (OWA) email client to read the email, there might be change of your html get corrupted because of OWA html filtering option.

Best solution is we can compress the file and attach to email as attachment.  We can find the different approachs to send the email, You can find the below best solution for attachment format.

Oct 28, 2012

Asp.Net Tutorial (PART-11)

Memory Management and Garbage Collection

In any object-oriented programming environment, there arises the need to instantiate and destroy objects. Instantiated objects occupy memory. When objects are no longer in use, the memory they occupy should be reclaimed for use by other objects. Recognizing when objects are no longer being used is called lifetime management, which is not a trivial problem. The solution the CLR uses has implications for the design and use of the components you write, so it is worth understanding.

Asp.Net Tutorial (PART-10)

Common Language Specification (CLS)

The CLI defines a runtime that is capable of supporting most, if not all, of the features found in modern programming languages. It is not intended that all languages that target the CLR will support all CLR features. This could cause problems when components written in different languages attempt to interoperate. The CLI therefore defines a subset of features that are considered compatible across
language boundaries. This subset is called the Common Language Specification (CLS).

Asp.Net Tutorial (PART-9)

Modules and Assemblies

A module is an .exe or .dll file. An assembly is a set of one or more modules that together make up an application. If the application is fully contained in an .exe file, fine—that's a one-module assembly. If the .exe is always deployed with two .dll files and one thinks of all three files as comprising an inseparable unit, then the three modules together form an assembly, but none of them does so by itself. If the product is a class library that exists in a .dll file, then that single .dll file is an assembly. To put it in Microsoft's terms, the assembly is the unit of deployment in .NET.

Asp.Net Tutorial (PART-8)

Common Type System (CTS)

The CLI specification defines a rich type system that far surpasses COM's capabilities. It's called the Common Type System (CTS). The CTS defines at the runtime level how types are declared and used. Previously, language compilers controlled the creation and usage of types, including their layout in memory. This led to problems when a component written in one language tried to pass data to a
component written in a different language. Anyone who has written Visual Basic 6 code to call Windows API functions, for instance, or who has tried to pass a JavaScript array to a component written either in Visual Basic 6 or C++, is aware of this problem. It was up to the developer to translate the data to be understandable to the receiving component. The CTS obliterates this problem by providing the following features:

Asp.Net Tutorial (PART-7)

.NET Framework

In the ASP/VB6 model, Microsoft had developers building a component and then calling it via an ASP. Microsoft realized that it would be a good idea to make the component directly callable over HTTP, so that an application anywhere in the world could use that component. Microsoft threw their support behind SOAP, Simple Object Access Protocol, which allows developers to call a component over HTTP
using an XML string, with the data returning via HTTP in an XML string. Components sport URLs, making them as easy to access as any other Web item. SOAP has the advantage of having been a cross-industry standard, and not just a Microsoft creation.

Asp.Net Tutorial (PART-6)

The Need for a New ASP Model

It was evident that Microsoft would require a fundamental change to bring ASP up to the standard of industrial-strength programming. Active Server Pages was a technology based on the foundations of COM. ActiveX and COM technology provided much of its strength, but also many of its limitations. Microsoft would need to have a long hard look at COM to see how it could improve, and these changes would be bound to affect ASP. At the same time,Microsoft realized that the developers' playing field was changing, with new standards arriving all the time, particularly in information-sharing and distributed applications using XML, such as Simple Object Access Protocol (SOAP) and XML-RPC.

Asp.Net tutorial (PART-5)

Major Changes with ASP 2

Moving to Active Server Pages 2 brought the developer into a more stable and feature-rich environment. All aspects of the technology were tuned and tweaked,and programmers really felt that things had settled into a stable technology.This newfound confidence was in part due to the evidence of successful transactional sites actually showing that the platform could deliver, but also the fact that the technology had been boosted under the hood with tighter integration with Microsoft Transaction Server (MTS).

In fact, IIS 4 was rebuilt to be a MTS application, and so ASP and MTS components were actually running in the same processes. Another improvement was the work with Microsoft Message Queue.This
allowed ASP and components to communicate across networks, ideal for largescale applications with complex backend requirements, for example, e-commerce systems integrating with existing legacy enterprise resource planning (ERP) infrastructures.

Asp.Net Tutorial (PART-4)

Why ASP Was Not Originally Embraced

Active Server Pages was not an overnight success, though understandably it did capture the imagination of a large sector of the development community, particularly those already well versed in Visual Basic programming or Visual Basic for applications scripting.

Others who did not have an investment in Visual Basic knowledge found the limitations of Visual Basic, and by extension Visual Basic Scripting, reasons to avoid the technology. Faults included poor memory management, the lack of strong string management abilities, such as Regular Expressions, found in other established languages.When compared to CGI with Perl,ASP was found lacking.

At that time, Internet Information Server was in its infancy, and take-up was low, despite Microsoft's public relations juggernaut going into full flow after the company's much-reported dramatic turnaround. In comparison to current versions of the software it seems very poor, but it was still competitive on performance.

Asp.Net Tutorial (PART-3)

History of ASP

You can trace the history of ASP right back to 1995 and the momentous occasion when Microsoft realized they were falling behind in a fundamental shift in the industry by not embracing the Internet. Up until that point Microsoft had been developing their proprietary technologies, tools, and network protocols for the Microsoft Network; all of a sudden they needed an Internet strategy and fast.

Microsoft has gone from a position of playing catch-up to one close to dominance, with the Internet Explorer Web browser having a strangle-hold on the Web browsing market, and Internet Information Server (IIS) installed at the majority of Fortune 1000 companies.

Asp.Net Tutorial (PART-2)

Separation of Code from Content

As I mentioned previously, a major drawback of ASP in certain instances is that there is no way to separate code from page content. In ASP.NET, due to the introduction of server controls and the event-driven model, the trend leans toward placing all the code in event handlers in one place in the file (normally at the top). If this isn't sufficient, it's also possible to totally separate code from content by placing all the code in a separate file (VS .NET does this by default).

Session State Management

ASP provided a special collection object where the programmer could store variables pertaining to a particular visitor's session. This was a commonly used feature, but it had three major shortcomings. First, it wasn't Web farm-friendly. Session state variables were stored in the IIS process space, and as such, they were tied to a specific machine. Thus, if a visitor to a site had a particular piece of information stored in a session variable on a particular request, and he or she was then sent to another server on the next request, the ASP code would not be able to retrieve the previously stored
value. Second, a disadvantage of storing session state in the IIS process space is that should the IIS service have to be restarted, the session information is lost. The third problem was slightly more subtle, but important nonetheless: ASP kept track of visitor IDs by using cookies, which aren't supported by all browsers, or are not guaranteed to be enabled in all user browsers.

Differences Between ASP and ASP.NET

ASP.NET isn't simply the next version of ASP it's a completely redesigned technology that takes the best aspects of ASP and merges them with the power of pure object-oriented programming (OOP), a powerful development framework, to give it a vast range of functionality and the advantages of a fully compiled execution environment. Because the changes between ASP and ASP.NET are so drastic, current ASP developers must "unlearn" many concepts that they became accustomed to in ASP in order to truly get the most out of ASP.NET.

Compiled Environment

One of the most dramatic changes in ASP.NET is that it's now a fully compiled environment. Microsoft has implemented this very intelligently and it would be very easy to dismiss ASP.NET as interpreted because, to the programmer and the end user, it appears as if ASP.NET works in exactly the same way as ASP: You modify your ASP.NET page, you refresh the page in the browser, and the changes are reflected. Nowhere are you required to run a compiler. Compilation actually occurs the first time a page is requested after it has been modified. This compiled copy is then kept until the page is modified and requested again. As I've already mentioned, this process is totally transparent to the user.

What is Asp.Net?


The Internet has grown at an enormous rate over the past few years, and it has almost certainly affected the lives of most people who use computers. In only a few years, the Internet has evolved from a platform for publishing “online brochures” to an entire architecture for developing dynamic, distributed applications. Developing these applications was previously extremely difficult and tedious.

The potential was huge, but the tools consisted of nothing more than text editors in which applications would be coded from scratch. This method of writing Web applications required extensive knowledge of the “plumbing” of the Internet, and there were a very limited number of languages to use. These factors made Web application programming available only to dedicated programmers who had the time to invest in learning rudimentary interfaces and unfamiliar programming languages.

Oct 27, 2012

Combobox in c# windows application

This example explains How To Create Cascading ComboBox Dependent On One Another In WinForms Windows Forms Applications Using C# And VB.Net.

I have used Country, State, City tables from database to populate respective cascading combobox based on selection of country and state.

Drag 3 combobox controls from toolbar on the windows form, write following code to populate comboboxes.

Table schemas are shown below.

Remote Scripting with IFRAME

Before you can exchange data between frames, you must first get access to the iframe's document object. There are 3 ways of doing this:

Three Methods

Method 1 - The iframe page can use it's own javascripts to transfer and place the data into the parent.

Method 2 - The iframe page can pass its document object as an argument to a function in the parent, thereby allowing the parent to retrieve data from the iframe.

Method 3 - Place an onload event handler in the iframe tag in the parent document (this page). This method does not work with Netscape 6.

We'll look at each of the methods below. For the sake of clarity, the iframes used in the following examples will be visible. In practice, they would be hidden using the technique discussed in the previous page.

Method 1

The parent page contains a form with a list of States. When you select a State and the results are returned in iframe name="repIframe", the iframe moves the data up to div id="results1" in this page using this script:

// - this is the script in the iframe results page
var reps = document.getElementById('state_reps').innerHTML;
parent.document.getElementById('results1').innerHTML = reps;

Method 2

Once again, we're going to use the form below to get a list of State Representatives. This time, however, when the results load in the iframe, this script will call the parent function showReps(doc) :

 // - this is the script in the iframe results page

The showReps(doc) function in the parent (this page) uses the document reference to retrieve the table in the iframe and put it into div id="results2". The script looks like this:

 // - this is the script in this page
function showReps(doc){
 var x = doc.getElementById('state_reps').innerHTML;
 document.getElementById('results2').innerHTML = x;

Method 3

Method 3 uses the onload event handler to gain access to the document object of iframe name="repIframe3" source page using window.frames['repIframe3'].document.

This method will NOT work with Netscape 6.

Here's how this example works: place the event handler onload="getIframeDoc()" in the iframe tag. Next, choose a State from the select object in form name="list3". When the page loads in the iframe it will exectue the getIframeDoc function.

<iframe name="repIframe3" src="blank.html" onload="getIframeDoc()"></iframe>

 function getIframeDoc(){
  var iframeDoc = window.frames['repIframe3'].document;
  var sr = iframeDoc.getElementById('state_reps');
  if (sr){
   var reps3 = sr.innerHTML;
   document.getElementById('results3').innerHTML = reps3;


DECLARE @t TABLE (A varchar(25))

INSERT @t values ('') 

  PARSENAME(A,1) AS 'First selected'
, PARSENAME(A,2) AS '2nd selected'
, PARSENAME(A,3) AS '3rd selected'
, PARSENAME(A,4) AS '4th selected'
 from @t

The question is: (select 1)

a. Are the values returned  First selected 77,  2nd selected 88,3rd selected 99,4th selected 100'

b. Are the values returned first selected 100,  2nd selected 99,3rd selected 88, 4th selected 77

c. No values are returned.

Oct 23, 2012

Custom validator with Javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UsingCustomValidator" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <title>Using a CustomValidator</title>
    <form id="form1" runat="server">
    Enter a date:<br />
    <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="custDate" runat="server"
       Text="Enter a valid future date"
       OnServerValidate="custDate_ServerValidate" />  

   <script type="text/javascript">
     function validateOrFields(source, args){
       var sUser = document.form1.<%= txtUser.ClientID %>.value;
       var sEmail = document.form1.<%= txtEmail.ClientID %>.value;
       if (sUser == "" && sEmail == "")
          args.IsValid = false;
          args.IsValid = true;
   Enter user name:<br />
   <asp:TextBox ID="txtUser" runat="server"></asp:TextBox>
   <br />
   Enter email:<br />
   <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

   <asp:CustomValidator ID="OrFieldValidator"
                        Text="Enter either a user name or a email"
                        OnServerValidate="OrFieldValidator_ServerValidate" />  

   <asp:Button ID="btnSubmit" Text="Click this to test validation" runat="server" />
<script type="text/javascript">
  ValidatorHookupControlID("<%= txtUser.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
  ValidatorHookupControlID("<%= txtEmail.ClientID %>",document.getElementById("<%= OrFieldValidator.ClientID %>"));
 File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UsingCustomValidator : System.Web.UI.Page
   protected void custDate_ServerValidate(object source, ServerValidateEventArgs args)
      string sEnteredDate = args.Value;
      DateTime dt;
      bool convertSuccessful = DateTime.TryParse(sEnteredDate, out dt);
      if (convertSuccessful && dt >= DateTime.Today)
         args.IsValid = true;
         args.IsValid = false;

   protected void OrFieldValidator_ServerValidate(object source, ServerValidateEventArgs args)
      if (txtUser.Text.Length <= 0 && txtEmail.Text.Length <= 0)
         args.IsValid = false;
         args.IsValid = true;

Postback With Javascript

Entire form tag of the page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

    __EVENTTARGET receives argument 1 of __doPostBack
    __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else")
End If
another Solution
<script type="text/javascript">
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');

Oct 21, 2012

How to Detect Errors of Our ASP.NET MVC Views on Compile Time

I have simple ASP.NET MVC 4 internet application which we get out of the box (Things that I will show can be applied with ASP.NET MVC 3 as well). Then I will put a bug inside the index view of my home controller :

    var poo = "bar"

<h3>We suggest the following:</h3>
As you can see it is not a valid code. So it should fail on both compile time and runtime, right? Let’s build the project first :


Display custom messages or images when there is no records in GridView Data Source

Display custom messages or images when there is no records in GridView Data Source

This is a very frequent requirements to display Custom Messages or Images when there is no records in Grid View. I found people used custom code to achieve this. But ASP.NET Gridview having some inbuilt features to do the same.   You can use EmptyDataTemplate using GridView to display any custom message or Images or even web controls to add new records or whatever you want as per your requirements.

How to Convert DataTable to Collection of Custom Class object

Imagine you have a DataTable with Records and you want to Convert that to a List of your Custom class objects ? how do you do that ?

The normal -straight forward way is to Loop through  each DataRow, Create a new instance of Custom class object, read the column values of the current row(iterator) in the loop and Set the Proerties of the object..

The below code shows looping the DataRows and Creating an object of our Custom Customer Class and Setting the Properties and Adding to the Collection of Customer objects.

We can avoid this handwritten ForEach loop by using some LINQ syntax.  Generally LINQ queries works on data sources which implement the IEnumerable<T>/ IQueryable<T> Interface. But DataTable does not
implement any of these. So we can not directly apply LINQ queries on a DataTable. 

But DataTable class has an extension method called AsEnumerable which returns an IEnumerable collection of DataRow. So we can apply the AsEnumerable function on a DataTable and then play with some LINQ on the resulting collection.

So we can replace our previous version of code with the below one which make use of LINQ


When to use ViewModel in mvc3

In mvc, a controller can pass single object to the corresponding view. This object may be a simple object or a complex object. ViewModel is a complex object that may contain multiple entities or objects from different data models or data source. Basically ViewModel is a class that specify data model used in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

Designing the model

public class UserLoginModel
[Required(ErrorMessage = "Please enter your username")]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter your password")]
[Display(Name = "Password")]
public string Password { get; set; }

Working with Enums and Templates In ASP.NET MVC

Imagine you have the following types defined.

public class Movie
    public int Id { get; set; }
    public string Title { get; set; }
    public MovieGenre Genre { get; set; }

public enum MovieGenre

If you want to display MovieGenre, the DisplayFor helpers generally give you what you expect (i.e. @Html.DisplayFor(m=> m.Genre) displays "Adventure"), but EditorFor will only give you a text input because the framework treats an enum the same as a string.

Oct 20, 2012

Configuring Multiple End points for WCF Service

Sample Service with multiple End Points

Step 1

Create a WCF Service Application. Open Visual studio and create new project selecting WCF Service Application project template. In VS2008, you will get WCF Service Application project template inside WEB tab whereas in VS2010, you will get WCF Service Application project template inside WCF tab.

Step 2

Delete the default code getting created for you by WCF. Delete all the code from IService1 and Service1. If you are using VS2008, comment out whole System.ServiceModel from Web.Config file. And if you are using VS2010 then comment out Multiple Host Binding.

Step 3

Oct 19, 2012

Gridview Paging using C#

A GridView is most often used to display the data retrieved from the database in Tabular form with features of Gridview like data paging, sorting and auto formats.

You can use C# code to bind the SQL data with GridView control and follow the following simple steps to make your ASP.Net GridView control with paging enabled.

First of all drag the GridView control from Data controls menu. It will add the GridView control HTML source code as given above. Now click on GridView control to load the control properties at right side panel.

Tooltip User Control

I have created Tooltip control that replaces standard browsers' tooltips with custom ones. You can write your own html template to customize it's look and feel.

The control derives on the client from Sys.UI.Control, and is implemented as WebControl on the server.

It is really easy to use it and it gives really nice experience.

Here is a source for a very simple page showing how to use it:


Trace.Write helps diagnose problems in ASP.NET. It determines what is actually running in an ASP.NET application. We review the basics of tracing in ASP.NET. We use the C# language to easily benchmark sites.

First we must add the trace markup to our Web.config file. The sample values in the markup I show can and should be changed by you. I encourage you to flip the attribute values and see what they do as much as possible. Here's how to add the markup.

Open Web.config file. Your ASP.NET project should have a Web.config file. If it doesn't, add one through the Website > Add New Item.... menu. This is an XML file used by ASP.NET to store website configuration settings.

Oct 18, 2012

How to use C# HashTable Class

Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve items from hashTable to provide the key . Both keys and values are Objects.

The commonly used functions in Hashtable are :

  Add                   : To add a pair of value in HashTable
  ContainsKey    : Check if a specified key exist or not
  ContainsValue  : Check the specified Value exist in HashTable

Remove : Remove the specified Key and corresponding Value

Add : To add a pair of value in HashTable

Syntax : HashTable.Add(Key,Value)
  Key : The Key value
  Value : The value of corresponding key
  Hashtable ht;

ht.Add("1", "Sunday");

Generics classes Overview in C#.Net

Generics main benefit is eliminating boxing and unboxing that is true, there are also other benefits like type safety, by using generics you eliminate type ambiguitiy.

  1. Generics provide type safety without the overhead of multiple implementations. Ex. We can create a linked list of string. LinkedListlinkList=new LinkedList(); There is no need to inherit from a base type and override members.The linked list is ready for immediate use.
  2. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
  3. Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types
  4. Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.  

Understanding Garbage Collection in the .NET Framework

In this article we will explore the Garbage Collection feature in the .Net framework and the activities required in applications to manage resources complementing the Garbage Collector.

Garbage Collection in Various Environments

One of the new features inherently available in the .Net framework is automatic garbage collection. The term garbage collection can be defined as management of the allocation and release of memory in an application. In C++, developers are responsible for allocating memory for objects created in the application and releasing the memory when the object is no longer needed. COM introduced a new model for memory management - Reference counting. Programmers were only responsible for incrementing the reference count when the object is referenced and decrementing the counter when the object goes out of scope. When the object's reference count reaches zero, the object is deleted and the memory gets freed. Both these schemes are dependent on the developer and result from time to time in memory leaks and application exceptions - conditions that occur at run-time and are not detectable at compilation.

A generic way to find ASP.NET ClientIDs with jQuery

I’ve been using a small hack to deal with the ASP.NET naming container morass that is so prevalent in client side development with ASP.NET. Particularly in Master Pages all server control IDs are basically munged  because the master page place holders are naming containers.

To recap – the problem is that if you are dealing with something as simple as this:

<div class="contentcontainer"  runat="server" id="PageContent">
    <h2>Stock Quote Lookup</h2>
    <div class="labelheader" style="margin-top: 20px;">Enter a stock symbol:</div>
    <asp:TextBox runat="server" ID="txtSymbol"  />
    <input type="button" id="btnGetQuote" value="Go" />
    <div id="divStockWrapper">
        <div id="divStockDetail">       
        <img id="imgStockChart"  />

Oct 17, 2012

C# KeyNotFoundException

A KeyNotFoundException was thrown. This is likely caused by an invalid usage of the Dictionary collection. As always we want a quick way to fix the problem.


First, here we see some code that looks correct, but actually has a severe flaw. The problem is that you cannot look up a key that doesn't exist in the Dictionary and try to assign your variable to its value.

The KeyNotFoundException here is thrown on the final line of try-block. The string "test" doesn't exist in the collection.

Program that throws KeyNotFoundException [C#]

using System;
using System.Collections.Generic;

class Program
    static void Main()
        // Create new Dictionary with string key of "one"
        Dictionary<string, string> test = new Dictionary<string, string>();
        test.Add("one", "value");

        // Try to access key of "two"
        string value = test["two"];
    catch (Exception ex)
        // An exception will be thrown.


    The given key was not present in the dictionary.
at System.ThrowHelper.ThrowKeyNotFoundException()


Here we look at how you can fix this exception by using the TryGetValue method on the Dictionary constructed type. Note that could use ContainsKey instead of TryGetValue, but the below code preserves the intention of the previous code.

Program that does not throw [C#]

using System;
using System.Collections.Generic;

class Program
    static void Main()
    Dictionary<string, string> test = new Dictionary<string, string>();
    test.Add("one", "value");
    // Use TryGetValue to avoid KeyNotFoundException.
    string value;
    if (test.TryGetValue("two", out value))
        Console.WriteLine("Not found");

Not found

You always have to use the if statement when testing values in the Dictionary, because there is always a possibility that the key won't exist.

We saw how to raise and catch the KeyNotFoundException during runtime. We then saw how to avoid causing the exception. We discussed alternatives, such as TryGetValue and ContainsKey, and looked at a program that does not have this problem.
Related Posts Plugin for WordPress, Blogger...