Friday, August 13, 2010

Read & Write operations using Console class

Console Class:

In this class we use two important methods named WriteLine() and ReadLine(). This class contained in the System namespace.

Eg: Print a message

class WriteString
public static void Main()
   System.Console.WriteLine("Welcome to C#.")

Eg: read a string

using System;
class WriteString
public static void Main()
   Console.WriteLine("Enter a string ");
   string str = Console.ReadLine();
   Console.WriteLine("You entered = " + str);

WriteLine() pumps a text string to the output stream. ReadLine() allows you to receive information from the input stream. The ReadLine(0 method returns a string value.

Thursday, August 12, 2010

Attaching detaching Databases

Attaching detaching Databases

At times, you may want to move an entire database- including all of its objects data, and log files- to another SQL server machine. To do this, SQL server enables attaching and detaching databases.

Eg: Detach


Eg: Attach

SP_ATTACH_DB 'DBTEST','E:\jobin\database\DBTESTDATA.mdf','E:\jobin\database\DBTESTLOG.ldf'

Reserved CommandName values

GridView Control's Reserved CommandName values and its Description

Cancel :  Cancels an edit operation and returns the GridView control to read-only mode. Raises the    RowCancelingEdit event.

Delete : Deletes the current record. Raises the RowDeleting and RowDeleted events

Edit : Puts the current record in edit mode. Raises the RowEditing event,

Page : Performs a paging operation. Sets the CommandArgument property of the button to "First", "Last", "Next", "Prev", or a page number to specify the type of paging operation to perform. Raises the PageIndexChanging and PageIndexChanged events

Select: Selects the current record. Raises the SelectedIndexChanging and SelectedIndexChanged events.

Sort: Sorts the GridView control. Raises the Sorting and Sorted events.

Update : Updates the current record in the data source. Raises the RowUpdating and RowUpdated events.

Custom Sorting with GridView Control | Handling GridView Sorting Event

Custom Sorting with GridView Control, Handling GridView Sorting Event

Bind a grid, and Set SortExpresion property for the particular field to be sortable (Eg, BoundField).
In the following example coulmn name is assigned to SortExpression property. I have a table with column with country; I need to sort records in ascending and descending order based on the country.

In the following example you can see three methods:

1. GridView1_Sorting :  GridView's Sorting event handling method.

2. Sort : implementation of sort logic

3. ManageViewState : To keep current sorting order.

#region Sort

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

void Sort(string column)

case "Country":

if (ViewState[column] == null)
reportsSorted = (from r in report orderby r.Country ascending select r).ToList();

reportsSorted = (from r in report orderby r.Country descending select r).ToList();
ManageViewState(column, false);



void ManageViewState(string key, bool Tokeep)
if (Tokeep)
    ViewState[key] = true;
else if(ViewState[key]!=null)


Have a look at above code and try to work out it.

Wednesday, August 11, 2010

Finding Row Index in GridView RowCommand Event

GridView RowCommand Event

The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.

The GridView control also raises other specialized events when certain buttons are clicked; means buttons with the CommandName property set to "Delete", "Update", "Page" etc…

When using one of these buttons, you should consider handling one of the specialized events provided by the control; such as RowDeleted or RowDeleting.

We will discuss more about these specialized events later.

protected void gvProjects_RowCommand(object sender, GridViewCommandEventArgs e)


The above example shows a sample RowCommand event handling method.

A GridViewCommandEventArgs object is passed to the event-handling method, which allows you to determine the command name and command argument of the button clicked. To determine the command name and command argument, use the CommandName and CommandArgument properties, respectively. You can also access the button control that raised the event by using the CommandSource property.

To find index of row, which caused this event, we can use any of the following method:

1. We can use e.CommandArgument property to find row index. ( It will work only if we didn’t set the CommandArgument property of button which we clicked)

int index = Convert.ToInt32(e.CommandArgument);

2. Second way is, we can find index from e.CommandSource property. See the following example to know more about it

LinkButton lbtn = (LinkButton)e.CommandSource; // get event caused button
GridViewRow gvrow = (GridViewRow)lbtn.NamingContainer; // get grid row contains event caused button
int index = gvrow.RowIndex;

Hope It will help you to handle GridView's RowCommand Event.

Tuesday, August 10, 2010

Creating a Database


A database is a collection of information that is organized so that it can easily be accessed, managed, and updated.

create a database:

syntax:  create database database_name


database_name is the name of the database. The maximum size of a database name is 128 characters.
SQL server has two operating system file types:

1. Data files (has extension .mdf)

2. Log files ( has extension .ldf)

Data files contain data and objects such as tables and indexes. Log files contain transaction log for recovering the database transactions.

Specifying the data file and log file




Introduction to Windows Presentation Foundation (WPF)

Windows Presentation Foundation

Windows Presentation Foundation (WPF) is the successor of Windows Forms for desktop application development. WPF applications differ from traditional Windows Forms applications in several ways. The most notable is that the code for the user interface is separate from the code for application functionality. The user interface of a WPF application is typically defined using a relatively new declarative syntax called Extensible Application Markup Language (XAML).

Selecting an Application Type

WPF development supports three kinds of application: Windows applications, Navigation applications, and XAML Browser Applications (XBAP).

Windows applications are Microsoft Windows-driven and provide a user experience that is familiar to Windows users and developers alike. Multiple windows can be open at any given time, and there is built in sense of navigation or history.

Navigation applications provide a page based user experience, similar to the experience of using a Web site. Typically, only a single page can be open at any given time, and the journal functionality keeps a record of pages visited and allows back-and-fourth navigation. Unlike a Web site, however, a Navigation application is a compiled application, has full access to the resources of your computer.

XABPs are similar to Navigation applications, but they are designed to run in Windows Internet Explorer. These applications can be deployed to a server or to a Web site and are downloaded when instantiated. Applications of this type do not have full access to a computer’s resources. XBAPs run under partial-trust environment, and resources such as the file system and the registry are inaccessible by XBAPs.

Windows Applications

A Windows Application consists of one or more windows and the associated business logic. The top level user interface (UI) element of a window is a class that derives from the Window class. The Window class derives from ContentControl, meaning that it can contain a single element in its Content property. This element is usually a layout control, such as a Grid control, which can itself contain multiple child controls.

Navigation Application

Navigation applications allow you to provide a different style of user interface to users. A navigation application is a desktop application that uses Page objects as its primary object instead of Window objects. Like Window objects, Page objects can contain a single control.

Page-based navigation applications are hosted automatically in a Navigation Window at startup. The Navigation Window provides some built in functionality for navigating through the pages of an application, such as Back and Forward buttons, and the journal, which keeps track of the pages that have been visited recently.


XBAPs are similar to Navigation applications. They use Page objects as the top-level UI object, and they allow a page-based navigation model that is similar to the experience of using a Web page. The primary difference between XNAP and a Navigation application is that XBAPs are not installed. They are designed to run in Internet Explorer and do not require the user to copy them onto the hard drive.

You cannot perform the following actions in an XBAP

• Access the file system, except for isolated storage

• Access the registry

• Create stand-alone windows, such as dialog boxes.

• Access local databases

• Use Windows drag-and-drop functionality

• Use WCF Web services.

Named Parameters with Example

Named Parameters

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name.

class Employee

   public void Create(string name, string job="Software Engineer", int salary=50000)

When we calling the above method we can use named parameters feature

obj.Create("Jobin John", salary : 80000);

Hope now it is clear the term Named Parameters.

Optional Parameters with Example

Optional Parameters

Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.


class Employee

    public void Create(string name, string job="Software Engineer", int salary=50000)


The above class contains a method Create, it has three parameters.  It allows to call this method like as following

obj.Create("Jobin John");

Other two parameters  declared as optional parameteds, so if we doesn't suppy values for it, automatically takes initialized values of that parameters.

The dynamic type

The dynamic type

C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:

dynamic d = GetDynamicObject(…);


The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.

The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:

dynamic d = 7; // implicit conversion

int i = d; // assignment conversion

Setting Web Server Control Properties & Common Web Server Control Properties

Setting Web Server Control Properties

Most Web server controls inherit from the WebControl class. All Web server controls must contain a unique (at the page level) ID attribute value to give you a way to programmatically reference the control. The other attributes and properties of a Web server control are used to control the look and behavior of the control.

Common Web Server Control Properties:

AccessKey The keyboard shortcut key. It can specify a single letter or number that the user can press while holding down Alt. For example, specify “Q” if you want the user to press Alt+Q to access the control. The property is supported only in Microsoft Internet Explorer 4.0 and later.

Attributes A collection of additional attributes on the control that is not defined by a public property, but that should be rendered in the primary HTML element of this control. This allows you to use an HTML attribute that is not directly supported by the control. This property is accessible programmatically; it cannot be set in the designer

BackColor The background color of the control, which can be set using standard HTML color identifiers, such as “red” or “blue,” or RGB values expressed in hexadecimal format (“#ffffff”).

BorderColor The border color of the control, which can be set using standard HTML color identifiers, such as “black” or “red,” or RGB values expressed in hexadecimal format (“#ffffff”).

BorderWidth The width of the control’s border in pixels. Not fully supported for all controls in browsers earlier than Internet Explorer 4.0

BorderStyle The border style, if there is any. Possible values are NotSet, None, Dotted, Dashed, Solid, Double, Groove, Ridge, Inset, and Outset

CssClass The CSS class to assign to the control.

Style A list of all CSS properties that are applied to the specified HTML server control

Enabled An attribute that disables the control when set to false. This dims the control and makes it inactive. It does not hide the control

EnableTheming The default is true, which enables themes for this control.

EnableViewState The default is true, which enables view state persistence for the control

Font An attribute that contains sub properties that you can declare using the property-sub property syntax in the opening tag of a Web server control element. For example, you can make a Web server control’s text

italic by including the Font-Italic attribute in its opening tag.

ForeColor The foreground color of the control. It is not fully supported for all controls in browsers earlier than Internet Explorer 4.0.

Height The control’s height. It is not fully supported for all controls in browsers earlier than Internet Explorer 4.0.

SkinID The skin to apply to the control

TabIndex The control’s position in the tab order. If this property is not set, the control’s position index is 0. Controls with the same tab index can be tabbed according to the order in which they are declared in the Web

page. This works only in Internet Explorer 4.0 and later.

ToolTip The text that appears when the user hovers the mouse pointer over a control. The ToolTip property does not work in all browsers.

Width The width of the control. The possible units are Pixel, Point, Pica, Inch, Mm, Cm, Percentage, Em, and Ex. The default unit is pixels.

Web server Controls and Adding Web Server controls

Web server Controls

ASP.NET provides programmers a set of Web server controls for creating Web pages that provide more functionality and a more consistent programming model than that of HTML server controls.

Web server controls are able to provide more functionality because they are not tied to a single HTML tag element. Instead, they typically render many HTML tags and may also include client-side JavaScript code. Web server controls also have the ability to detect the Web browser’s capabilities and render the appropriate HTML based on those capabilities.

A Web server control can be added to an .aspx page using the Visual Studio Design view or Source view, or dynamically using code.

Eg: Adding Web Server Controls Using Design View

1. Open a Web page in Visual Studio.

2. Click the Design tab at the bottom of the Web page.

3. Open the Toolbox and click the Standard tab.

4. Drag a Web server control from the Toolbox and drop it on the Web page.

Eg: Adding Web Server Controls Using Source View

1. Open a Web page in Visual Studio.

2. Click the Source tab at the bottom of the Web page.

3. In Source view of the Web page, type the Web server control element and its attributes..

4. Alternatively, you can drag a control from the Toolbox directly into the page source..

Eg: Adding Web Server Controls Dynamically Using Code

1. Open the Web page’s code-behind page in Visual Studio.

2. Create a handler for the Page_PreInit event.

3. In the Page_PreInit method, add code to create a new instance of a TextBox Web server control.

4. After creating the instance, add code to set the control’s ID property.

5. Finally, add the control to the Controls collection of form1. This will make sure the control is output as part of the form.

protected void Page_PreInit(object sender, EventArgs e)

TextBox textBoxUserName = new TextBox();
TextBoxUserName.ID = "TextBoxUserName";


ASP.NET Page Life Cycle Events

Page Life Cycle Events:

1. PreInit: This is the first real event you might handle for a page. You typically use this event only if you need to dynamically (from code) set values such as master page or theme. This event is also useful when you are working with dynamically created controls for a page. You want to create the controls inside this event.

2. Init: This event fires after each control has been initialized. You can use this event to change initialization values for controls.

3. InitComplete: Raised once all initializations of the page and its controls have been completed.

4. PreLoad: This event fires before view state has been loaded for the page and its controls and before PostBack processing. This event is useful when you need to write code after the page is initialized but before the view state has been wired back up to the controls

5. Load: The page is stable at this time; it has been initialized and its state has been reconstructed. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. The page’s load event is called first. Then, the load event for each child control is called in turn (and their child controls, if any). This is important to know if you are writing your own user or custom controls.

6. Control (PostBack) events: ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event, for example.

7. LoadComplete: At this point all controls are loaded. If you need to do additional processing at this time you can do so here.

8. PreRender: Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.

9. SaveStateComplete: Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored. This is useful if you need to write processing that requires the view state to be set.

10. Render: This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser. This method is useful if you are writing your own custom control. You override this method to control output for the control.

11. UnLoad: This event is used for cleanup code. You use it to release any managed resources in this stage. Managed resources are resources that are handled by the runtime, such as instances of classes created by the .NET common language runtime.

Monday, August 9, 2010

The Importance of View State

The Importance of View State:

View state is a mechanism used by ASP.NET to store user-specific request and response data between page requests. The data being stored is typically associated with the server controls. This data is referred to as control state. Again, the view state data is not stored by the server. Instead, it is saved into the page’s view state (stage 7, rendering) and sent in the page’s response back to the user. When the user makes the next request, the view state is returned with his or her request. When the page processes, ASP.NET pulls the view state from the page and uses it to reset property values of the page and its controls (stage 4, load). This allows ASP.NET to have all the object data between requests without having to store it on the server. The result is a more scalable Web server that can handle more requests.

Life Cycle of an ASP.Net web page

Life Cycle of an ASP.Net web page

The life cycle starts when a user requests a Web page through his or her browser. The Web server then processes the page through a series of stages before returning the results back to the user’s browser. These processing stages define the life cycle of a Web page. Understanding how ASP.NET processes a Web page on the server is key to being able to successfully develop Web applications.

1. page request: Compile page (if necessary) Pull from cache (if available)

2. Start: Set request and response. Determine IsPostback.

3. Page Init: Initialize page controls (but not their properties). Apply page theme.

4. Load: If PostBack, load control properties from view state.

5. Validation: validate page and validator controls.

6. Post back Event handling: Call control event handlers (for post back requests).

7. Rendering: Save ViewState. Render controls and output the page.

8. Unload: Unload Request and Response. Perform clean-up. Page is ready to be discarded.

When a Web page is requested, the server creates objects associated with the page and all of its child control objects and uses these to render the page to the browser. Once the final stage is complete, the Web server destroys these objects to free up resources to handle additional requests.

Message Exchange Patterns

Message Exchange Patterns

MEPs describe the protocol of message exchanges a consumer must engage in to converse properly with the service.




1. Request/Response

This is by far the most common MEP and very little has to be done to set it up because the default value for the IsOneWay property of OperationContractAttribute is false.

Even with a void return type, if you are using Request/Response, then a response message is still going back to the consumer when the operation is called; it just would have an empty SOAP body.

2. OneWay

Sometimes, you simply want to send a message off to a service and have it trigger some sort of business logic, and you aren’t in fact interested in receiving anything back from the service. In such cases, you might want to use the OneWay MEP, that is, have the consumer simply send one-way messages into the service endpoint without any responses back from the service. This MEP is declared by setting the IsOneWay property on the OperationContractAttribute to true.

The most important one is that such an operation cannot pass any data back to the client application; it must return a void and cannot have parameters marked as out or ref.

When a OneWay operation starts running in the service, the client application has no further contact with it and will not even be aware of whether the operation was successful or not.

If the operation raises an exception that would normally generate a SOAP fault message, this SOAP fault message is simply discarded and never sent to the client.


void Cancel(string action);


The Duplex MEP is a two-way message channel whose usage might be applicable in either of these two situations.

• The consumer sends a message to the service to initiate some longer-running processing and then subsequently requires notification back from the service, confirming that the requested processing has been done.

• The consumer needs to be able to receive unsolicited messages from the service.

There are two Service contracts to consider in a Duplex MEP scenario, namely

1. the Service contract and

2. the Callback contract

This MEP is declared by associating the Callback contract with the Service contract. This association is done through the CallbackContract property of the ServiceContractAttribute that is adorning the service that needs to be capable of calling back to a consumer.

The MessageParameter Attribute

The MessageParameter Attribute

The MessageParameter Attribute also defined in the System.ServiceModel namespace, controls how the names of any operation parameters and return values appear in the service description, that is, how they are emitted as part of the WSDL for the service. This attribute has only one property, the Name property.

One concrete case in which this attribute can be useful is when you need to have a .NET keyword or type name for the name of the XML element that is serialized at the wire-level transport layer.


int Display(
int a);

The OperationContract Attribute

The OperationContract Attribute:

The OperationContract Attribute, also defined in the System.ServiceModel namespace, can be applied only to methods. It is used to declare the method as belonging to a Service contract.

As with the ServiceContractAttribute, the OperationContractAttribute can be declared with a variety of named parameters that provide control over the service description and message formats.

• Name Specifies a different name for the operation instead of using the default, which is the method name.

int Add(int a, int b);

Service Contracts and Service Types

Service Contracts and Service Types:

The ServiceContractAttribute, defined in the System.ServiceModel namespace, can be applied to either .NET interfaces or .NET classes. It is used to declare the type as a Service contract.

The Service Contract attribute enables the WCF runtime to generate a description for the service.

The ServiceContractAttribute can be declared without any parameters, but it can also take named parameters.

Name: Specifies a different name for the contract instead of the default, which is simply the interface or class type name. This contract name is what will appear in the portType name when consumers access the WSDL.

Namespace Specifies a target namespace in the WSDL for the service. The default namespace is


public interface IService1

Sunday, August 8, 2010

Introduction to WCF | Inter-Process Communications Technologies

Inter-Process Communications Technologies:

Networking solutions enabled PCs to be able to communicate with each other. Inter-Process Communications Technologies are:

1. COM


3. COM+


Microsoft originally designed COM to enable communications between components and applications running on the same computer.

COM was followed by DCOM (distributed COM), enabling applications to access components running on other computers over a network.

DCOM was itself followed by COM+. COM+ incorporated features such as integration with Microsoft Transaction Server, enabling applications to group operations on components together into transactions so that the results of these operations could either be made permanent (committed) if they were all successful, or automatically undone (rolled back) if some sort of error occurred. COM+ provided additional capabilities, such as automatic resource management (for example, if a component connects to a database, you can ensure that the connection is closed when the application finishes using the component), and asynchronous operations (useful if an application makes a request to a component that can take a long time to fulfill; the application can continue processing, and the component can alert the application by sending it a message when the operation has completed).

COM+ was followed in turn by the .NET Framework, which further extended the features available and renamed the technology as Enterprise Services. The .NET Framework also provided several new technologies for building networked components. One example was Remoting, which enabled a client application to access a remote object hosted by a remote server application as though it was running locally, inside the client application.

The Web Services

Technologies such as COM, DCOM, COM+, Enterprise Services, and .NET Framework Remoting all work well when applications and components are running within the same local area network inside an organization.

A Web service is an application or component that executes on the computer hosting the Web site rather than the user’s computer. A Web  service can receive requests from applications running on the user’s computer, perform operations on the computer hosting the Web service, and send a response back to the application running on the user’s computer. A Web service can also invoke operations in other Web services, hosted elsewhere on the Internet. These are global, distributed applications.

WCF ( Windows Communication Foundation)

The purpose of WCF is to provide a unified programming model for many of technologies (Web Services, COM, Remoting, MSMQ etc..), enabling you to build applications that are as independent as possible from the underlying mechanism being used to connect services and applications together.

Introduction to Silverlight


Silverlight is Microsoft’s implementation of a cross-browser, cross-platform client framework that allows designers and developers to deliver Rich Internet Applications (RIA) embedded in Web pages OR Silverlight is Microsoft's new browser-based plug-in for delivering richer interactive applications to users over the web.

Silverlight applications are implemented as embedded objects in Web pages. When the browser encounters a Silverlight object in the Web page, the plug-in downloads an XAP package from the Web server that contains the binaries and resources for the Silverlight application and then begins code execution inside the Web page.

The Silverlight framework allows applications to access Web services, databases, Web servers, and other data sources to acquire data that is displayed in the UI. It also allows the application to integrate with the Web page DOM as well as AJAX and JavaScript to enhance the functionality of the Web page.

Comparing Silverlight 1.0 and Silverlight 2.0

The difference between Silverlight 1.0 and 2 is very significant. The biggest change is the implementation of the .NET framework. If you are familiar with Silverlight 1.0 then you will be used to coding the application functionality in JavaScript. You still can implement functionality using JavaScript; however, you can now also implement functionality using C#, Visual Basic, Python, Ruby, and managed JavaScript.

Another major change is the introduction of the XAP package. In Silverlight 1.0, the XAML code was referenced directly by the Silverlight object embedded in the browser. In Silverlight 2, however, the embedded object references an XAP package that contains the XAP file, assemblies, and resources necessary to run the Silverlight application.

Silverlight applications are built from two code bases — XAML and managed code. The managed code can be written in C#, Visual Basic, JavaScript, or any of the Dynamic Language Runtime (DLR) languages. The common code in all Silverlight applications is XAML. You use XAML code in Silverlight to create the visual elements that make up the UI. XAML provides a robust set of controls that allow you to create rich, professional-looking UI very rapidly

Understanding and using server controls

understanding and using server controls

An ASP.NET server control is a control that provides both user functionality and programmability through a server-side event model. For example, a Button control allows users to trigger an action, such as indicating they have completed a task. In addition, the Button control is posted back to the server where ASP.NET is able to match the control with its associated event code (an on-click event, for instance). The server controls that ship with ASP.NET allow you to write code against a well-defined object model. In fact, all server controls, including the Web page class itself, inherit from the System.Web.UI.Control class.

There are two primary types of server controls in ASP.NET: HTML and Web. The HTML controls provide server-side processing that generally maps back to an HTML input element like a text box or submit button. The Web controls are ASP.NET controls that focus more on their object model and less on their HTML rendering aspects.