Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 216

ExecuteNonQuery

ExecuteNonQuery is basically used for operations where there is nothing returned from the SQL Query or
Stored Procedure. Preferred use will be for INSERT, UPDATE and DELETE Operations.

INSERT

string name = "Mudassar Khan";


string city = "Pune";
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Persons (Name, City) VALUES
(@Name, @City)", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}

UPDATE

string name = "Mudassar Khan";


string city = "Pune";
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persons SET City = @City WHERE Name =
@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}

The screenshot below displays the rows affected.

DELETE

string name = "Mudassar Khan";


string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM Persons WHERE Name = @Name",
con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}

The screenshot below displays the rows affected.

What happens when I use ExecuteNonQuery for SELECT statement?


ExecuteNonQuery will work flawlessly for SELECT SQL Query or Stored Procedure but that will simply
execute the query and do nothing. Even if you use it you will not throw any error but the Rows Affected will be
negative i.e. -1.

string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;


using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}

The screenshot below displays the rows affected returned -1.

Thus concluding it, we must use ExecuteNonQuery for INSERT, UPDATE and DELETE operations only.

ExecuteScalar

ExecuteScalar is a handy function when you want to just need one Cell value i.e. one column and one row.

For example in a case where I need to get the City of a person based on its Name.

string name = "Mudassar Khan";


string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT City FROM Persons WHERE
Name=@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null)
{
string city = o.ToString();
}
con.Close();
}
}

The screenshot below displays the value of the column returned.

Another case would when you have an Identity (Auto Increment) column and you need to get the value of the
ID column newly added record. You can refer my article for more reference

Return Identity (Auto increment) Column value after record insert in SQL Server
Database using ADO.Net with C# and VB.Net

What happens when I use ExecuteScalar for SELECT statement with multiple columns and multiple rows?

This is a great question and the answer is yes you can use it but as its behavior it will return the very first cell i.e.
first row and first column.

using (SqlConnection con = new SqlConnection(constring))


{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons WHERE
Name=@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null)
{
string city = o.ToString();
}
con.Close();
}
}

The screenshot below displays the value of the first cell i.e. first row and first column being returned.

Can we use ExecuteScalar for INSERT, UPDATE and DELETE Statements?

Yes you can. But since INSERT, UPDATE and DELETE Statements return no value you will not get any value
returned from the Query as well as you will not get the Rows Affected like you get in ExecuteNonQuery.

string name = "Mudassar Khan";


string city = "Pune";
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persons SET City = @City WHERE Name =
@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
object o = cmd.ExecuteScalar();
con.Close();
}
}

The screenshot below displays the returned value being returned as NULL since there’s nothing returned from
the UPDATE query.
Thus concluding it, we must use ExecuteScalar must be when used when you need to fetch a single cell (Scalar)
value.

ExecuteReader

ExecuteReader is strictly used for fetching records from the SQL Query or Stored Procedure i.e. SELECT
Operation.

Example would be fetching Name City for all records in the Person Table.

string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;


using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string name = dr["Name"].ToString();
string city = dr["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
con.Close();
}
}
Once the ExecuteReader method is executed it returns an object belonging to IDataReader Interface. Since we
are dealing with SQL Server, I have used SqlDataReader. Until the DataReader Read method is returning true, it
means that it is fetching record.

Hence a while loop is executed and records are fetched one by one.

ExecuteReader can also be used to bind a GridView control, but do it only if the GridView does not need
Paging to be implemented. This is necessary since if you set AllowPaging to True and bind GridView using
DataReader then you will land into an Exception as DataReader fetches records in ForwardOnly Mode.

How can we identify that the Page is Post Back?


Page object has an “IsPostBack” property, which can be checked to know t the page is posted back.

What is the use of @ Register directives?


@Register directive informs the compiler of any custom server control added to the page.

What is the use of Smart Navigation property?


It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back.

What is AppSetting Section in “Web.Config” file?


Web.config file defines configuration for a web project. Using “AppSetting” section, we can define
user-defined values. Example below is a “Connection String” section, which will be used throughout
the project for database connection.\

<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

Where is View State information stored?


In HTML Hidden Fields.

Top 10 ASP.NET MVC Interview


Questions

1. Explain MVC (Model-View-Controller) in general?

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various


components of a web application. By using MVC pattern, we can develop applications that are
more flexible to changes without affecting the other components of our application.

 "Model" is basically domain data.


 "View" is user interface to render domain data.
 "Controller" translates user actions into appropriate operations performed on model.

2. What is ASP.NET MVC?

ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-
View-Controller) architectural design pattern. Microsoft has streamlined the development of MVC
based applications using ASP.NET MVC framework.

3. Difference between ASP.NET MVC and ASP.NET WebForms?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas
ASP.NET MVC uses Front controller approach. In case of Page controller approach, every page
has its own controller, i.e., code-behind file that processes the request. On the other hand, in
ASP.NET MVC, a common controller for all pages processes the requests.
Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.

4. What are the Core features of ASP.NET MVC?

Core features of ASP.NET MVC framework are:

 Clear separation of application concerns (Presentation and Business Logic)


 An extensible and pluggable framework
 Extensive support for ASP.NET Routing
 Support for existing ASP.NET features

Follow for detailed understanding of the above mentioned core features.

5. Can you please explain the request flow in ASP.NET MVC framework?

Request flow for ASP.NET MVC framework is as follows:


Request hits the controller coming from client. Controller plays its role and decides which model
to use in order to serve the request further passing that model to view which then transforms the
model and generates an appropriate response that is rendered to the client.

6. What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such
as .aspx file. ASP.NET MVC framework uses friendly URLs that more easily describe user’s action
but are not mapped to physical files.

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can
define routing rules for the engine, so that it can map incoming request URLs to appropriate
controller.

Practically, when a user types a URL in a browser window for an ASP.NET MVC application and
presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order
to parse the URL and find out the path of corresponding controller.

7. What is the difference between ViewData, ViewBag and TempData?

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC
framework provides different options i.e., ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to communicate between controller and corresponding
view. But this communication is only for server call, it becomes null if redirect occurs. So, in
short, it's a mechanism to maintain state between controller and corresponding view.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0


feature). ViewData being adictionary object is accessible using strings as keys and also
requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting
and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request.
So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the
other controller.

8. What are Action Methods in ASP.NET MVC?

I already explained about request flow in ASP.NET MVC framework that request coming from
client hits controller first. Actually MVC application determines the corresponding controller by
using routing rules defined in Global.asax. And controllers have specific methods for each user
actions. Each request coming to controller is for a specific ActionMethod. The following code
example, “ShowBooks” is an example of an Action method.

Collapse | Copy Code

public ViewResult ShowBooks(int id)


{
var computerBook = db.Books.Where(p => P.BookID == id).First();
return View(computerBook);
}

9. Explain the role of Model in ASP.NET MVC?

One of the core features of ASP.NET MVC is that it separates the input and UI logic from business
logic. Role of Model in ASP.NET MVC is to contain all application logic including validation,
business and data access logic except view, i.e., input and controller, i.e., UI logic.

Model is normally responsible for accessing data from some persistent medium like database and
manipulate it.

10. What are Action Filters in ASP.NET MVC?

If we need to apply some specific logic before or after action methods, we use action filters. We
can apply these action filters to a controller or a specific controller action. Action filters are
basically custom classes that provide a means for adding pre-action or post-action behavior to
controller actions.

For example:

 Authorize filter can be used to restrict access to a specific user or a role.


 OutputCache filter can cache the output of a controller action for a specific duration.

Top 10 WCF Interview Questions


1. What is the difference between WCF and ASMX Web Services?

Simple and basic difference is that ASMX or ASP.NET web service is designed to
send and receive messages using SOAP over HTTP only. While WCF can exchange
messages using any format (SOAP is default) over any transport protocol (HTTP,
TCP/IP, MSMQ, NamedPipes etc).Another tutorial WCF Vs ASMX has detailed
discussion on it.

2. What are WCF Service Endpoints? Explain.

For Windows Communication Foundation services to be consumed, it’s


necessary that it must be exposed; Clients need information about service to
communicate with it. This is where service endpoints play their role.A WCF
service endpoint has three basic elements i.e. Address, Binding and
Contract.Address: It defines “WHERE”. Address is the URL that identifies the
location of the service.
Binding: It defines “HOW”. Binding defines how the service can be accessed.
Contract: It defines “WHAT”. Contract identifies what is exposed by the service.

3. What are the possible ways of hosting a WCF service? Explain.

For a Windows Communication Foundation service to host, we need at least a


managed process, a ServiceHost instance and an Endpoint configured. Possible
approaches for hosting a service are:
1. Hosting in a Managed Application/ Self Hosting
a. Console Application
b. Windows Application
c. Windows Service
2. Hosting on Web Server
a. IIS 6.0 (ASP.NET Application supports only HTTP)
b. Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
NamedPipes, MSMQ.

4. How we can achieve Operation Overloading while exposing WCF


Services?

By default, WSDL doesn’t support operation overloading. Overloading behavior can


be achieved by using “Name” property of OperationContract attribute.

[ServiceContract]
interface IMyCalculator
{
[OperationContract(Name = "SumInt")]
int Sum(int arg1,int arg2); [OperationContract(Name = "SumDouble")]
double Sum(double arg1,double arg2);
}

When the proxy will be generated for these operations, it will have 2 methods with
different names i.e. SumInt and SumDouble.

5. What Message Exchange Patterns (MEPs) supported by WCF? Explain


each of them briefly.

1. Request/Response
2. One Way
3. Duplex
Request/Response
It’s the default pattern. In this pattern, a response message will always be
generated to consumer when the operation is called, even with the void return type.
In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute
certain business functionality but not interested in receiving anything back. OneWay
MEP will work in such scenarios.
If we want queued message delivery, OneWay is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to
send a message to service to initiate some longer-running processing and require a
notification back from service in order to confirm that the requested process has
been completed.

6. What is DataContractSerializer and How its different from


XmlSerializer?

Serialization is the process of converting an object instance to a portable and


transferable format. So, whenever we are talking about web services, serialization
is very important.
Windows Communication Foundation has DataContractSerializer that is new in .NET
3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in
means specify whatever we want to serialize while Opt-out means you don’t have to
specify each and every property to serialize, specify only those you don’t want to
serialize.
DataContractSerializer is about 10% faster than XmlSerializer but it has almost no
control over how the object will be serialized. If we wanted to have more control
over how object should be serialized that XmlSerializer is a better choice.

7. How we can use MessageContract partially with DataContract for a


service operation in WCF?

MessageContract must be used all or none. If we are using MessageContract into an


operation signature, then we must use MessageContract as the only parameter type
and as the return type of the operation.
8. Which standard binding could be used for a service that was designed
to replace an existing ASMX web service?

The basicHttpBinding standard binding is designed to expose a service as if it is an


ASMX/ASP.NET web service. This will enable us to support existing clients as
applications are upgrade to WCF.

9. Please explain briefly different Instance Modes in WCF?

WCF will bind an incoming message request to a particular service instance, so the
available modes are:

Per Call: instance created for each call, most efficient in term of memory but need
to maintain session.
Per Session: Instance created for a complete session of a user. Session is
maintained.
Single: Only one instance created for all clients/users and shared among all.Least
efficient in terms of memory.

10. Please explain different modes of security in WCF? Or Explain the


difference between Transport and Message Level Security.

In Windows Communication Foundation, we can configure to use security at different


levels

a. Transport Level security means providing security at the transport layer itself.
When dealing with security at Transport level, we are concerned about integrity,
privacy and authentication of message as it travels along the physical wire. It
depends on the binding being used that how WCF makes it secure because most of
the bindings have built-in security.
<netTcpBinding>
<binding name=”netTcpTransportBinding”>
<security mode=”Transport”>
<Transport clientCredentialType=”Windows” />
</security>
</binding>
</netTcpBinding>
b. Message Level Security
For Tranport level security, we actually ensure the transport that is being used
should be secured but in message level security, we actually secure the message.
We encrypt the message before transporting it.
<wsHttpBinding>
<binding name=”wsHttpMessageBinding”>
<security mode=”Message”>
<Message clientCredentialType=”UserName” />
</security>
</binding>
</wsHttpBinding>

It totally depends upon the requirements but we can use a mixed security mode also
as follows:

<basicHttpBinding>
<binding name=”basicHttp”>
<security mode=”TransportWithMessageCredential”>
<Transport />
<Message clientCredentialType=”UserName” />
</security>
</binding>
</basicHttpBinding>

WCF Vs ASMX Web Services

First of all, it needs to understand that WCF Service provides all the capabilities
of .NET web servies and further extends it.Simple and basic difference is that
ASMX web service is designed to send and receive messages using SOAP over HTTP
only. While WCF service can exchange messages using any format (SOAP is default)
over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).
ASMX is simple but limited in many ways as compared to WCF.

1. ASMX web services can be hosted only in IIS while WCF service has all the
following hosting options:
a. IIS
b. WAS (Windows Process Activation Services)
c. Console Application
d. Windows NT Services
e. WCF provided Host
2. ASMX web services support is limited to HTTP while WCF supports HTTP, TCP,
MSMQ, NamedPipes.
3. ASMX Security is limited. Normally authentication and authorization is done
using IIS and ASP.NET security configuration and transport layer security.For
message layer security, WSE can be used.
WCF provides a consistent security programming model for any protocol and it
supports many of the same capabilities as IIS and WS-* security protocols,
additionally, it provides support for claim-based authorization that provides
finer-grained control over resources than role-based security.WCF security is
consistent regardless of the host that is used to implement WCF service.
4. Another major difference is that ASMX web services uses XmlSerializer for
serialization while WCF uses DataContractSerializer which is far better in
performance than XmlSerializer.
Key Issues with XmlSerializer in serializing .NET types to xml are:
a. Only public fields or properties of the .NET types can be translated to Xml.
b. Only the classes that implement IEnumerable can be translated.
c. Classes that implement IDictionary, such as Hashtable cannot be serialized.

Understanding WCF Bindings and


Channel Stack

In order to understand Windows Communication Foundation Bindings in details,


it’s important to understand the Channel Stack as part of WCF runtime.WCF binding
is composed of binding elements and each binding element is corresponding to a
specific channel in Channel Stack. The Channel Stack can be categorized into two
major areas i.e. Protocol Channels and Transport Channels.
Protocol Channels are Transaction Protocol, Reliable Messaging Protocol and Security
Protocol while Transport Channels includes Message Encoding and Transport
Protocol.
Transaction flow is the optional element that controls the incoming transactions
flow.
Reliability is also the optional binding element specifies that reliable messaging is
supported or not.
Security is another element that specifies that how security concepts like
authentication, authorization, confidentiality and integrity will work.
Encoding is the required message encoding element that specifies which encoding
method will be used i.e. text, binary, or MTOM.
Transport is also required binding element that specifies which transport protocol will
be used i.e. TCP, NamedPipes, HTTP, HTTPS, MSMQ, or Peer-to-Peer or we can
define our own custom one.

Each request coming from the client will go through Channel Stack from top to
bottom and then encoded byte stream message will travels over wire. On the other
end, message travel from bottom to top and reaches the service as shown in above
diagram.

A complete picture of WCF runtime with Service Instance, Dispatcher and Channel
Stack is as follows:
WCF is extensible, so we can defined our own bindings but there are different built-
in bindings available in WCF, each designed to fulfill some specific needs.

1. basicHttpBinding
2. wsHttpBinding
3. netNamedPipeBinding
4. netTcpBinding
5. netPeerTcpBinding
You can find difference between basicHttpBinding and wsHttpBinding in another WCF
Tutorial on this blog.
For example, We should go for basicHttpBinding or wsHttpBinding, if interoperability
is our concern and we need to communicate with non-WCF systems. In some case,
our service can reside on a single system, In such scenario netNamedPipeBinding
will be the most efficient option.
netTcpBinding or netPeerTcpBinding might be best options, if we need to
communicate across multiple computers.
And if the service needs support for disconnected or queued calls, netMsmqBinding
or msmqIntegrationBinding will be the candidate options.
Finally an important thing to note is, if at all possible, tries to customize an existing
standard binding rather than creating a custom binding because creating new one
will add the complexity to our solution.
WCF Services – Choosing the
appropriate WCF binding

Windows Communication Foundation is a programming model that enables us to


develop and then expose our services in a variety of different ways. It means a
single WCF service can be exposed with different wire formats and message
protocols. Bindings in WCF actually defines that how to communicate with the
service. So, binding specifies that what communication protocol as well as encoding
method will be used. Optionally, it can specify other important factors like
transactions, reliable sessions and security.
Windows Communication Foundation comes with a number of built-in bindings
that we can use to expose our service, but WCF is extensible so we can define our
own custom bindings to fulfill specific needs.In this WCF Tutorial, we will keep our
focus on learning about existing bindings available in WCF. But instead of explaining
those bindings in general, we will try to understand these bindings with respect to
some suitable scenarios in which it can be used. For understanding WCF Binding
internals, another WCF Binding Tutorial has these details.Interoperability
Scenario:
If we are going to develop a WCF service that will be consumed by non-WCF client
applications, then we can expose our service using BasicHttpBinding or
WsHttpBinding. So, how these two bindings differ from each other is explain as:
1) BasicHttpBinding is designed to replace ASMX Web services. It supports both
HTTP and Secure HTTP. As far as encoding is concerned, it provides support for Text
as well as MTOM encoding methods. BasicHttpBinding doesn’t support WS-*
standards like WS-Addressing, WS-Security and WS-ReliableMessaging.
2) WsHttpBinding also supports interoperability. With this binding, the SOAP
message is, by default, encrypted. It supports HTTP and HTTPS. In terms of
encoding, it provides support for Text as well as MTOM encoding methods. It
supports WS-* standards like WS-Addressing, WS-Security and WS-
ReliableMessaging. By default, reliable sessions are disabled because it can cause a
bit of performance overhead.
3) WsDualHttpBinding has all features of WsHttpBinding with addition that it
supports Duplex MEP (Message Exchange Pattern). In this MEP, service can
communicate with client via callback. Its basically a two way communication.

4) WsFederationHttpBinding is a specialized form of WS Binding that offers


support for federated security.

Single Computer Scenario:


If our WCF service resides on a single computer, then netNamedPipeBinding will be
the best choice.
5) NetNamedPipeBinding is secure and reliable binding on a single WCF computer
across process communication. It provides support for binary encoding which is the
best choice in this scenario and uses named pipes as transport for SOAP messages.
Intranet/Cross Computers .NET Communication Scenario:
If we need to communicate across computers with same .NET technology on
intranet, then netTcpBinding or netPeerTcpBinding options are available. It’s
basically the replacement or enhancement of earlier .NET Remoting technology.
6) NetTcpBinding supports reliability, transactions and security. It also supports
TCP protocol and binary as encoding method. We can say that it’s the most
optimized or fastest binding because both client and service are on the same WCF
technology.
7) NetPeerTcpBinding supports features as that of netTcpBinding but it provides
secure binding for peer-to-peer environment with WCF Services.
Disconnected Queued Scenario:
8) NetMsmqBinding is required in a cross machine environment with secure and
reliable queued communication. This uses MSMQ as transport.

3 simple steps to create your first


ASP.NET Web API service

“ASP.NET Web API is a framework that simplifies the creation of HTTP services”.
Using ASP.NET Web API we can create HTTP services those are non-SOAP based like
plain XML or JSON strings etc. with added advantages.
 Allowing to create resource-oriented services using the full features of HTTP.
 Exposing services to a variety of clients easily like browsers or mobile devices
etc.
Before diving into details, I would like to clarify one misconception that ASP.NET
Web API has replaced WCF. WCF is still a powerful programming model for creating
SOAP based services that use a variety of transport protocols like HTTP, TCP, Named
Pipes or MSMQ etc. You can find the same implementation by using WCF REST in
another article i.e. “5 simple steps to create your first RESTful service“
>>Creating ASP.NET Web API service that supports CRUD (Create, Retrieve,
Update, Delete) operations<<
Apart from Visual Studio 2010 or 2012, we also need MVC 4.0 to implement this
HTTP service. For the purpose of this implementation, I am going to use Visual
Studio 2010.
You can download MVC 4.0 for Visual Studio 2010 from Microsoft as follows:
 Download Executable for MVC 4
 ASP.NET MVC 4 Web Platform Installer for Visual Studio 2010 SP1
Following are 3 simple steps to create HTTP service that returns non-SOAP based
data.

 Create Web API Project


 Prepare domain Model
 Adding Controller class
Let’s move forward step by step to create a simple HTTP service using ASP.NET Web
API.

1. Create Web API Project


 Open Visual Studio and create “New Project” i.e. File -> New Project.
 Choose “ASP.NET MVC 4 Web Application” template and name project as
“FirstWebAPIService”.
 When you click “OK” button, a new window will appear for selecting a sub-
template. Actually for ASP.NET MVC 4 Web Application, we have multiple sub-
options i.e. Empty, Internet Application, Web API etc.
 Choose “Web API” and simply press “OK” button.
 A default ASP.NET MVC 4 Web API template project is created. As its an MVC
application template, so you will easily find “Model”, “View” and “Controller”
folders inside it.
2. Preparing domain Model
Now in a second step, we need to prepare the model.
 Right click on the “Model” folder and choose “Class” under “Add” from the
context menu as shown in figure.
 Name the class as “Product.cs”.
Here is the code for Product class.
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductCategory { get; set; }
public int Price { get; set; }
}

3. Adding Controller Class


Controller class plays an important role, because request coming from client hits the
controller first. Then the controller decides which model to use to serve the incoming
request. So, in order to add a controller:
 Right click on the “Controller” folder and choose “Controller” under “Add” from
the context menu as shown in figure.
 Name the controller as “ProductsController”.


Click the “Add” button, a new controller class will be added.
In order to make the things simple, we will load the model with data inside this
controller instead of loading it from database. Following is the code for controller
class.
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { ProductID = 1, ProductName = “Product 1″, ProductCategory=
“Category 1″, Price = 120 },
new Product { ProductID = 2, ProductName = “Product 2″, ProductCategory=
“Category 1″, Price = 100 },
new Product { ProductID = 3, ProductName = “Product 3″, ProductCategory=
“Category 2″, Price = 150 },
new Product { ProductID = 4, ProductName = “Product 4″, ProductCategory=
“Category 3″, Price = 90 }
};
public IEnumerable<Product> GetProducts()
{
return products;
}
}

Don’t forget to add “using FirstWebAPIService.Models;” at the top of the controller


class.
Now, it’s time to test your HTTP service using ASP.NET MVC Web API.
Run the application by pressing “CTRL+F5″, Welcome window will appear as follows:

In order to call our Product controller, change the URL as


“http://localhost:XXXX/api/products”. You will see the results as shown in following
output window.
Final output returned can be displayed differently by different browsers. Here is the
output of google chrome version 29.0.1547.66.

Next -> Performing CRUD (Create, Retrieve, Update, Delete) operations using
ASP.NET Web API.

Hopefully, this simple web development tutorial will be helpful for developers to code
their first HTTP service using ASP.NET MVC Web API. Further, for performing all
CRUD operations using Web API, Follow the click.

Performing CRUD operations using


ASP.NET Web API – Part 1

In one of my previous articles, I explained 3 simple steps to create your first


ASP.NET Web API service. In this article, I’ll try to perform all CRUD (Create, Read,
Update, Delete) operations using Microsoft ASP.NET Web API.I already has discussed
that ASP.NET Web API is a framework that simplifies the creation of HTTP services.
We can build loosely coupled services as Web API follows REST architecture. Another
advantage of using HTTP services is that it can be consumed by a wide range of
clients.As we are going to perform CRUD (Create, Read, Update, Delete) operations
in this Web Development article using HTTP services, we must understand that these
how these operations map to basic HTTP verbs.
 Create -> POST
 Read -> GET
 Update -> PUT
 Delete -> DELETE
In order to get start with coding, please create a new ASP.NET MVC 4 Project using
Visual Studio and choose Web API template. When the new project is created
successfully, you can easily find “Model”, “View” and “Controller” folders inside it.

First of all, we will be creating a new domain model class inside the model folder say
“Student.cs” as:

public class Student


{
public string StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
For a better and clean separation, we will add another class “StudentRepository.cs”
which will actually perform the CRUD operations. For the purpose of simplicity, I am
not going to write complete database interaction code here. You can have
implementation of your choice, for example, LINQ or ADO.NET Entity Framework
etc.

public class StudentRepository


{
private static List<Student> students;
public static List<Student> GetAllStudents()
{
//Code logic to get all students.
} public static Student GetStudent(string studentID)
{
//Code Logic to get all students.
}public static void RemoveStudent(string studentID)
{
//Code Logic to delete a student
}public static void AddStudent(Student student)
{
//Code Logic to Add a new student.
}public static void UpdateStudent(Student student)
{
//Code Logic to Update a student.
}
}
Now, its time to add controller class to your project. In controller folder, you will find
two controller classes by default i.e. HomeController.cs and ValuesController.cs. Add
a new controller “StudentsController.cs” under “Controller” folder. Following will be
the code for it.
public class StudentsController : ApiController
{
public List<Student> Get()
{
return StudentRepository.GetAllStudents();
}
public Student Get(string id)
{
return StudentRepository.GetStudent(id);
}
public void Post(Student Student)
{
StudentRepository.AddStudent(Student);
}
public void Put(Student Student)
{
StudentRepository.UpdateStudent(Student);
}
public void Delete(string id)
{
StudentRepository.RemoveStudent(id);
}
}
In this ASP.NET Web API article we have completed the code for performing CRUD
operations using ASP.NET Web API. In second part of this article, we will focus on
writing the code for consuming the service.
Performing CRUD operations using
ASP.NET Web API – Part 2

In part-1 of this web application development tutorial, we developed an application


that perform all CRUD (Create, Retrieve, Update, Delete) operations using Microsoft
ASP.NET Web API. Now, In this part, we will consume HTTP service developed using
ASP.NET Web API using jQuery.
If you haven’t gone through first part of this article, I’ll recommend to read and
understand Part-1and then move to this part.
I am going to recap what we implemented in Part-1 i.e. How HTTP service is
developed using ASP.NET Web API.
 Created a domain model class i.e. Student
 Implemented a StudentRepository class that contains actual code for DB
interaction.
 Added a StudentController class implementing ApiController.
Focus of this article will remain on jQuery code for consuming HTTP service,
although following is the HTML code for displaying data returned from Web API
service on get requrest. You can add following HTML table to your web page.

<table border=’1′ id=”students”>


<!– Make a Header Row –>
<tr>
<td><b>StudentID</b></td>
<td><b>FirstName</b></td>
<td><b>LastName</b></td>
</tr>
</table>
jQuery Ajax call for all CRUD operations has following important elements that need
to be understood for implementation.

 type is HTTP verb used for the calls i.e. GET, POST, PUT, DELETE etc.
 url is the Web API service URL pointing to Controller class.
 Content Type is the type of data sending to server i.e. JSON here.
 dataType is the type of data expected back from server i.e. JSON.
So, in order to get all students and display on a web page, GetAllStudents() function
make jQuery ajax call with “GET” as type and url pointing to our Web API service
controller i.e. StudentsController.
// GET ALL
function GetAllStudents()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/”,
contentType: “json”,
dataType: “json”,
success: function (data) {
$.each(data, function (key, value) {
//stringify
var jsonData = JSON.stringify(value);
//Parse JSON
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;

$(‘<tr><td>’ + id + ‘</td><td>’ + fname +


‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);

});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

On success, stringify the JSON object, parse and load into students table as a row
for each separate record.

For getting a specific student record we can modify the URL by passing id of student
as follows:
http://localhost/CRUDWebAPI/api/students/1
GetStudentById() doing almost the same as that of GetAllStudents() except that it
passes id for fetching the records.
//GET
function GetStudentById()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
//stringify
var jsonData = JSON.stringify(data);
//Parse JSON
var objData = $.parseJSON(jsonData);
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;

$(‘<tr><td>’ + id + ‘</td><td>’ + fname +


‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

Now, for Adding a new student, AddNewStudent() function does the following:

 Prepare a JSON object and pass as a parameter to “data” element of jQuery


ajax call.
 type is “POST” for create operation.
 url is pointing to StudentsController.
//ADD or CREATE
function AddNewStudent()
{
var studentData = {
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “POST”,
url: “http://localhost/CRUDWebAPI/api/students/”,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

For Updating an existing student, UpdateStudent() function does the following:

 Prepare a JSON object and pass as a parameter to “data” element of jQuery


ajax call.
 type is “PUT” for update operation.
 url is pointing to StudentsController with StudentId.
//UPDATE
function UpdateStudent()
{
var studentData = {
“StudentId”: 1,
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “PUT”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Finally, for deleting a record, jQuery ajax call code in DeleteStudent() function is as
follows:

 type is “DELETE” for delete operation.


 url is pointing to StudentsController with StudentId.
//DELETE
function DeleteStudent()
{
$.ajax({
type: “DELETE”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
alert(“successs…. ” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Hopefully this series of article on ASP.NET Web API will be helpful for web
developers.

5 simple steps to create your first


RESTful service

RESTful services are those which follow the REST (Representational State Transfer)
architectural style. Before implementing your first RESTful service, lets first
understand the concept behind it. As we know that WCF allows us to make calls and
exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named
Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just
utilizing HTTP as a transport. But HTTP is much more than just a transport. So,
when we talk about REST architectural style, it dictates that “Instead of using
complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP
should be used for making calls”.

RESTful architecture use HTTP for all CRUD operations like


(Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and
DELETE).It’s simple as well as lightweight. For the sake of simplicity, I am going to
implement only a GET request for which service will return certain types of data (i.e.
Product data) in XML format.
Following are 5 simple steps to create your first RESTful service that returns data in
XML.
 Create a WCF Service Project.
 Preparing the data (e.g. Product) to return
 Creating Service Contract
 Implementing Service
 Configure Service and Behavior

1. Create a WCF Service Project


 Open Visual Studio.
 From File -> New Project. Select WCF from left and create a new WCF
Service Application.
2. Preparing the data to return
 Now add a class to newly created project. Name it to Products.cs.

Now this Products.cs file will contain two things.First one is Data Contract
[DataContract]
public class Product
{
[DataMember]
public int ProductId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string CategoryName { get; set; }
[DataMember]
public int Price { get; set; }
}
Second one is a singleton implemented class that gets products data from a
database and return list of products. In order to make it simple, we are preparing
data inside this class instead of fetching from the database as follows:
public partial class Products
{
private static readonly Products _instance = new Products();
private Products() { }
public static Products Instance
{
get { return _instance; }
}
public List ProductList
{
get { return products; }
}
private List<Product> products = new List<Product>()
{
new Product() { ProductId = 1, Name = “Product 1″, CategoryName =
“Category 1″, Price=10},
new Product() { ProductId = 1, Name = “Product 2″, CategoryName =
“Category 2″, Price=5},
new Product() { ProductId = 1, Name = “Product 3″, CategoryName =
“Category 3″, Price=15},
new Product() { ProductId = 1, Name = “Product 4″, CategoryName =
“Category 1″, Price=9}
};
}
3. Creating Service Contract
Now add a new WCF Service to this project as follows:
It will add contract as well as service file to project. Following is the code for service
contract i.e. IProductRESTService.cs.

[ServiceContract]
public interface IProductRESTService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetProductList/")]
List GetProductList();
}
IProductRESTService contains only one method i.e. GetProductList. Important points
to understand about this method is WebInvoke attribute parameters.
 Method = “GET”, represents an HTTP GET request.
 ResponseFormat = WebMessageFormat.Xml, response format will be XML here
but we can return JSON as well by changing its value to
WebMessageFormat.json.
 BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and
response are wrapped.
 UriTemplate = “GetProductList/”, it has two parts, URL path and query.
Don’t forget to add using System.ServiceModel.Web at top.
4. Implementing RESTful Service
In this step we are going to implement the service. Only one method GetProductList
is defined in the contract, so implementing service class will be as follows:
public class ProductRESTService : IProductRESTService
{
public List GetProductList()
{
return Products.Instance.ProductList;
}
}
5. Configure Service and Behavior
The last step is to configure the service and its behaviors using the configuration file.
Following is the complete ServiceModel configuration settings.
<system.serviceModel>
<services>
<service name=”MyRESTService.ProductRESTService”
behaviorConfiguration=”serviceBehavior”>
<endpoint address=””
binding=”webHttpBinding”
contract=”MyRESTService.IProductRESTService”
behaviorConfiguration=”web”></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=”serviceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”web”>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
webHTTPBinding is the binding used for RESTful services.
Now, everything about creating RESTful service is done. You can easily run and test it.

Right click ProductRESTService.svc file and click “View in Browser“. You will see the following
screen, that means service is fine.

Just modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we
defined as service contract method.
Hopefully, this simple WCF tutorial will be helpful for the readers. To keep the things simple, I
restrict it to just getting records using HTTP GET verb. In my coming article, I’ll provide all CRUD
(Create, Read, Update, Delete) operations using RESTful service.

Practical guide to WCF RESTful


service

REST (Representational State Transfer) is an architectural style that dictates to think


in terms of resources and their representation instead of just thinking about
methods within a system. REST architecture focuses almost on the same set of
constraints like Uniform interface, separation of concerns, caching, statelessness etc.
as other distributed architecture follow.
Using REST, we get the following advantages:
 Interoperability
 Scalability
 Performance
 Efficiency
 Independent Evolution
 and many more…
REST also means using HTTP the way it meant to be. But a simple WCF service uses
HTTP only as a transport, although HTTP is much more than just a transport. HTTP is
already designed in the way as RESTful architecture suggests. RESTful services are
also referred as HTTP services because HTTP also focuses on interaction between
resources and their representation.
HTTP is the standard protocol for the all communication between resources over the
Web. So, it defines various methods for interaction with resources as follows:

 GET:- means requesting a specific representation of a resource.


 PUT:- means creating or updating a resource with a provided representation.
 DELETE:- simply defines, deleting the specific resource.
 POST:- defines submitting data to be processed by the identified resource.
 HEAD:- is similar to GET but only retrieve header not the body.
 OPTIONS:- it returns the method supported by the identified resource.
So far in this guide, we talked a lot about REST and related concepts. Lets move
further to practically implementing all these concepts. We will start this WCF tutorial
from beginner level and take to professional level.

Consume RESTful service using


jQuery in 2 simple steps

jQuery possess the functionality that simplifies the AJAX call for a RESTful
service.So, when we think about consuming a RESTful service and then rendering
received XML/JSON data in a Web Application, jQuery automatically becomes a good
option.In this WCF tutorial, we are going to call a simple RESTful service using a GET
request and then display the received data. As its a continuation of my previous
post, so I am not going to create a new RESTful service now. Please go through my
last post “5 simple steps to create your first RESTful service”, because I am going to
call the same created service.As in above mentioned article, I created a project
using Visual Studio 2010 named as “MyRESTService”. So, we will add a new client
project to same existing solution.

1. Add client project to same solution.


 Open the solution MyRESTService in Visual Studio.
 Add new project to this solution. From File -> New Project. Choose
“ASP.NET Web Application” template.
 Name the project as “MyRESTClient“.
 Choose “Add to Solution” against solution dropdown and press “OK” button.

 Now, you can see two projects under a solution. MyRESTService project and
newly added MyRESTClient project.
2. We will call that existing service using jQuery’s Ajax function in our
MyRESTClient project.
 Add a new ASP.NET WebForm page to client project and name it as
“MyRESTServiceCaller.aspx”.

Add reference to jQuery Library from Scripts.
<script src=”Scripts/jquery-1.4.1.min.js” type=”text/javascript”></script>
 Add a table to HTML body to contain contents rendered from RESTful service.
<table border=’1′ id=”products”>
<!– Make a Header Row –>
<tr>
<td><b>Product Id</b></td>
<td><b>Name</b></td>
<td><b>Price</b></td>
<td><b>Category</b></td>
</tr>
</table>
 Add following jQuery code snippets in script tag for calling service and
rendering returned XML data.
<script type=”text/javascript”>
$(document).ready(function ()
{
$.ajax({
type: “GET”,

url: “http://localhost/MyRESTService/ProductRESTService.svc/GetProductList/”,
dataType: “xml”,
success: function (xml) {
$(xml).find(‘Product’).each(function () {
var id = $(this).find(‘ProductId’).text();
var name = $(this).find(‘Name’).text();
var price = $(this).find(‘Price’).text();
varcategory = $(this).find(‘CategoryName’).text();
$(‘<tr><td>’ + id + ‘</td><td>’ + name + ‘</td><td>’ + price
+ ‘</td><td>’ +
category + ”).appendTo(‘#products’);
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
</script>
jQuery Ajax function basically performs an asynchronous HTTP request with
parameters, I mentioned in bold.

 type is the request method. Possible values can be GET, POST, DELETE, PUT
etc. Here we are making a “GET” request.
 url represents a resource on web. In our case we are providing service URL.
 datatype specifies the type of data returned from server i.e. xml, text, html,
script, json, jsonp.
 success is the callback function that will be invoked when request gets
completed.
 error is also a callback function that will be called in case of request failure.
When you run the application, it will call service, fetch data and display in a tabular
format as shown in the following figure.

Now, hopefully, you can create a simple WCF RESTful service and consume it using
jQuery as well. My next article will contain all CRUD (Create, Read, Update, Delete)
operations for RESTful service.

Post JSON data to WCF RESTful


Service using jQuery

The POST request method is basically designed to post data to a web server for
storage. That’s why its normally used when submitting a complete form. In this WCF
RESTful service tutorial, I’ll try to explain how we can post JSON data to a WCF
RESTful service using jQuery Ajax call with POST type. We discussed about “POST”
HTTP verb in previous WCF tutorials but we didn’t use it in our implementation.
Purpose of this article is to understand “POST” request with complete
implementation for a specific operation.Earlier we discussed in detail that how to
perform CRUD operations using WCF RESTful service and consume RESTful service
using jQuery? We also discussed about different HTTP verbs (GET, POST, PUT,
DELETE etc) and how these verbs map to different operation?
HTTP verb Operation
GET To get a specific resource.
PUT Create or Update a resource.
DELETE Delete a resource.
POST Submit data to a resource.
So, here we are going to create a new resource using POST HTTP verb. We’ll not
rewrite the complete code here instead we will reuse what we did in earlier tutorial.
Let’s recap it here and continue.

1. We have a DataContract class i.e. “Book”.


2. a class BookRepository that implements an interface IBookRepository.
3. RESTful service BookService implementing IBookService.
4. and finally configuration related to our service.

First of all, we are going to add a service method “SaveBook” to our existing
BookService. Add following method to IBookService interface.

[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "SaveBook/{id}")]
string SaveBook(Book book, string id);
 Method is the HTTP verb mapped here i.e. “POST”.
 RequestFormat defines that request message format i.e. JSON in our
example.
 ResponseFormat represents response message format i.e. also JSON.
 UriTemplate represents unique URI for this service operation.
BookService.cs implements the above operation as follows:
public string SaveBook(Book book, string id)
{
Book newBook = repository.AddNewBook(book);
return “id=” + newBook.BookId;
}
Configuration settings for the BookService service will remain the same. No
operation specific configuration required.

Now, we are going to consume this service using jQuery and call SaveBook service
operation using jQuery Ajax POST as given below.
function SaveBook() {

var bookData = {
“BookId”: 0,
“ISBN”: “32334833425543″,
“Title”: “WCF RESTful Service by Example”
};

$.ajax({
type: “POST”,
url:
“http://localhost/RESTServiceCRUD/BookService.svc/SaveBook/0″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Few important notes about above code are:

 jQuery makes an asynchronous HTTP request with type as “POST”. Remember


while defining service operation, we use the same “POST” verb as method in
WebInvoke attribute.
 We created a JSON object i.e. bookData and pass it as parameter to data
element.
 URL is pointing to our BookService.svc plus “SaveBook/0″. While defining
service operation, we use define it as “UriTemplate” in WebInvoke attribute.
Note: As we are going to add a new book, thats why, pass “0″ for id
parameter.
 processData, contentType and dataType are pretty simple.
When we run the above example, JSON object will be posted to WCF RESTful service
and a new book will be added to our repository.

WCF Hosting in Windows Service


Simplified

We have discussed briefly about different available hosting options (Self Hosting,
Windows Service, IIS, WAS etc) for WCF Service in separate post “WCF Interview
Questions and Answers – Part 1“. In this WCF Tutorial, we are going to implement
hosting WCF Service in a Windows Service. Hosting in Windows Service is suitable
for long-running WCF Service where the lifetime of the service is controlled by
operating system.
Remember, in previous WCF Tutorial, we have already implemented WCF Self
Hosting in a Console Application with example using a step by step approach. In this
WCF Service Tutorial, we will follow the same step by step approach to host WCF
Service as:
 Creating a Class Library for WCF Service
 Adding a Windows Service
Create a Class Library i.e. StudentService:
In Visual Studio, create a new Class Library Project, name it as “StudentService” and
press “OK” button.
Then, right click on project and Add a new “WCF Service” to this Class Library
Project.
It will add Service Contract (IStudentService) and it’s implementation class
(StudentService) to class library project. Also, it will add a reference
to System.ServiceModel.
Code for IStudentService interface will be as follows:
[ServiceContract] public interface IStudentService
{
[OperationContract]
string GetStudentInfo(int studentId);
}
And following is the code for StudentService implementation class:
public class StudentService : IStudentService
{
public string GetStudentInfo(int studentId)
{
string studentName = string.Empty;
switch (studentId)
{
case 1:
{
studentName = “Muhammad Ahmad”;
break;
}
case 2:
{
studentName = “Muhammad Hamza”;
break;
}
default:
{
studentName = “No student found”;
break;
}
}
return studentName;
}
}
Now, we are done with our WCF Service i.e. StudentService. For the purpose of
simplicity, we are going to add Windows Service project to same solution.
Adding a Windows Service:
In order to host this WCF Service in Windows Service, let’s add a new Windows
Service project “WinServiceStudentHost” to this solution.

Our Windows Service will have reference to:


 StudentService class library
 System.ServiceModel.
As we want to host our WCF Service when Windows Service get started. We will
write WCF Service hosting code in OnStart() method of Windows Service
(StudentHost.cs) and close the Service Host in OnStop() method accordingly.
namespace WinServiceStudentHost
{
public partial class StudentHost : ServiceBase
{
ServiceHost studentServiceHost = null;

public StudentHost()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
//Base Address for StudentService
Uri httpBaseAddress = new
Uri(“http://localhost:4321/StudentService”);
studentServiceHost = new
ServiceHost(typeof(StudentService.StudentService),httpBaseAddress);
//Add Endpoint to Host

studentServiceHost.AddServiceEndpoint(typeof(StudentService.IStudentService),

new WSHttpBinding(), “”);


//Metadata Exchange
ServiceMetadataBehavior serviceBehavior = new
ServiceMetadataBehavior();
serviceBehavior.HttpGetEnabled = true;
studentServiceHost.Description.Behaviors.Add(serviceBehavior);
//Open
studentServiceHost.Open();
}
catch (Exception ex)
{
studentServiceHost = null;
}
}
protected override void OnStop()
{
if (studentServiceHost != null)
{
studentServiceHost.Close();
studentServiceHost = null;
}
}
}
}
Note: Dont’ forget using System.ServiceModel and
System.ServiceModel.Description.
Also, code for Main() method in Program.cs will be as follows:

namespace WinServiceStudentHost
{
static class Program
{ static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new StudentHost()
};
ServiceBase.Run(ServicesToRun);
}
}
}
For our Windows Service to be installed, we need to add an installer class to our
project. Right click on Windows Service project i.e. WinServiceStudentHost and
choose Add->New Item -> Installer Class as follows:
Following is the code for Host Installer class:

namespace WinServiceStudentHost
{
[RunInstaller(true)]
public partial class StudentHostInstaller : System.Configuration.Install.Installer
{
public StudentHostInstaller()
{//Process
ServiceProcessInstaller process = new ServiceProcessInstaller();
process.Account = ServiceAccount.NetworkService; //Process
ServiceInstaller service = new ServiceInstaller();
service.ServiceName = “StudentHostWindowService”;
service.DisplayName = “StudentHostWindowService”;
service.Description = “Student WCF Service Hosted Successfully.”;
service.StartType = ServiceStartMode.Automatic;

Installers.Add(process);
Installers.Add(service);
}
}
}
Note: Don’t forget using System.ServiceProcess.
Finally, we need to build our project. We can install our Windows Service through
Visual Studio Command Prompt using InstallUtil utility. We will point to
WinServiceStudentHost.exe in InstallUtil command as shown in below diagram.

Our Windows Service is installed successfully and hosted our StudentService. Now,
we can easily consume that WCF Service in a Client Application. For implementation
on creating a proxy to consume a WCF Service, you can follow my previous WCF
Tutorial on Calling a WCF Self Hosting Service.
Hopefully, this WCF Service Tutorial will help in practically implementing Hosting
WCF Service in Windows Service.

Calling a WCF Self Hosted Console


Application

In previous WCF Tutorial, we discussed about different hosting options available for
a WCF Service. We also implemented hosting a WCF Service in a Console
Application. Now in this part, we are going to call our already console
hosted StudentService from a client. I’ll strongly recommend to go through
previous WCF Tutorial for creating and hosting a WCF Service in a Console
Application.
Just to recap, what we did in previous post:

 Created a StudentService Class Library


 Add a Console Application to solution
 Hosted the WCF service in Console Application
 Run the hosted Service
Now, when the self hosted service is live and listening at following address:
http://localhost:4321/StudentService

We will create a new client application to consume this self hosted WCF service. Let’s
add a new Console Application project to existing solution as:
For client application to communicate with our WCF Service “StudentService”, we
will implement a proxy class. Windows Communication Foundation (WCF) supports
multiple ways to generate proxy as:

 Adding Service Reference to Client


 Using Tool i.e. SvcUtil.exe, or
 Implement ClientBase class.
Each proxy generate approach has some pros and cons that we will discuss in a
separate WCF Tutorial but for this implementation, we will use the first approach i.e.
Adding a Service Reference to client.

Now, right click on ClientApp project and choose “Add Service Reference”, following
dialog will appear:
In address Textbox, paste the StudentService URL and press “Go” button. This tool
will search for the service and list all available WCF services in Services area as
shown. Provide a meaningful name for Namespace and press “OK” button.
Note: WCF Service must be running before we press the “Go” button. Also
System.ServiceModel must be referenced to ClientApp project as we did in case of
StudentHost application.
Under Service Reference, StudentProxy will be added as shown in below diagram:
As a new proxy is added to ClientApp, we will use this to call our WCF Service and
get the output. Here is the detailed code for calling our Windows Communication
Foundation StudentService.

Now, its time to run the application and see the output. First run the WCF host
application and then client. You will see the following result:

This WCF Tutorial is completing the previous one using step by step approach and
hopefully will be useful for understanding WCF Self hosting in a more practical way.
WCF Self Hosting in a Console
Application Simplified

In order to host a Windows Communication Foundation Service, we normally


need a managed process, a ServiceHost instance and an endpoint configured forWCF
Service.We can host aWCF Service in following different possible ways:
 Hosting in a Managed Application/ Self Hosting
 Console Application
 Windows/WPF Application
 Windows Service
 Hosting on Web Server
 IIS 6.0 (ASP.NET Application supports only HTTP)
 Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP,
TCP, NamedPipes, MSMQ.
In this WCF Tutorial, focus is to Self Host our WCF Service in a Console Application
using step by step approach. Self Hosting a WCF Service in a console application is
comparatively easy as well as flexible because we can achieve the purpose by
writing few lines of code.
Let’s first Create a Simple WCF Service i.e. a StudentService and then host in a
Console application.StudentService having service operation GetStudentInfo that
takes StudentId as parameter and returns student name.

1. Create StudentService Class Library:


Open Visual Studio and Create a new Class Library Project, name it as
“StudentService” and press “OK” button.
Then, right click on project and Add a new “WCF Service” to this Class Library
Project.
It will add Service Contract (IStudentService) and it’s implementation class
(StudentService) to class library project. Also, it will add a reference
to System.ServiceModel.
Code for IStudentService interface will be as follows:
[ServiceContract] public interface IStudentService
{
[OperationContract]
string GetStudentInfo(int studentId);
}
And following is the code for StudentService implementation class:
public class StudentService : IStudentService
{
public string GetStudentInfo(int studentId)
{
string studentName = string.Empty;
switch (studentId)
{
case 1:
{
studentName = “Muhammad Ahmad”;
break;
}
case 2:
{
studentName = “Muhammad Hamza”;
break;
}
default:
{
studentName = “No student found”;
break;
}
}
return studentName;
}
}
2. Add a Console Application:
In order to host this service in Console application, let’s add a new console
application project “StudentHost” to this solution.

Our console application will have reference to:


 StudentService class library
 System.ServiceModel.
At the start of this WCF Tutorial, we discuss that hosting a WCF service requires a
Managed Process (i.e. console application), Service Host (an instance
of ServiceHost class) and one or more Service Endpoints. Detailed implementation of
Student host application is as follows:
class Program
{
static void Main(string[] args)
{
ServiceHost studentServiceHost = null;
try
{
//Base Address for StudentService
Uri httpBaseAddress = new
Uri(“http://localhost:4321/StudentService”);

//Instantiate ServiceHost
studentServiceHost = new
ServiceHost(typeof(StudentService.StudentService),
httpBaseAddress);

//Add Endpoint to Host

studentServiceHost.AddServiceEndpoint(typeof(StudentService.IStudentService),
new WSHttpBinding(), “”);

//Metadata Exchange
ServiceMetadataBehavior serviceBehavior = new
ServiceMetadataBehavior();
serviceBehavior.HttpGetEnabled = true;
studentServiceHost.Description.Behaviors.Add(serviceBehavior);

//Open
studentServiceHost.Open();
Console.WriteLine(“Service is live now at : {0}”, httpBaseAddress);
Console.ReadKey();
}
catch (Exception ex)
{
studentServiceHost = null;
Console.WriteLine(“There is an issue with StudentService” +
ex.Message);
}
}
}
Now, simply build the console application and run it after setting as startup project.
You will see the following screen that shows our self-hosted WCF Service is running.

In this WCF Service Tutorial, we have created a Windows Communication Foundation


Service and hosted in a Console Application. In following post on this WCF blog, we
will call this self hosted WCF service from a client application.

WCF Hosting in IIS Simplified

It’s part-3 in series of WCF Hosting Tutorials and we are going to implement that
how we can host a WCF Service in IIS (version 5 or 6)? We already have
implemented the following in series:
 WCF Self Hosting in a Console Application
 WCF Hosting in Windows Service
Microsoft introduced WCF (Windows Communication Foundation) in .NET
Framework v 3.0 with lots of exciting features but most exciting feature among all
was, How it’s different from ASMX services or ASP.NET Web Services? or What’
additional things it provide as compared to ASMX services?
Primary difference is that ASMX or ASP.NET web service is designed to send and
receive messages using SOAP over HTTP only. While WCF can exchange messages
using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP,
MSMQ, NamedPipes etc). Another WCF Tutorial has detailed discussion on WCF Vs
ASMX here.

So, if we are hosting a WCF Service in IIS (version 5 or 6), only HTTP option is
available as transport protocol. In later versions of IIS (Internet Information
Services), we an use any other protocol (TCP/IP, MSMQ, NamedPipes etc.) as
transport protocol.

As we already know that in order to host a WCF Service, we need a managed


process. In case of IIS (Internet Information Services), it provides the host process
and launch the process as the first request reaches server.

Now let’s first create a WCF service and later host in IIS.

Create a StudentService Class Library

We have already created a StudentService Class Library project while


implementing WCF Self Hosting Tutorial. In order to make things consistent here, we
will use the same service, so please go through step 1 of that WCF Tutorial for
creating a WCF Service.

WCF Hosting in IIS

So in order to host our WCF Service in IIS, follow the simple step by step approach.

1. Add a Website to our Solution. Choose “ASP.NET Empty Web Site” template. For
Web location, choose “HTTP” instead of “File System”, provide the path and press
“OK” button.
2. Add Reference of StudentService project to our WebSite i.e. StudentIISHost.

3. Add Reference of System.ServiceModel to website.

4. Add a new .svc file to our website project as.


In above code, we are pointing Service to StudentService in ServiceHost.

5. Updated configuration for System.ServiceModel in web.config will be as follows:

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=”StudentServiceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration=”StudentServiceBehavior”

name=”StudentService.StudentService”>
<endpoint
address=”http://localhost/StudentIISHost/MyStudentHost.svc”
binding=”wsHttpBinding”

contract=”StudentService.IStudentService”>
<identity>
<dns value=”localhost”/>
</identity>
</endpoint>
<endpoint address=”mex”
binding=”mexHttpBinding”
contract=”IMetadataExchange”/>
</service>
</services>
</system.serviceModel>
6. Access the hosted WCF Service i.e. StudentService using following path.

http://localhost/StudentIISHost/MyStudentHost.svc

Hopefully, this WCF Tutorial will help to understand implementation for hosting a
WCF Service in IIS (Internet Information Service).

Automatic Format Selection in WCF


RESTful service

In .NET framework 4.0, Automatic Format Selection feature is introduced


byAutomaticFormatSelectionEnabled property of WebHttpBehavior class. The
purpose is to dynamically find out and return the response in appropriate format for
a service operation.
If the value of this property is set to “true” means using Automatic Format Selection,
the response format of the operation is determined by the following factors in the
same ordered way:
1. Accept header of Request Message
2. Content-Type of the HTTP request Message
3. ResponseFormat parameter of service operation.
4. WebHttpBehavior’s default format settings
By default, AutomaticFormatSelectionEnabled property of WebHttpBehavior class is
set to false. So, in my previous article on Step by step creating a WCF RESTful
Service, we explicitly defined format selection of ResponseFormat parameter in Web
operation as follows:
[ServiceContract]
public interface IProductRESTService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetProductList/")]
List<Product> GetProductList();
}
But when Automatic Format Selection feature is enabled, Accept header of
request message takes the highest precedence. First of all, Windows
Communication Foundation infrastructure looks forAccept header of Request
message. If found an appropriate format, response will be returned in the same
format. However, if not the value of Accept header is found suitable, then WCF will
look for the next factor i.e. Content Type of Request Message.
In one of my WCF service tutorial, I have explained how to consume WCF RESTful
service using jQuery? So, if you wanted to see that how to set media-type of Accept
header or Content-Type of request message, you can find complete code in
that WCF RESTful Service Example. For your understanding, following is the
sample jQuery Ajax call for my WCF HTTP Service.
$.ajax({
type: “GET”,
url: “http://localhost/XXXXXXX/XXX”,
dataType: “json”,
contentType: “json”,
success: function (data) {
//Success code…
});
},
error: function (xhr) {
alert(xhr.responseText);
}
In above jQuery code snippet, dataType represents the expected response format
from server that becomes the value of Accept header in Request Message,
while contentType is Content Type of the same.
So, in order, if no appropriate Content Type is specified, ResponseFormat parameter
inWebInvokeAttribute/WebGetAttribute of service operation will be considered,
already explained above.
Lastly, DefaultOutgoingResponseFormat property of WebHttpBehavior class will be
used to determine the output format of WCF RESTful service response, if nothing
found in service operation attribute.
Now, how to enable this Automatic Format Selection feature for a WCF RESTful
service? It can be done programmatically as well as through configuration.
Configuration settings for enabling this feature is simple and straight forward using:
 WebHttpBehavior
 WebHttpEndpoint
Using WebHttpBehavior:-
<system.serviceModel>
<services>
<service name=”MyRESTService.ProductRESTService”
behaviorConfiguration=”serviceBehavior”>
<endpoint address=””
binding=”webHttpBinding”
contract=”MyRESTService.IProductRESTService”
behaviorConfiguration=”web”>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=”serviceBehavior”>
<serviceMetadata httpGetEnabled=”true”/>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”web”>
<webHttp automaticFormatSelectionEnabled=”true” />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
Using WebHttpEndpoint:-
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name=”web”
helpEnabled=”true”
automaticFormatSelectionEnabled=”true” />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Hopefully, this WCF tutorial has simplified the concept of Automatic Format Selection
for Windows Communication Foundation RESTful service.

Error Handling in WCF RESTful


Service

WCF possesses the capability to handle errors for RESTful services and return
appropriate HTTP status code as well as error details using standard formats like
JSON or XML. So, WebFaultExceptionis the class used to return:
 HTTP status code only, or
 HTTP status code and user-defined type.
We can define a custom type for error details and pass it to WebFaultException class
constructor. Further, this custom type is serialized using defined format (i.e.
JSON/XML) and forwarded to the client.

This WCF tutorial is part of series on Creating WCF RESTful services. In previous
articles, we created RESTful services peforming all CRUD operations and later in
Part-2, consuming it usingjQuery. Here in this part, our focus is on error handling
mechanism supported by WCF for HTTP services. We will be referring the previous
article example here, so I’ll recommend to go through it first.
Now, its quite simple to return HTTP status code only. For example in previous
article, we created a WCF RESTful service having a service method GetBookById. It
takes a bookId as method parameter and return Book object against provided
bookId in JSON format. So, in order to return proper HTTP status code, we can
update the implementation as follows:
public Book GetBookById(string id)
{
Book book = repository.GetBookById(int.Parse(id));
if (book == null)
{
throw new WebFaultException(HttpStatusCode.NotFound);
}
return book;
}
But if we wanted to add some custom details with error code, we need to provide a
user-defined type that holds the information. I have created one simple custom
error type but you can modify it according to your need.

[DataContract]
public class MyCustomErrorDetail
{
public MyCustomErrorDetail(string errorInfo, string errorDetails)
{
ErrorInfo = errorInfo;
ErrorDetails = errorDetails;
}
[DataMember]
public string ErrorInfo { get; private set; } [DataMember]
public string ErrorDetails { get; private set; }
}
And implementation for the same service method GetBookById will be updated
accordingly as follows:
public Book GetBookById(string id)
{
Book book = repository.GetBookById(int.Parse(id));
if (book == null)
{
MyCustomErrorDetail customError = new MyCustomErrorDetail(
“Book not found”,
“No book exists against provided bookId.”);
throw new WebFaultException(customError,
HttpStatusCode.NotFound);
}
return book;
}
Hopefully, this article will helpful in custom error handling for WCF RESTful service.

CRUD Operations using WCF RESTful


Service – Part 1

REST (Representational State Transfer) is basically an architectural style that is


based on the same principles as that of “Web”. In this WCF Service tutorial we are
going to see these web principles in action. We will be using standard HTTP verbs for
CRUD (Create, Retrieve, Update, Delete) operations, HTTP Content-Types etc.In one
of my previous articles, I explained 5 simple steps to create your first RESTful web
service. In part-1 of this article, we will build a RESTful web serviceusingWCF while
in second part, we will be consuming the web service using jQuery.Let’s start by
creatingaWCF Service Application project using Visual Studio. Beforecreatingactual
service, lets prepare object that represents data in our application.Following is the
code forourDataContract class i.e. “Book”.
[DataContract]
public class Book
{
[DataMember]
public int BookId { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string ISBN { get; set; }
}
For the purpose of simplicity, we are not going to write code for interacting with
database. Instead we will separate code for actual CRUD operations using repository
design pattern. Benefit of using repository pattern approach is that we can easily
replace the implementation with actual database interaction code according to our
own need.

We will create an interface “IBookRepository” and a class “BookRepository” as


follows:

public interface IBookRepository


{
List GetAllBooks();
Book GetBookById(int id);
Book AddNewBook(Book item);
bool DeleteABook(int id);
bool UpdateABook(Book item);
}

public class BookRepository : IBookRepository


{
private List<Book> books = new List<Book>();
private int counter = 1;

public BookRepository()
{
AddNewBook(new Book { Title = “Thinking in C#”, ISBN =
“65674523432423″ });
AddNewBook(new Book { Title = “Thinking in Java”, ISBN =
“34223434543423″ });
AddNewBook(new Book { Title = “Beginning WCF”, ISBN = “35343532423″
});
}
//CRUD Operations
//1. CREAT
public Book AddNewBook(Book newBook)
{
if (newBook == null)
throw new ArgumentNullException(“newBook”);
newBook.BookId = counter++;
books.Add(newBook);
return newBook;
}//2. RETRIEVE /ALL
public List GetAllBooks()
{
return books;
} //2. RETRIEVE /By BookId
public Book GetBookById(int bookId)
{
return books.Find(b => b.BookId == bookId);
}
//3. UPDATE
public bool UpdateABook(Book updatedBook)
{
if (updatedBook == null)
throw new ArgumentNullException(“updatedBook”);
int idx = books.FindIndex(b => b.BookId == updatedBook.BookId);
if (idx == -1)
return false;
books.RemoveAt(idx);
books.Add(updatedBook);
return true;
}
//4. DELETE
public bool DeleteABook(int bookId)
{
int idx = books.FindIndex(b => b.BookId == bookId);
if (idx == -1)
return false;
books.RemoveAll(b => b.BookId == bookId);
return true;
}
}
As we are going to perform CRUD operations using RESTful service, we must know
that how these actions map to standard HTTP verbs.

Method Action

Getting a specific representation of a resource. In our case, get all books or ge

GET a specific ID are relevant actions.

PUT Create/Update a resource. Add a new book or update an existing book.

DELETE Delete a resource. Delete an existing book.

POST Submit data to a resource.

Now, its time to add WCF service contract as well as service as follows:
[ServiceContract]
public interface IBookService
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "Books/")]
List GetBookList();

[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "BookById/{id}")]
Book GetBookById(string id); [OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "AddBook/{id}")]
string AddBook(Book book, string id);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "UpdateBook/{id}")]
string UpdateBook(Book book, string id);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteBook/{id}")]
string DeleteBook(string id);
}
Service exposes methods for all CRUD operations. Major things to understand about
above code are:

WebInvoke attribute is used to expose services using HTTP verbs like GET, POST,
PUT, DELETE etc.

 Method is the HTTP verb used for a specific action already explained above.
 RequestFormat is the request message format e.g. JSON, XML etc.
 ResponseFormat is the response message format e.g. JSON, XML etc.
 UriTemplate is the unique URI for each specific service operations. Service
consumer only knows about unique URI defined in UriTemplate.
Implementation code of BookService for all operations is as follows:
public class BookService : IBookService
{
static IBookRepository repository = new BookRepository();
public List GetBookList()
{
return repository.GetAllBooks();
} public Book GetBookById(string id)
{
return repository.GetBookById(int.Parse(id));
}
public string AddBook(Book book, string id)
{
Book newBook = repository.AddNewBook(book);
return “id=” + newBook.BookId;
}
public string UpdateBook(Book book, string id)
{
bool updated = repository.UpdateABook(book);
if (updated)
return “Book with id = ” + id + ” updated successfully”;
else
return “Unable to update book with id = ” + id;
}
public string DeleteBook(string id)
{
bool deleted = repository.DeleteABook(int.Parse(id));
if (deleted)
return “Book with id = ” + id + ” deleted successfully.”;
else
return “Unable to delete book with id = ” + id;
}
}
Configuration settings for the service given below. I have placed the complete
configuration for <system.serviceModel>.

<system.serviceModel>
<services>
<service name=”RESTServiceCRUD.BookService”
behaviorConfiguration=”serviceBehavior”>
<endpoint address=””
binding=”webHttpBinding”
contract=”RESTServiceCRUD.IBookService”

behaviorConfiguration=”RESTEndpointBehavior”></endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name=”RESTEndpointBehavior”>
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name=”serviceBehavior”>
<serviceMetadata httpGetEnabled=”true” />
<serviceDebug includeExceptionDetailInFaults=”false” />
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Above configuration is pretty similar like normal WCF service except the following.

 webHttpBinding is the binding specifically introduced for RESTful services in


WCF 3.5.
 endpointBehavior is “webHttp” for RESTful service.
We are done with implementation of all CRUD operations for a WCF RESTful service.
Now, in Part-2 of this WCF tutorial series, we will consume all these operations.

CRUD Operations using WCF RESTful


Service – Part 2

In previous part of this article, we created a WCF RESTful service step by step and
make it available to be consumed by a client. Here in this part, we will write and
understand code to consume the RESTful web service using jQuery. Same like
previous part, I will write complete jQuery code for all CRUD operations instead of
leaving something for the reader.One of the advantages of using RESTful web
services is that it can be consumed by a wide range of client applications. Following
is the jQuery code for each CRUD operation call against WCF RESTful service created
in part 1 of this WCF Application Tutorial series.For the purpose of implementation, I
have created a new ASP.NET project to existing solution and add an ASP.NET Web
Form to make calls. But you can have your own choice of client implementation
using following jQuery code.In order to display the data returned from REST WCF
Service, I have added HTML table to body of the page.
<table border=’1′ id=”books”>
<!– Make a Header Row –>
<tr>
<td><b>Book ID</b></td>
<td><b>ISBN</b></td>
<td><b>Title</b></td>
</tr>
</table>
Here is the function that make a call to our RESTful web service to fetch all books.

// GET ALL
function GetAllBooks()
{
$.ajax({
type: “GET”,
url: “http://localhost/RESTServiceCRUD/BookService.svc/Books/”,
contentType: “json”,
dataType: “json”,
success: function (data) {
$.each(data, function (key, value) {
//stringify
var jsonData = JSON.stringify(value);
//Parse JSON
var objData = $.parseJSON(jsonData);
var bookId = objData.BookId;
var isbn = objData.ISBN;
var title = objData.Title;
$(‘<tr><td>’ + bookId + ‘</td><td>’ + isbn + ‘</td><td>’ + title +
‘</td></tr>’).appendTo(‘#books’);
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
jQuery asynchronous HTTP Request is made with type as “GET”. It represents HTTP
verb being used to make a call. We have used same verb on WebInvoke attribute
while defining service contract for GetBookList service method.

Second important thing is


URL”http://localhost/RESTServiceCRUD/BookService.svc/Books/”.
In order to understand it, we can break up above URL into two parts as:
 http://localhost/RESTServiceCRUD/BookService.svc is simple URL to our
service file (.svc).
 /Books/ is what we define as UriTemplate in WebInvoke attribute of that
particular method.
Note: You may have noticed that for in Part-1, method name in service contract was
“GetBookList” but UriTemplate was “Books/”. So, client only understand UriTemplate
not the exact method name.
Third and last input parameter is “Content-Type”. It’s sent with request header to
tell server that what kind of response is expected on client-side i.e. JSON.
On success, the output will be in the form of JSON, so just parse it and append rows
to already entered html table.
“GetBookById” is another way of consuming RESTful service and getting a record by
bookId.

//GET
function GetBookById()
{
$.ajax({
type: “GET”,
url: “http://localhost/RESTServiceCRUD/BookService.svc/BookById/2″,
contentType: “json”,
dataType: “json”,
success: function (data) {
//stringify
var jsonData = JSON.stringify(data);
//Parse JSON
var objData = $.parseJSON(jsonData);
var bookId = objData.BookId;
var isbn = objData.ISBN;
var title = objData.Title;
$(‘<tr><td>’ + bookId + ‘</td><td>’ + isbn + ‘</td><td>’ + title +
‘</td></tr>’).appendTo(‘#books’);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

In this case the URL is


“http://localhost/RESTServiceCRUD/BookService.svc/BookById/2″.UriTem
plate is “BookById” for service method “GetBookById” and “2″ is the parameter for
bookId.
Implementation for adding a new book or updating an existing record is as follows:

//CREATE
function AddNewBook()
{
var bookData = {
“BookId”: 0,
“ISBN”: “9483877388484″,
“Title”: “Migration Strategies”
};
$.ajax({
type: “PUT”,
url: “http://localhost/RESTServiceCRUD/BookService.svc/AddBook/0″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
//UPDATE
function UpdateBook()
{
var bookData = {
“BookId”: 2,
“ISBN”: “9483877388484″,
“Title”: “Migration Strategies”
};
$.ajax({
type: “PUT”,
url: “http://localhost/RESTServiceCRUD/BookService.svc/UpdateBook/2″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

For Create and Update, we create a JSON object and pass to jQuery Ajax as data
parameter and type is “PUT” as Http verb.

Implementation for deleting a book. In following example we are going to delete a


book with Id = 2.

//DELETE
function DeleteBook() {
$.ajax({
type: “DELETE”,
url: “http://localhost/RESTServiceCRUD/BookService.svc/DeleteBook/2″,
contentType: “json”,
dataType: “json”,
success: function (data) {
alert(“successs…. ” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
For this WCF Tutorial, I have provided the complete code and hopefully it will be
very easy for readers to understand and implement CRUD operations for WCF
RESTful service.

5 Simple Steps to Enable Transactions


in WCF

Transaction is basically a logical unit of work comprising of activities that all needed
to be succeeded or failed, and also it must be compliant with ACID
principals.Movement of money from a bank account to another is a simple example
of a transaction. In this single transaction, two operations will be performed. One
account will be debited (amount will be taken from) and other will be credited
(amount will be deposited).Enabling transactions in Windows Communication
Foundation is simple and straight forward but implementation sometimes becomes
difficult depending upon the scenario. For example, implementing transactions in
a distributed environment will definitelyrequire effort and more things to consider.

Now, consider we already have developed a WCF service and we wanted to enable
transactions on it. So, we will follow the steps below:
1. Add System.Transactions namespace to WCF Service project.
2. Set TransactionFlow property of the OperationContract attribute to Mandatory.
Available options for TransactionFlow are:
a. Mandatory – transaction must be flowed
b. Allowed – transaction may be flowed
c. Not Allowed – transaction is not flowedFor example, our WCF service
contract as follows:[TransactionFlow(TransactionFlowOptions.Mandatory]
void MyMethod();
3. Now, set the OperationBehavior attribute for the implementing method.
[OperationBehavior(TransactionScopeRequired=true,
TransactionAutoComplete=true)]
void MyMethod()
{
}TransactionScopeRequired = true means it can only be called in a transaction.
TransactionAutoComplete = true means that if the operation completes
successfully, transaction will be committed.
4. Enable Transactions for WCF Binding being used.
For Example, In our configuration file bindings will be as follows:<bindings>
<wsHttpBinding>
<binding name=”httpBinding” transactionFlow=”true” />
wsHttpBinding >
Remember that we must choose a binding that supports transactions i.e.
netTcpBinding, netNamedPipeBinding, wsHttpBinding, wsDualHttpBinding, and
wsFederationHttpBinding.
5. Need to start the transaction from client as:using System.Transaction;
Using( var transScope = new TransactionScope())
{//Calling service methods
IMyServiceClient client = new IMyServiceClient();
client.MyMethod();transScope.complete();}
Optionally, If we wanted to specify the Isolation level for the transaction, we can
add serviceBehaviorattribute to implementing class as follows:
[ServiceBehavior(TransactionIsolationLevel=System.Transaction.IsolationLevel.Seria
lizable)]
Public class MyService : IMyService{}
This is all we need to do for enabling transactions in WCF.
There are few more things regarding “Service Instancing and Sessions” that need to
be considered while working with Transactions but this basic WCF tutorial is more
focused on enabling transactions in simple scenario. In my later WCF article on
Windows Communication Foundation Transactions on this blog, I’ll discuss those
concepts in more details.

3 techniques for Instance


management in WCF
Instance management basically defines the binding of service instance to a request received
from a client. In case of WCF, following three techniques for service instantiation are available:
 PerCall
 PerSession
 Single
As we know that application requirements varies from one to another with respect to scalability,
durability, performance, transactions etc, so in order to meet respective needs of the application,
we chose between different WCF service instance modes and this is what we are going to
discuss here in this WCF Tutorial.

“PerSession” is the default instance mode for WCF Service. In order to use any specific
techniques mentioned above, we need to configure serviceBehavior attribute for a service as
follows:
[ServiceContract()]
public interface IInstanceManagDemoService
{
[OperationContract]
string Method1();
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
public class InstanceManagDemoService : IInstanceManagDemoService
{
public string Method1()
{
//method details here…..
}
}

PerCall
In case of PerCall Instance mode, a new instance is created against each request coming from
client and later disposed off when response is sent back from service as shown in the following
diagram.
Above diagram shows that all request coming from one or more clients are served by separate
instance on server.
Key points about this approach are follows:
 We will prefer to use this approach when we don’t need to maintain state between
requests.
 Scalability is a major concern and service holds expensive resources like communication
ports, files or database connections etc.

PerSession
For PerSession Instance mode, a new instance is maintained on server for one session. For
separate session, another instance is created that serves the request. Normally, we use this
technique, when we need to maintain session between multiple requests.

Above diagram shows that for all requests from “WCF Client 1″ are served by “Service Instance
1″. Same is the case for client 2 and client 3 respectively. In this technique, the service instance
is disposed off when one a particular client completes its all method calls to perform a specific
functionality.
Key points about this approach are follows:
 Approach is preferable when we need to maintain state.
 Scalability is a concern but not the biggest concern.

Single
In case of Single/Singleton Instance mode, only one instance is created to serve all the requests
coming from all clients.

In this technique, service instance is not disposed off and it stays on server to serve all incoming
requests.
Key points about this approach are follows:
 We want to share global data using service.
 Scalability is not a concern at all.

WCF Service – What is a KnownType?

In Windows Communication Foundation, a KnownType is the acceptable derived


class for a givenData Contract.
Using WCF Data Contract Known Types by Example
For the purpose of understanding in this WCF Tutorial, lets take an example.
Consider the following Data Contract classes having inheritance relationship as
follows:

[DataContract]
public class UserAccount {}

[DataContract]
public class Admin : UserAccount {}
[DataContract]
public class Guest : UserAccount {}
Now, look into following code:

[DataContract]
[ServiceKnownType(typeof(Admin))]
[ServiceKnownType(typeof(Guest))]
public class SecurityInfo
{
[DataMember]
private UserAccount user;
}
Above code will work fine, either we set SecurityInfo data member to Admin or
Guest.
But if KnownTypeAttribute for Admin and Guest are not provided, deserialization
engine will not recognize Admin and Guest types and will cry.
For more detailed understanding with example of all possible ways of associating
Known Types in WCF, Click Here.

Using WCF Data Contract Known


Types by Example

Data Contract describes the type of data that will be sent or received between a
service and a client. But in certain scenarios, sent or received data is not known
between the the communicating parties. For example, a service sending data back
to client is not the actual data contract but a derived type of it. In such cases, there
will be a De-serialization problem. De-serialization engine will not recognize the
derived Data Contract type and will generate an error.
In order to handle such scenarios, Data Contract Known types are available
in Windows Communication Foundation. So by definition, “Known Type in WCF
is an acceptable derived type for a Data Contract“.In one of my previous WCF
Service articles, I exlained WCFKnowTypeAttribute with the help of a simple
example. But here in this WCF Tutorial, I’ll try to discuss all possible ways to use
Data Contract Known Types, so that the reader can get a detailed understanding
about Known Types and be able to use it in various practical scenarios.

Consider we have a service contract “IVehicleService” as:


[ServiceContract]
public Interface IVehicleService
{
[OperationContract]
Vehicle AddNewVehicle(Vehicle myVehicle);

[OperationContract]
bool UpdateVehicle(Vehicle myVehicle);
}
We can use Data Contract Known Types at different levels depending upon the
requirements:
 Global Level
 Using Code at base type
 Using Web.config
 Service Contract Level
 Operation Contract Level
Using Globally (Using Code at base type):
In order to use globally, we can apply KnownTypeAttribute at base Data Contract
type as used in following example:
[KnownType(typeof(Car))]
[KnownType(typeof(Truck))]
[DataContract]
public class Vehicle
{
}
[DataContract]
public class Car : Vehicle
{
}
[DataContract]
public class Truck : Vehicle
{
}
In above example, you can see that KnownTypeAttribute is used at base Data
Contract Type i.e. Vehicle. So, now these derived types are globally known for all
service and operation contracts wherever the Vehicle type is used.
Using Globally (Using Web.config):
We can achieve the same as above using web.config as follows:
<system.runtime.serialization>
<dataContractSerializer>
<declaredTypes>
MyService.Vehicle,
MyService, Version=,
Culture=Neutral, PublicKeyToken=null”>
<knownType type=”MyService.Car,
MyService, Version=<version here>,
Culture=Neutral, PublicKeyToken=null” />
<knownType type=”MyService.Truck,
MyService, Version=<version here>,
Culture=Neutral, PublicKeyToken=null” />
</add>
</declaredTypes>
</dataContractSerializer>
</system.runtime.serialization>
Above configuration will also make the derived types (Car, Truck) as globally known
Types.

Using at Service Contract:


For certain scenarios, if we wanted to make such derived types as known types for a
particular service, we can apply ServiceKnownTypeAttribute as follows:
[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(Truck))]
[ServiceContract]
public Interface IVehicleService
{
[OperationContract]
Vehicle AddNewVehicle(Vehicle myVehicle);

[OperationContract]
bool UpdateVehicle(Vehicle myVehicle);
}
Now, these derived types are known to all operation contracts
within IVehicleService.
Using at Operation Contract:
In order to make it more restricted i.e. for only a specific operation contract within a
service, we can do the following:
[ServiceContract]
public Interface IVehicleService
{
[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(Truck))]
[OperationContract]
Vehicle AddNewVehicle(Vehicle myVehicle);

[OperationContract]
bool UpdateVehicle(Vehicle myVehicle);
}
So now, these derived types are known types only for AddNewVehicle method and
not for the UpdateVehicle or other operations within IVehicleService.
This Service tutorial provides all possible ways for associating Data Contract Known
Types in WCF.

WCF Service – Bindings default


security

When we talk about security in Windows Communication Foundation, It can be


at two different levels i.e.
 Transport Level Security
 Message Level Security
Different WCF bindings have security defaults as follows:
1. BasicHttpBinding
 No Security
 Interopable with ASMX Web Services
2. WsHttpBinding
 Message Level Security
 SOAP Messages are encrypted
3. NetTcpBinding
 Transport Level Security
 Packets are encrypted but not the messages (SOAP messages)
ASP.NET MVC3 Vs MVC4 Vs MVC5

In this ASP.NET MVC tutorial, we will have a quick look into new and important
features introduced in major versions of Microsoft ASP.NET MVC starting from MVC
3 to MVC 5 (the latest one so far).

MVC3 Vs MVC4 Vs MVC5

Building your ASP.NET MVC Application using Entity Framework

ASP.NET MVC 3

 New Project Templates having support for HTML 5 and CSS 3.


 Improved Model validation.
 Razor View Engine introduced with a bundle of new features.
 Having support for Multiple View Engines i.e. Web Forms view engine, Razor or
open source.
 Controller improvements like ViewBag property and ActionResults Types etc.
 Unobtrusive JavaScript approach.
 Improved Dependency Injection with new IDependencyResolver.
 Partial page output caching.

ASP.NET MVC 4

 ASP.NET Web API, a framework that simplifies the creation of HTTP


services and serving a wide range of clients. Follow to create your first ASP.NET
Web API service.
 Adaptive rendering and other look-n-feel improvements to Default Project
Templates.
 A truly Empty Project Template.
 Based on jQuery Mobile, new Mobile Project Template introduced.
 Support for adding controller to other project folders also.
 Task Support for Asynchronous Controllers.
 Controlling Bundling and Minification through web.config.
 Support for OAuth and OpenID logins using DotNetOpenAuth library.
 Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5

Creating your first ASP.NET MVC 5 Application in 4 simple steps


 Bootstrap replaced the default MVC template.
 ASP.NET Identity for authentication and identity management.
 Authentication Filters for authenticating user by custom or third-party
authentication provider.
 With the help of Filter overrides, we can now override filters on a method or
controller.
 Attribute Routing is now integrated into MVC 5.
Hopefully, this article will help you in comparing core features of ASP.NET MVC in
different versions.

Solution to browser back button click


event handling

In Javascript, onbeforeunload event is fired when the page is about to unload and
there can be multiple reasons for this unload. For instance, back or forward or
refresh button is clicked or a link on the page is clicked
etc.Normally, onbeforeunload event is used in order to handle browser back button
functionality as follows:
<body onbeforeunload=”HandleBackFunctionality()”>
function HandleBackFunctionality()
{
if(window.event) //Internet Explorer
{
alert(“Browser back button is clicked on Internet Explorer…”);
}
else //Other browsers e.g. Chrome
{
alert(“Browser back button is clicked on other browser…”);
}
}
But there is a problem that identical event occurs once a user clicks on refresh
button of a browser. So, to grasp whether or not refresh button or back button is
clicked, we will use the subsequent code.

if(window.event.clientX < 40 && window.event.clientY < 0)


{
alert(“Browser back button is clicked…”);
}
else
{
alert(“Browser refresh button is clicked…”);
}
Above code snippet works well in browsers aside from FireFox, In case of FireFox,
we need to apply the following check.
if(event.currentTarget.performance.navigation.type == 1)
{
alert(“Browser refresh button is clicked…”);
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert(“Browser back button is clicked…”);
}
So, consolidated code snippet will look as:

function HandleBackFunctionality()
{
if(window.event)
{
if(window.event.clientX < 40 && window.event.clientY < 0)
{
alert(“Browser back button is clicked…”);
}
else
{
alert(“Browser refresh button is clicked…”);
}
}
else
{
if(event.currentTarget.performance.navigation.type == 1)
{
alert(“Browser refresh button is clicked…”);
}
if(event.currentTarget.performance.navigation.type == 2)
{
alert(“Browser back button is clicked…”);
}
}
}
Above code snippet is beneficial in many scenarios however there are some issues
with it. For instance, navigation can be done using keyboard keys and refresh can
also be done using F5 or CTRL+R which can not be handled using above code.

In order to handle back button functionality, we need to come up with a solution


that requires server-side effort together with client side Javascript code.
So, what’s the concept is…?
We will store the current page URL in session variable (say CurrentPageURL) on a
page. When moved to another page, we will get that variable value and store in a
second session variable (say PreviousPageURL) and update CurrentPageURL session
variable with new page URL. ASP.NET straightforward code implementation is as
follows:

//ASP.NET/C# code
if (Session["CurrentPageURL"] != null)
{
Session["PreviousPageURL"] = Session["CurrentPageURL"];
}
Session["CurrentPageURL"] = Request.Url;
On client side, when onbeforeunload event is fired, we will verify that whether or not
Javascript document.referrer value is same as that of the session variable? If the
value is same, means back button is clicked, so will act accordingly.
function HandleBackFunctionality()
{
var previousPageURL = “<%= Session["PreviousPageURL"] %>”;
if (document.referrer == previousPageURL)
{
alert(“Its a back button click…”);
//Specific code here…
}
}
This solution works well regardless of the browser type and simple to implement.
Server-side implementation in other languages is also straightforward. Please feel
free to comment and suggest a better idea (if any).

Difference betweeen ASP.NET


WebForms and ASP.NET MVC

If you are visiting ASP.NET forums and communities, you will find following
questions frequently i.e.
 What is the difference between ASP.NET MVC and ASP.NET WebForms?
 Is ASP.NET MVC going to replace ASP.NET WebForms?
 MVC vs Webforms or ASP.NET Webforms Vs MVC model?
In this web development tutorial, I’ll try to answer and explain such queries.

First of all, let me clear that ASP.NET MVC is not replacing ASP.NET WebForms. Both
these development models exist and can be used to develop ASP.NET applications.
Although both has pros and cons, that we will discuss and compare here.

>>>Create ASP.NET Web API service in 3 simple steps

ASP.NET Web Forms ASP.NET MVC

ASP.NET Web Forms uses Page controller pattern ASP.NET MVC uses Front Controller approach. That

approach for rendering layout. In this approach, every approach means ,a common controller for all pages,
page has it’s own controller i.e. code-behind file that

processes the request. processes the requests.

No separation of concerns. As we discussed that every

page (.aspx) has it’s own controller (code behind i.e. Very clean separation of concerns. View and Controller are

aspx.cs/.vb file), so both are tightly coupled. neatly separate.

Because of this coupled behavior, automated testing is Testability is key feature in ASP.NET MVC. Test driven

really difficult. development is quite simple using this approach.

In order to achieve stateful behavior, viewstate is used.

Purpose was to give developers, the same experience of a ASP.NET MVC approach is stateless as that of the web. So

typical WinForms application. here no concept of viewstate.

Statefulness has a lots of problem for web environment in As controller and view are not dependent and also no

case of excessively large viewstate. Large viewstate viewstate concept in ASP.NET MVC, so output is very

means increase in page size. clean.

No Page Life cycle like WebForms. Request cycle is simple

ASP.NET WebForms model follows a Page Life cycle. in ASP.NET MVC model.

Along with statefulness, microsoft tries to introduce

server-side controls as in Windows applications. Purpose

was to provide somehow an abstraction to the details of

HTML. In ASP.NET Web Forms, minimal knowledge of In MVC, detailed knowledge of HTML, JavaScript and

HTML, JavaScript and CSS is required. CSS is required.

Above abstraction was good but provides limited control

over HTML, JavaScript and CSS which is necessary in

many cases. Full control over HTML, JavaScript and CSS.

With a lots of control libraries availability and limited

knowledge of other related technologies, ASP.NET

WebForms is RAD(Rapid Application Development)

approach. It’s a step back. For developers decrease in productivity.

It’s good for small scale applications with limited team It’s better as well as recommended approach for large-scale

size. applications where different teams are working together.

>>>Create ASP.NET Web API service in 3 simple steps


This article explains the pros and cons associated with each model. And in last point,
I concluded that which model is suitable in a scenario. Hopefully, it will be a
reference for choosing the right approach.

Top 5 New Features in ASP.NET Web


API 2

ASP.NET Web API 2 has been released with a number of new exciting features. In this web
development post, I’ll try to discuss new features of it which can be considered the top 5.

1. Attribute Routing
Along with convention-based routing, Web API 2 now supports attribute routing as well.
In case of convention-based routing, we can define multiple route templates. When a request
comes, it will be matched against already defined route templates, and forwarded to specific
controller action according to matched template.
You can see the following default route template in routing table for Web API:

Config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{Controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);

This routing approach has benefits that all routing templates are defined at one common location
but for certain URI patterns, it really becomes difficult to support (like nested routing on same
controller).
With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as
well. Following shows an example of a URI pattern with attribute routing.

URI Pattern –> books/1/authors

[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ….. }

2. CORS – Cross Origin Resource Sharing


Normally, browsers don’t allow making cross-domain calls due to same-origin policy and we
know that. So, what exactly is CORS (Cross Origin Resource Sharing)?
CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the
domain which actually rendered that specific web page. CORS is compliant with W3C standards
and now ASP.NET Web API has support for it in version 2.

3. OWIN (Open Web Interface for .NET) self hosting


ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi.
OwinSelfHost.
According to http://owin.org/
“OWIN defines a standard interface between .NET web servers and web applications. The goal
of the OWIN interface is to decouple server and application, encourage the development of
simple modules for .NET web development, and, by being an open standard, stimulate the open
source ecosystem of .NET web development tools.”

So, according to above description, OWIN is an ideal option for self hosting a web application in
a process other than IIS process.
There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some
may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web
API frameworks.

4. IHttpActionResult Along with the existing two approaches of creating response from
controller action, ASP.NET Web API 2 now supports another way of doing the same.
IHttpResponseMessage is basically an interface which acts as a factory for
HttpResponseMessage. It’s very powerful because it extensify web api. Using this approach we
can compose any specific type of response.
Please follow the link to know how to serve HTML with IHttpActionResult.
5. Web API OData
The Open Data Protocol (OData) is actually a web protocol for querying and updating data.
ASP.NET Web API 2 has added support for $expand, $select, and $value options for OData. By
using these options, we can control the representation that is returned from the server.
 $expand: Normally, response doesn’t include related entities if we query an
OData collection. By using $expand, we can get related entities inline in
response.
 $select: It’s used if we wanted to include subset of properites in response
instead of all.
 $value: It allows to return raw value of the property instead returning in
OData format.
Top 10 ASP.NET Web API Interview
Questions

In this ASP.NET Interview Questions Series, so far we have covered questions


related to the core of ASP.NET technology. In this part-6 of ASP.NET
Tutorial series, we will cover top 10 interview questions related to ASP.NET Web
API framework.What we have covered so far can be summarized as follows:
 Part 1 – Interview Questions on State Management and ASP.NET Controls.
 Part 2 – ASP.NET Interview Questions on Globalization and Localization, Culture
etc.
 Part 3 – Interview Questions on Cache Management & Security in ASP.NET.
 Part 4 – ASP.NET Interview Questions on Security in Detail.
 Part 5 – Top 10 ASP.NET AJAX Interview Questions
So, let’s dive deeper to understand ASP.NET Web API technology concepts through
Interview Questions.

What is ASP.NET Web API?

ASP.NET Web API is a framework that simplifies building HTTP services for broader
range of clients (including browsers as well as mobile devices) on top of .NET
Framework. Using ASP.NET Web API we can create non-SOAP based services like
plain XML or JSON strings etc. with many other advantages including:

 Create resource-oriented services using the full features of HTTP.


 Exposing services to a variety of clients easily like browsers or mobile devices
etc.

What are the advantages of using ASP.NET Web API?

Using ASP.NET Web API has a number of advantages, but core of the advantages
are:

 It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE
etc for all CRUD operations.
 Complete support for routing.
 Response generated in JSON or XML format using MediaTypeFormatter.
 It has the ability to be hosted in IIS as well as self-host outside of IIS.
 Supports Model binding and Validation.
 Support for OData.
 and more….
For implementation on performing all CRUD operations using ASP.NET Web API, click
here.
What new features are introduced in ASP.NET Web API 2.0?

More new features introduced in ASP.NET Web API framework v2.0 are as follows:

 Attribute Routing
 External Authentication
 CORS (Cross-Origin Resource Sharing)
 OWIN (Open Web Interface for .NET) Self Hosting
 IHttpActionResult
 Web API OData
You can follow a good Web API new feature details on Top 5 New Features in
ASP.NET Web API 2 here.

WCF Vs ASP.NET Web API?

Actually, Windows Communication Foundation is designed to exchange standard


SOAP-based messages using variety of transport protocols like HTTP, TCP,
NamedPipes or MSMQ etc. On the other hand, ASP.NET API is a framework for
building non-SOAP based services over HTTP only. For more details, please follow
here.

Is it true that ASP.NET Web API has replaced WCF?

It’s a misconception that ASP.NET Web API has replaced WCF. It’s another way of
building non-SOAP based services, for example, plain XML or JSON string etc.

Yes, it has some added advantages like utilizing full features of HTTP and reaching
more clients such as mobile devices etc.

But WCF is still a good choice for following scenarios:


 If we intended to use transport other than HTTP e.g. TCP, UDP or Named Pipes.
 Messag Queuing scenario using MSMQ.
 One-way communication or Duplex communication
A good understanding for WCF(Windows Communication Foundation), please
follow WCF Tutorial.

MVC Vs ASP.NET Web API?

As in previous ASP.NET Web API Interview Questions, we discussed that purpose of


Web API framework is to generate HTTP services that reaches more clients by
generating data in raw format, for example, plain XML or JSON string. So, ASP.NET
Web API creates simple HTTP services that renders raw data. On the other hand,
ASP.NET MVC framework is used to develop web applications that generates Views
as well as data. ASP.NET MVC facilitates in rendering HTML easy.
For ASP.NET MVC Interview Questions, follow the link.

How to return View from ASP.NET Web API method?

(A tricky Interview Question) No, we can’t return view from ASP.NET Web API
Method. As we discussed in earlier interview question about difference between
ASP.NET MVC and Web API that ASP.NET Web API creates HTTP services that
renders raw data. Although, it’s quite possible in ASP.NET MVC application.

How to restrict access to Web API method to specific HTTP Verb?

Attribute programming plays it’s role here. We can easily restrict access to an
ASP.NET Web API method to be called using a specific HTTP method. For example,
we may required in a scenario to restrict access to a Web API method through HTTP
POST only as follows:

[HttpPost] public void UpdateStudent(Student aStudent)


{ StudentRepository.AddStudent(aStudent); }

Can we use Web API with ASP.NET Web Form?

Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be
used with ASP.NET Web Form. It can be done in three simple steps as follows:

1. Create a Web API Controller.


2. Add a routing table to Application_Start method of Global.asax.
3. Make a jQuery AJAX Call to Web API method and get data.
jQuery call to Web API for all CRUD (Create, Retrieve, Update, Delete) operations
can be found here.

How we can provide an alias name for ASP.NET Web API action?

We can provide an alias name for ASP.NET Web API action same as in case of
ASP.NET MVC by using “ActionName” attribute as follows:
[HttpPost] [ActionName("SaveStudentInfo")] public void
UpdateStudent(Student aStudent) { StudentRepository.AddStudent(aStudent); }

In this ASP.NET Tutorial, we covered most important Interview Questions on


ASP.NET Web API framework. Hopefully, it will be helpful for Web API developer
Interview but along with these questions, do the practical implementation as much
as you can. In Practical guide to ASP.NET Web API, you can find a good step by
step approach for understanding and implementing ASP.NET Web API
services. Previous <<< ASP.NET Interview Questions – Part -5

Top 10 ASP.NET AJAX Interview


Questions

Exploring key features/capabilities of ASP.NET and getting answers for ASP.NET


Interview Questions in this Web Development Tutorial series, we have reached
this Part-5 with a set of questions on ASP.NET and AJAX (Asynchronous JavaScript
and XML).What we have covered so far can be summarized as follows:
 Part 1 – Interview Questions on State Management and ASP.NET Controls.
 Part 2 – ASP.NET Interview Questions on Globalization and Localization, Culture
etc.
 Part 3 – Interview Questions on Cache Management & Security in ASP.NET.
 Part 4 – ASP.NET Interview Questions on Security in Detail.
So, let’s keep exploring further ASP.NET technology concepts through Interview
Questions Series.

Define AJAX?

AJAX stands for “Asynchronous JavaScript and XML”. It’s basically a technique for
creating Rich Internet Applications (RIA) that are faster as well as more interactive,
using a combination of commonly used techniques as HTML/XHTML, CSS, Document
Object Model (DOM), JavaScript, XML/XSLT and XMLHttpRequest object.

XMLHttpRequest object is the key basis of AJAX and makes it possible to


communicate with the web server asynchronously and exchange data.

Please elaborate XMLHttpRequest Object further?

XMLHttpRequest is the core object in AJAX technology regardless of any


implementation. XMLHttpRequest object is used to exchange data with a server
seamlessly. Basically JavaScript uses this Object to exchange XML as well as text
data between client and server. An AJAX implementation uses this object and
communicate with server but it doesn’t require the complete page to be refreshed.

How to send a request to server using XMLHttpRequest Object?

We can send a request to server using HTTP GET and POST methods as follows:

//Simple GET Request

var xmlHttp = new XMLHttpRequest();

xmlHttp.open(“GET”, “TestFile.txt”, true);

xmlHttp.send();

//Simple POST Request

var xmlHttp = new XMLHttpRequest();

xmlHttp.open(“POST”, “TestFile.txt”, true);

xmlHttp.send();

What is ASP.NET AJAX?

Microsoft provided an implementation of AJAX functionality known as ASP.NET


AJAX.
As we discussed in above interview question that AJAX is a combination of various
techniques, so Microsoft simplified the usage of these techniques with its own
implementation. ASP.NET AJAX is a set of extensions to ASP.NET and comes with
reusable AJAX controls. Using ASP.NET AJAX, we can develop applications that can
update partial page instead of a complete page refresh.

Difference between Synchronous and Asynchronous Postback?

In Synchronous postback, complete web page is sent to server and in return


rendering the output (i.e. complete page), whereas in case of Asynchronous
postback, partial page goes to the server and renders only partial (required) part of
the page.

What are the basic controls in ASP.NET AJAX?

Following controls can be considered as core AJAX controls in ASP.NET.

 ScriptManager
 ScriptManagerProxy
 UpdatePanel
 UpdateProgress
 Timer
Later more controls are added to ASP.NET AJAX library e.g. Script Loader, Client
Data Context, Client Data Access, jQuery Integration etc.

What is a ScriptManager in ASP.NET AJAX?

In order to use AJAX functionality on a web page, we add a ScriptManager control to


the page in most of the scenarios, because ScriptManager control register AJAX
library scripts to that particular web page. We can have only one ScriptManager per
page.

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>


ScriptManager basically manages all ASP.NET AJAX resources of a web page, creates
proxies for asynchronous web service call and also manages partial page updates…
etc.

ScriptManager Vs ScriptManagerProxy?

As we understand that we can have only one ScriptManager control on a page but
we can have multiple ScriptManagerProxy controls.
Consider a scenario that we have ScriptManager in our MasterPage that is available
for all content pages. Now, we wanted to register a web service in a particular page.
So, we will not add another ScriptManager to that page instead we will add
ScriptManagerProxy to it in order to avoid error.

What is the role of UpdatePanel in ASP.NET AJAX?


UpdatePanel is the control that facilitate the partial page rendering functionality in
an ASP.NET application. As discussed earlier that using ASP.NET AJAX, we can
communicate with a web server asynchronously and update a part of a page without
a complete page postback. In order to apply partial page update/rendering, we can
add one or more UpdatePanel controls to our ASP.NET Page as follows:

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>

<ContentTemplate>

<asp:Label ID=”lblPanel” runat=”server” Text=”Update Panel


Added.”></asp:Label><br />

<asp:Button ID=”btnTestButton”
runat=”server”
OnClick=”btnTestButton_Click”
Text=”Test Button” />

</ContentTemplate>

</asp:UpdatePanel>

What are the limitations of AJAX?

 AJAX on an application will not work if JavaScript is disabled.


 In some scenarios, it exposes vulnerability.
 It will always be difficult to bookmark application state.
 Application behavior may be slow in some scenarios, because of different
loading time of controls on a single page.
Hopefully, this ASP.NET Tutorial will clear more concepts about AJAX technology
usage in ASP.NET.

4 simple steps to enable tracing in


WCF

Tracing mechanism in Windows Communication Foundation is based on the


classes that resides in System.Diagnostic namespace.Important classes are Trace,
TraceSource and TraceListener. For better understanding we will follow step by step
approach in this WCF Tutorial.Following are the steps to enable tracing in WCF:
1. Configuring WCF to emit tracing information/Define Trace Source, we have the
following options:
 System.ServiceModel
 System.ServiceModel.MessageLogging
 System.ServiceModel.IdentityModel
 System.ServiceModel.Activation
 System.Runtime.Serialization
 System.IO.Log
 Cardspace
In configuration file, we will define a source to enable this configuration as follows:

<source name=”System.ServiceModel.MessageLogging”>

2. Setting Tracing Level, we have the following available options, we need to set this
tracing level to available options other than default “Off”:
 Off
 Critical
 Error
 Warning
 Information
 Verbose
 ActivityTracing
 All
In configuration file, we can choose above values for switchValue attribute as
follows:
<source name=”System.ServiceModel.MessageLogging”
switchValue=”Information”>
3. Configuring a trace listener
For configuring a trace listener, we will add following to config file.
<listeners>
<add name=”messages”
type=”System.Diagnostics.XmlWriterTraceListener”
initializeData=”d:logsmessages.svclog” />
</listeners>
4. Enabling message logging
<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage=”true”
logMalformedMessages=”false”
logMessagesAtServiceLevel=”true”
logMessagesAtTransportLevel=”false”
maxMessagesToLog=”3000″
maxSizeOfMessageToLog=”2000″/>
</diagnostics>
</system.serviceModel>
logEntireMessage: By default, only the message header is logged but if we set it to
true, entire message including message header as well as body will be logged.
logMalformedMessages: this option log messages those are rejected by WCF stack at
any stage are known as malformed messages.
logMessagesAtServiceLevel: messages those are about to enter or leave user code.
logMessagesAtTransportLevel: messages those are about to encode or decode.
maxMessagesToLog: maximum quota for messages. Default value is 10000.
maxSizeOfMessageToLog: message size in bytes.

Putting all this together, configuration file will appear like this.
<system.diagnostics>
<sources>
<source name=”System.ServiceModel.MessageLogging”>
<listeners>
<add name=”messagelistener”
type=”System.Diagnostics.XmlWriterTraceListener”
initializeData=”d:logsmyMessages.svclog”></add>
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage=”true”
logMessagesAtServiceLevel=”false”
logMessagesAtTransportLevel=”false”
logMalformedMessages=”true”
maxMessagesToLog=”5000″
maxSizeOfMessageToLog=”2000″>
</messageLogging>
</diagnostics>
</system.serviceModel>
Note: In this case, information will be buffered and not published to file
automatically, So, we can set the autoflush property of the trace under sources as
follows:
autoflush =”true” />

What’s new in WCF v4.5

In part-1 of this WCF Tutorial series, we have gone through new features introduced
in Windows Communication Foundation v3.5 and v4.0. In this part, we will highlight
new features of WCF 4.5.

New Features in WCF v4.5

 Simplified Generated Configuration files, generated configuration file on


client will only have non-default binding configuration. more…
 Validating WCF Configuration is now part of v4.5. While compiling if there
are some validation errors with configuration file, it will be displayed as
warnings in Visual Studio. more…
 WCF 4.5 support for Task-based Asynchronous programming model.
 Contract First Development is now supported. Only contract will be
generated in service.cs, if we use SvcUtil.exe with “/ServiceContract” switch
while generating proxy.
 ASP.NET Compatibility Mode changed to enable WCF service to participate in
ASP.NET Pipeline just like ASMX services.
 Tooltip and intellisense support in Configuration files. more…
 XmlDictionaryReaderQuotas default values has been changed.
 v4.5 allows to create an endpoint that supports Multiple Authentication
Types.
 Automatic HTTPS endpoints in IIS.
 Improvements in Streaming, support for real asynchronous streaming, no
blockage of one thread per client as with previous versions.
 Support for UDP transport, using UDP one way messages are very fast.
 BasicHttpsBinding, new security configuration option.
 In order to have bidirectional communication with better performance like
TCP, WebSocket is the right choice. WCF v4.5 introduces NetHttpBinding and
NetHttpsBinding bindings for supporting WebSockets.
 Single WSDL Document, now we can create WSDL information in one
file. more…
 IDN (Internationalized Domain Names) support means WCF Service can
be called using IDN names by client.
 Compression support is now available for Binary Encoder in WCF 4.5
through CompressionFormat property.
 ChannelFactory Cache, WCF 4.5 now support for caching Channel Factories
to reduce overhead associated while creating a ChannelFactory instance.
 WCF Service can be configured using config file or through code. In
v4.5, configuration through code has been simplified by defining a public
static method (i.e. configure) instead of creating a ServiceHostFactory.
In order to look for comparison with previous versions, please follow the link to WCF
3.5 and WCF 4.0

Difference between a Postback and a


Callback in ASP.NET

“A postback is a request sent from a client to server from the same page, user is
already working with.“ASP.NET was introduced with a mechanism to post an HTTP
POST request back to the same page. It’s basically posting a complete page back to
server (i.e. sending all of its data) on same page. So, the whole page is refreshed.In
order to understand how this postback mechanism works in ASP.NET, follow the
simple steps:
 Add a new ASP.NET web form page to a project e.g. WebForm1.aspx.
 View the page code in HTML Source view. You will find something like following
screen.


Look the form line of code.
<form id=”form1″ runat=”server”>
It represents a server-side implementation of form control.
 Now just run the application to see WebForm1.aspx page and view its source
code. HTML source of the page will display form element as follows:
<form method=”post” action=”WebForm1.aspx” id=”form1″>You can see that
an HTML form element generated with an HTTP method as “POST” and
action=”WebForm1.aspx”. So, if a submit button is clicked, the page will
postback to itself by default.
Series of ASP.NET Interview Questions and Answers

“A callback is generally a call for execution of a function after another function has
completed.”
But if we try to differentiate it from a postback then we can say: It’s a call made to
the server to receive specific data instead of whole page refresh like a postback. In
ASP.NET, its achieved using AJAX, that makes a call to server and updating a part of
the page with specific data received.

Top 10 ASP.NET Interview Questions


and Answers
“ASP.NET is a web application development framework for building web sites and
web applications that follows object oriented programming approach”.Following are
the top 10 commonly asked Interview Questions with detailed answers on ASP.NET
technology. I have also prepared a comprehensive Tutorial Series of ASP.NET
Interview Questions that you can further read through to better prepare for your
ASP.NET interview.

What is the concept of Postback in ASP.NET?


A postback is a request sent from a client to server from the same page user is
already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to
the same page. It’s basically posting a complete page back to server (i.e. sending all
of its data) on same page. So, the whole page is refreshed.
Another concept related to this approach is “Callback” that is also asked sometimes
during a technical interview question. Click here to understand Postback Vs Callback
in ASP.NET.
Difference between ASP.NET WebForms and ASP.NET MVC?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In
this approach, every page has it’s own controller i.e. code-behind file that processes
the request. On the other hand, ASP.NET MVC uses Front Controller approach. In
this approach a common controller for all pages, processes the requests.
Please follow for detailed information on WebForms Vs MVC.

Please briefly explain ASP.NET Page life Cycle?


ASP.NET page passes through a series of steps during its life cycle. Following is the
high-level explanation of life cycle stages/steps.

Initialization: Controls raise their Init event in this stage.Objects and variables are
initializes for complete lifecyle of request.

LoadViewState: is a post back stage and loads the view state for the controls that
enabled its view state property.

LoadPostBackData: is also a post back stage and loads the data posted for the
controls and update them.

Load: In this stage page as well as all the controls raise their Load event. Till this
stage all the controls are initialized and loaded. In most of the cases, we are coding
this event handler.RaisePostBackEvent: is again a postback stage. For example,
it’s raise against a button click event. We can easily put our code here to perform
certain actions.SaveViewState: Finally, controls state is saved in this stage before
Rendering HTML.Render: This is the stage where HTML is generated for the
page.Dispose: Lastly, all objects associated with the request are cleaned up.
For very detailed explanation of Page Life Cycle is explained here.

What is the difference between custom controls and user controls?


Custom controls are basically compiled code i.e. DLLs. These can be easily added to
toolbox, so it can be easily used across multiple projects using drag and drop
approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy
to create but tightly couple with respect to User Interface and code. In order to use
across multiple projects, we need to copy and paste to the other project as well.
What is the concept of view state in ASP.NET?
As in earlier question, we understood the concept of postback. So, in order to
maintain the state between postbacks, ASP.NET provides a mechanism called view
state. Hidden form fields are used to store the state of objects on client side and
returned back to server in subsequent request (as postback occurs).
Difference between Response.Redirect and Server.Transfer?
In case of Response.Redirect, a new request is generated from client-side for
redirected page. It’s a kind of additional round trip. As new request is generated
from client, so the new URL is visible to user in browser after redirection.
While in case of Server.Transfer, a request is transferred from one page to another
without making a round trip from client. For the end user, URL remains the same in
browser even after transferring to another page.
Please briefly explain the usage of Global.asax?
Global.asax is basically ASP.NET Application file. It’s a place to write code for
Application-level events such as Application start, Application end, Session start and
end, Application error etc. raised by ASP.NET or by HTTP Modules.
There is a good list of events that are fired but following are few of the important
events in Global.asax:

 Application_Init occurs in case of application initialization for the very first time.
 Application_Start fires on application start.
 Session_Start fires when a new user session starts
 Application_Error occurs in case of an unhandled exception generated from
application.
 Session_End fires when user session ends.
 Application_End fires when application ends or time out.

What are the different types of Validation controls in ASP.NET?


In order to validate user input, ASP.NET provides validation server controls. All
validation controls inherits from BaseValidator class which contains the common
validation properties and methods like ControlToValidate, Enabled, IsValid,
EnableClientScript, ValidationGroup,Validate() etc.
ASP.Net provides a range of validation controls:

 RequiredFieldValidator validates compulsory/required input.


 RangeValidator validates the range. Validates that input falls between the given
range values.
 CompareValidator validates or compares the input of a control with another
control value or with a fixed value.
 RegularExpressionValidator validates input value against a defined regular
expression pattern.
 CustomValidator allows to customize the validation logic with respect to our
application logic.
 ValidationSummary displays all errors on page collectively.

What are the types of Authentication in ASP.NET?


There are three types of authentication available in ASP.NET:
 Windows Authentication: This authentication method uses built-in windows
security features to authenticate user.
 Forms Authentication: authenticate against a customized list of users or users
in a database.
 Passport Authentication: validates against Microsoft Passport service which is
basically a centralized authentication service.

What are Session state modes in ASP.NET?


ASP.NET supports different session state storage options:
 In-Process is the default approach. It stores session state locally on same web
server memory where the application is running.
 StateServer mode stores session state in a process other than the one where
application is running. Naturally, it has added advantages that session state is
accessible from multiple web servers in a Web Farm and also session state will
remain preserved even web application is restarted.
 SQLServer mode stores session state in SQL Server database. It has the same
advantages as that of StateServer.
 Custom modes allows to define our custom storage provider.
 Off mode disables session storage.
I strongly believe that every asp.net web developer should prepare and understand
the above discussed interview questions. You can follow here for Comprehensive list
of ASP.NET Interview Questions.

Top 10 HTML5 Interview Questions


It’s a collection of selected top 10 HTML5 Interview Questions and Answers.
These are the most frequently asked interview questions for web developers.

1.What’s new HTML 5 DocType and Charset?

As HTML 5 is now not subset of SGML so its DocType is simplified as follows:


<!doctype html>
And HTML 5 uses UTF-8 encoding as follows:
<meta charset=”UTF-8″>

2.How can we embed Audio in HTML 5?

HTML 5 comes with a standard way of embedding audio files. Supported audio
formats are MP3, Wav and Ogg.

<audio controls>
<source src=”jamshed.mp3″ type=”audio/mpeg”>
Your browser does’nt support audio embedding feature.
</audio>

3.How can we embed Video in HTML 5?

Same like audio, HTML 5 defined standard way of embedding video files.Supported
video formats are MP4, WebM and Ogg.

<video width=”450″ height=”340″ controls>


<source src=”jamshed.mp4″ type=”video/mp4″>
Your browser does’nt support video embedding feature.
</video>

4.What are the new media element in HTML 5 other than audio and
video?

HTML 5 has strong support for media. Other than audio and video tags, it comes
with the following tags:

 <embed> acts as a container for external application.


 <track> defines text track for media.
 <source> is helpful for multiple media sources for audio and video.
5.What is the usage of canvas Element in HTML 5?

<canvas> is an element in HTML5 which we can use to draw graphics with the help
of scripting (which is most probably JavaScript).
This element behaves like a container for graphics and rest of things will be done by
scripting. We can draw images, graphs and a bit of animations etc using <canvas>
element.

<canvas id=”canvas1″ width=”300″ height=”100″>


</canvas>

6.What are the different types of storage in HTML 5?

HTML 5 has the capability to store data locally. Previously it was done with the help
of cookies.
Exciting thing about this storage is that its fast as well as secure.

There are two different objects which can be used to store data.

 localStorage object stores data for a longer period of time even if the browser
is closed.
 sessionStorage object stores data for a specific session.

7.What are the new Form Elements introduced in HTML 5?

There are a number of new form elements has been introduced in HTML 5 as
follows:

 datalist
 datetime
 output
 keygen
 date
 month
 week
 time
 number
 range
 email
 url

8.What are the deprecated Elements in HTML5 from HTML4?

Elements that are deprecated from HTML 4 to HTML 5 are:

 frame
 frameset
 noframe
 applet
 big
 center
 basefront

9.What are the new APIs provided by HTML 5 standard?

HTML 5 standard comes with a number of new APIs. Few of it are as follows:

 Media API
 Text Track API
 Application Cache API
 User Interaction
 Data Transfer API
 Command API
 Constraint Validation API
 History API
 and many more….

10.What is the difference between HTML 5 Application Cache and regular


HTML Browser Cache?

One of the key feature of HTML 5 is “Application Cache” that enables us to make an
offline version of a web application. It allows to fetch few or all of website contents
such as HTML files, CSS, images, javascript etc locally. This feature speeds up the
site performance. This is achieved with the help of a manifest file defined as follows:
<!doctype html>
<html manifest=”example.appcache”>
…..
</html>

As compared with traditional browser caching, Its not compulsory for the user to
visit website
contents to be cached.

7 jQuery Code Snippets every web


developer must have

jQuery extensively simplified web developer’s life and has become a leader in javascript
available libraries. There are a lot of useful jQuery snippets available but here in this post I am
going to share 7 basic and widely used code snippets that every front-end web developer must
have. Even for those who are new to jQuery can easily understand and get benefit from these
routinely used code snippets.

1. Print Page Option


Providing option to print a page is a common task for web developers. Following is the available
code:

<!– jQuery: Print Page –>


$(‘a.printPage’).click(function(){
window.print();
return false;
});

<!– HTML: Print Page –>


<div>
<a class=”printPage” href=”#”>Print</a>
</div>

2. Helping Input Field/Swap Input Field


In order to make an Input Text field helpful, we normally display some default text inside it (For
Example “Company Name”) and when user click on it, text disappears and user can enter the
value for it.
You can try it yourself by using the following code snippet.
<!– jQuery: Helping Input Field –>
$(‘input[type=text]‘).focus(function(){
var $this = $(this);
var title = $this.attr(‘title’);
if($this.val() == title)
{
$this.val(”);
}
}).blur(function() {
var $this = $(this);
var title = $this.attr(‘title’);
if($this.val() == ”)
{
$this.val(title);
}
});

<!– HTML: Swap Input Field –>


<div>
<input type=”text”
name=”searchCompanyName”
value=”Company Name”
title=”Company Name” />
</div>

3. Select/Deselect All options


Selecting or Deselecting all available checkbox options using a link on HTML page is common
task.

<!– jQuery: Select/Deselect All –>


$(‘.SelectAll’).live(‘click’, function(){ $
(this).closest(‘.divAll’).find(‘input[type=checkbox]‘).attr(‘checked’, true); return false; }); $
(‘.DeselectAll’).live(‘click’, function(){ $
(this).closest(‘.divAll’).find(‘input[type=checkbox]‘).attr(‘checked’, false); return false; });

<!– HTML: Select/Deselect All –>


<div class=”divAll”> <a href=”#” class=”SelectAll”>Select All</a>&nbsp; <a href=”#”
class=”DeselectAll”>Deselect All</a> <br /> <input type=”checkbox” id=”Lahore”
/><label for=”Lahore”>Lahore</label> <input type=”checkbox” id=”Karachi” /><label
for=”Karachi”>Karachi</label> <input type=”checkbox” id=”Islamabad” /><label
for=”Islamabad”>Islamabad</label> </div>
4. Disabling Right Click
For web developers, its common to disable right click on certain pages so following code
will do the job.

<!– jQuery: Disabling Right Click –>


$(document).bind(“contextmenu”,function(e){
e.preventDefault();

});

5. Identify which key is pressed.


Sometimes, we need to validate the input value on a textbox. For example, for “First
Name” we might need to avoid numeric values. So, we need to identify which key is
pressed and then perform the action accordingly.
<!– jQuery: Which key is Pressed. –>
$(‘#txtFirstName’).keypress(function(event){
alert(event.keyCode);
});

<!– HTML: Which key is Pressed. –>


<asp:TextBox ID=”txtFirstName” runat=”server”></asp:TextBox>

6. Validating an email.
Validating an email address is very common task on HTML form.

<!– jQuery: Validating an email. –>


$(‘#txtEmail’).blur(function(e) {
var sEmail = $(‘#txtEmail’).val();
if ($.trim(sEmail).length == 0) {
alert(‘Please enter valid email address’);
e.preventDefault();
}
var filter = /^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]
{2,4}|[0-9]{1,3})(]?)$/;
if (filter.test(sEmail)) {
alert(‘Valid Email’);
}
else {
alert(‘Invalid Email’);
e.preventDefault();
}
});

<!– HTML: Validating an email–>


<asp:TextBox id=”txtEmail” runat=”server” />

7. Limiting MaxLength for TextArea


Lastly, it usual to put a textarea on a form and validate maximum number of characters on it.

<!– jQuery: Limiting MaLength for TextArea –>


var MaxLength = 500;
$(‘#txtDescription’).keypress(function(e)
{
if ($(this).val().length >= MaxLength) {
e.preventDefault();}
});

<!– HTML: Limiting MaLength for TextArea–>


<asp:TextBox ID=”txtDescription” runat=”server”
TextMode=”MultiLine” Columns=”50″ Rows=”5″></asp:TextBox>

This is my selection of jQuery code snippets but jQuery is a very powerful client-side framework
and a lot more can be done using it.

Generics in c#
Generic allows declaring classes, methods, interfaces, etc without specify the type of value you are
going to store. You have to specify the type of value you are going to use when you declare the
instance to be used. So when you do that, the generic T value is replaces with the actual type you
are going to use at compilation time. See the next example to get the idea better:

//Generics.cs

namespace ConsoleApplication1
{

public class Generics

public T value;

//Program.cs (main)

namespace ConsoleApplication1

public class Program

public static void Main(string[] args)

Generics<String> g = new Generics<string>();

g.value = "String value";

//g.value = 66; Compilation Error

Console.WriteLine(g.value.ToString());

//Will show: “String value”

Converting String to Int (C# .NET)

Here I will show you some easy ways you can convertString to integer in C#. The first
way is by using the System namespace of the .NET Framework Class Library. In this
namespace you can find the "Convert" class that lets you convert a base type to another
base type.
Example:

String num = "123";

//First argument the String and second the base.


int a = System.Convert.ToInt32(num, 10);

Another way is by using the Parse function.


Example:

int b = Int32.Parse(num);

Now, if you want a method for doing these convertions, you can take a look at the
following example. For argument the String value to be converted and return the integer
for it. To make it a little interesting, the String value contains non numeric characters
until the position number 6, example: abbton4457

public int change(String s) {

String st = s.Substring(6);
int x = Int16.Parse(st);
return x;

String Manipulation (C#)


Here I will show you some useful string manipulation functions in C#.

ToUpper, ToLower function.

Coverts all the characters from a String into upper/lower case. Example:

String st = " String Manipulation in C# ";


String a3 = st.ToUpper();

Trim function.

The trim function strips all white spaces form both start and end form a given string. It has two other
variants, the TrimStart and TrimEnd.

Example:

String trimed = st.Trim();


Console.WriteLine("Original: " + st);
Console.WriteLine("Using Trim: " + "=" + trimed +"=");

String trimedStart = st.TrimStart();


Console.WriteLine("1st TrimStart: " + trimedStart + "=");

//Other TrimStart variant


char[] c = { ' ', 'S' };
String trimedStart2 = st.TrimStart(c);
Console.WriteLine("2nd TrimStart: " + trimedStart2 + "=");

ToReplace function.

The ToReplace function searches for a string/char to be replaced with a new string/char value.
Example:

String toRepalce = st.Replace("C#" , "Java");


Console.WriteLine("=" + toRepalce + "=");

Split Function

Useful function when you want to split a string using delimiter. Example:

String [] a = st.Split('g');
String first = a[0];
String second = a[1];
Console.WriteLine("=" + first + "=");
Console.WriteLine("=" + second + "=");

Remove function.

The Remove function lets you strip a specified number of characters. The first value you set indicates
the starting point and the second the total characters to strip. Example:
String a2 = st.Remove(10, 13);
Console.WriteLine("=" + a2 + "=");

Substring Function.

Removes a certain amount of characters form the 0 of the string to the used position.
Example:

String a1 = st.Substring(9);
Console.WriteLine("=" + a1 + "=");

Structures (C#)
A Structure in C# is a composite data type containing many number of different data types. A Struct
in C# can contain methods, constructors, fields, other structure type, properties, constants and
indexers.

To declare a structure you use the struct keyword:

<modifiers> struct <struct_name>

For example:

public class Program


{

public struct St { //Could be private, internal or protected

public int val;


public String text;

public static void Main(string[] args)

//Initializing the struct

St s = new St();
//Adding values to the struct members

s.text = "Using struct";


s.val = 2;

Console.WriteLine("Value: " + s.val + " - Text: " + s.text);


Console.Read();

}
}

Text file Reading and Writing in C#


This program below demonstrates the use of StreamWriter and StreamReader (both
derive form the abstract type TextWriter and TextReader respectively). The .Net
Framework has simple solutions to work with files. When working with text files there
are usually three common steps:

1- Opening the file


2- Reading/Writing
3- Closing it

Now, lets take a look at this example:

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

namespace ConsoleApplication
{
class Program
{

public static void Main(string[] args)


{

//C# Code for writing into a file we call: File.txt

FileInfo f = new FileInfo("File.txt");


StreamWriter Text = f.CreateText();
//Insert text in separate lines
Text.WriteLine("-->Line One content");
Text.WriteLine("--->Line Two Content");

//Insert text but does not create a new line


Text.Write("---->Line Three ");
Text.WriteLine("Content");

//To create new Line.


Text.Write(Text.NewLine);
Text.WriteLine(System.DateTime.Now);
Text.Close();

//Calling the method to read File.txt


readFiles();

Console.Read();

public static void readFiles()

//We open File.txt


StreamReader sr = new StreamReader("File.txt");
string lines = null;

//Here we do a while loop in order to look for none empty lines.


while ((lines = sr.ReadLine()) != null)
{
Console.WriteLine(lines);
}

sr.Close();
}

}
}
Implementing Interfaces in C#
Interfaces are a set of methods, properties and event that provides functionalities. This interces can
be implemented by C# classes or structures.

Interfaces do not provide methods of their own. They only contain methods identifiers, return values
and parameters.
This is very useful when you have certain behaviour that need to follow a set of operations, such as
manipulating a Data Base.
C# classes are allowed to implement many interfaces.

Implementing an Interfaz in a class says that the class must provide implementation to all of the
methods signatures from the interface.

Let’s write a small C# example. In this example you will see of to implement interfaces that contain
methods signatures and how a class implements this interface.

Code:
interface Interface1
{

void Method1();
void Method2();

public class Class1 : Interface1


{

public void Method1()


{
//Implementation of the method
}

public void Method2() { }

Now, you can also use interfaces that the .NET Frameworks has. In this example you will see how to
implement the Idisposable interface. The Idisposable interface supports a method called Dispose(). It
also supports a constructor and a destructor.

Also you will see in the Main class, the keyword using. It is used to create a new object and can be
manipulated only within the braces ({}). After the close brace is reached, the object will be
automatically destroyed.
Code:
class Class2 : IDisposable
{

public Class2()
{
Console.WriteLine("Constructor");
}

~Class2()
{
Console.WriteLine("Destuctor");
}

public void Dispose()


{
Console.WriteLine("Dispose from IDisposable.Dispose");
}

Main:

class Program
{

static void Main(string[] args)


{

using (Class2 myC = new Class2()) { }


}
}

Console:

MessageBox using AbortRetryIgnore Button in C#


This example is very similar to the previous one where I showed you how to write an
example using the YesNo MessageBox. Here the only difference is that the MessageBox
is with the AbortRetryIgnore Button.

Ok, now I will proceed to write a small example of this. Basicly what I want to do here is
to distinguish between the three different types of buttons that this type of MessageBox
contains. Here I will use a swith statment because I find it a little more correct.
So the complete C# code is this:

using System;

using System.Collections.Generic;
using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

private void button1_Click(object sender, EventArgs e)

DialogResult result;

result = MessageBox.Show("The Cd drive is not ready. \nReinsert and try


again!", "Error on
Drive", MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Error);

switch (result)

case DialogResult.Abort:

MessageBox.Show("Abort Selected");

break;

case DialogResult.Retry:

MessageBox.Show("Retry Selected");

break;

case DialogResult.Ignore:

MessageBox.Show("Ignore Selected");

break;

default:

break;

Result when executing:


The NullReferenceException:

The easiest way to explain how this works is by writing an example. What we are going to do
in the following example is quite simple: we are going to create an Object and initialize it
with null value. This object contains string public value type that we can malipulate. But in
this particulare case, our Object was set to null, so the CLR will catch this particular
exception:

Class Person

public class Person


{
public String name;
}
Main:
static void Main(string[] args)
{
try
{
Person p = new Person();
p = null;
p.name = "CoderG";
}
catch (NullReferenceException) {
Console.WriteLine("p set tu null, cannot be referenced");
}
}
Console:

The StackOverflowException:

This exception is catch by the CLR when it runs out of stack memory. Be aware that the CLR
has a finite amount of stack space, so if it gets full, the StackOverflowException will catch
the exception. An easy way to trigger this is by defining a recursive function that does
nothing, just call itself. Eventually, if the stack was infinite, this method will never stop, but
because it is finite, the exception catches this:

Main:

static void Main(string[] args)


{
try
{
callMe();
}
catch (StackOverflowException) {
Console.WriteLine("Stack run out of memory!!!!");
}
}
public static void callMe(){
callMe();
}
Console:

Using destructors in C#
Destructors are similar to de Constructors, almost the oposite.
The destructor is used by the CLR when objects are destroyed.
All this process happens in the background so the developer does not have to preocupate
about deleting
created objects. Writing a destructor is not necessary but if you are going to create one in
your class,
you can only add one.
The Destructors sintaxis are very similar to the constructors.
They start with the simbole ~ and the name must be the same to the class.
Also, there are a few particulares things about destructors you should know:
-No parameters are allowed here.
-As said before, you can only write one.
-You can not call a constructor like you will normally do with a method. They are automatically used
by the CLR (by the garbage collection).
-No overload or inheritances are allowed.

So let’s write a small C# class.

-Class Plane

using System;
using System.Text;

class Plane
{
public String type;
public String company;

public Plane(String t, String c){


type = t;
company = c;
Console.WriteLine("Constructor in action\n");
}

~Plane() {
type = "N/A";
company = "N/A";
Console.WriteLine("Destructor in action");
}

- Main

static void Main(string[] args)


{

Plane p = new Plane("AirBus", "Tam");

- Console

Get integer sequence primary key in C#


Here is a nice method of getting the primary key from a table. Basicly what I do here is
obtanning the first available key to insert new rows with this obtained key.

First we set the instance of the connection with the database and then we create a sql
command. After this, we open the connection and execute the command directly to the
database.
If everything executes correctly, we will obtain the first available key. If not, an
exception is going to be raised.

public int GetOid()

OleDbConnection conn = ConnectionMgr.GetInstance().GetConnection();

OleDbCommand cmd = new OleDbCommand("Select * From Oid", conn);

int oidNum = 0;

try
{

conn.Open();

oidNum = (int)cmd.ExecuteScalar();

oidNum++;

cmd = new OleDbCommand("UPDATE Oid SET lastOid=" + oidNum, conn);

cmd.ExecuteNonQuery();

catch (OleDbException ex)

throw new DatabaseException("Error updating oid", ex);

finally

conn.Close();

return oidNum;

Split function in C#
Here is a small post about using split function in c#. We are going to split a String by
using delimiters. A delimiter will tell when to split the string. So here is a fragment of
code to perform splitting.

String answer = "This$is|a|string";

char[] delimitator1 = new char[] { '$' };

char[] delimitator2 = new char[] { '|' };

string[] words = answer.Split(delimitator1);

Console.WriteLine("First word : " + words[0]);

//Note that now we split the second part of the string

String allRest = words[1];

string[] rest1 = allRest.Split(delimitator2);

Console.WriteLine("Second word : " + rest1[0]);

Console.WriteLine("Third word : " + rest1[1]);

Console.WriteLine("Fourth word : " + rest1[2]);


Output:

Xml Document creation using DOM


In this article I´ll show you how to create a .xml document using proper tags and definitions. To do
this you need to import the System.Xml library.

The idea is simple and the best way to learn this is by a small example.

Here I´ll create a XmlDocument with a couple of child elements.

Code:

XmlDocument xmlDoc = new XmlDocument();

//First, create the declaration

XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

xmlDoc.AppendChild(declaration);

XmlElement books = xmlDoc.CreateElement("BOOK");

xmlDoc.AppendChild(books);

//Child 1 for BOOK

XmlElement book1 = xmlDoc.CreateElement("book-1");

book1.SetAttribute("name", "Harry Potter");

books.AppendChild(book1);
//Child 2 for BOOK

XmlElement book2 = xmlDoc.CreateElement("book-2");

book2.SetAttribute("name", "People");

book2.SetAttribute("type", "magazine");

books.AppendChild(book2);

//Save the Xml

xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");

Output:

Xml document edition


In the previous post I showed you how to create a XmlDocument following some easy steps. The
idea now is to read the created xml and find elements by a specific tag. Then we are going to change
that value and save the edited xml.

Code:

For the first book element, we are going to add inner text:
XmlDocument xmlDoc = new XmlDocument();

//Load the Xml created previously

xmlDoc.Load(@"C:\XML\" + "xmlTest.xml");

XmlNodeList books;

books = xmlDoc.GetElementsByTagName("book-1");

//Since there is only one element with this tag, the loop is not necessary.

foreach (XmlNode node in books)

node.InnerText = "Great Book";

For the second element, we are changing the attributes values:

books = xmlDoc.GetElementsByTagName("book-2");

foreach (XmlNode node in books)

node.Attributes[0].Value = "Time";

xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");

Output:
More XML options in C#

Continuing the xml posts, in this oportunity I will show you more options to create your
XmlDocument.

Here we will see:

- Adding comment to the xml document (XmlComment)

- Adding fragment (XmlDocumentFragment)

- Creation of attributes (XmlAttribute)

- Adding information about the document Type (XmlDocumentType)

- And also, declarations and elements

Code:

XmlDocument xmlDoc = new XmlDocument();

XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

xmlDoc.AppendChild(xmlDec);

XmlElement root = xmlDoc.CreateElement("root-element");

//Adding info about the document type

XmlDocumentType docType = xmlDoc.CreateDocumentType("BOOKS", null, null, null);

xmlDoc.AppendChild(docType);

XmlAttribute xmlAtt = xmlDoc.CreateAttribute("attribute");


xmlAtt.Value = "value_for_xmlAtt";

root.SetAttributeNode(xmlAtt);

xmlDoc.AppendChild(root);

//Placing a comment in the Xml

XmlComment xmlComment = xmlDoc.CreateComment("First Book information");

root.AppendChild(xmlComment);

XmlElement book1 = xmlDoc.CreateElement("book-1");

book1.SetAttribute("name", "Harry Potter");

root.AppendChild(book1);

//Creating a Fragment

XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();

xmlDocFragment.InnerText = "---------Inner text-------";

xmlDoc.DocumentElement.AppendChild(xmlDocFragment);

XmlElement book2 = xmlDoc.CreateElement("book-2");

book2.SetAttribute("name", "Robles");

root.AppendChild(book2);

xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");

Output:
Defining methods in Structures (C#)
Normally you will see structures with only variables on it, but methods can also be
included. This is usefull when you need to write a method that works directly with the
content of the stuct.

- The first method that I will create inside the structure is a constructor. Remember that there can be
many constructores as long as the parameter list is different of each other.
- The second method you will see next is a simple bool method that return true if both values of the
structure varaibles (integers) are 50.

Ok, lets now proceed to write this example.

using System;

class Program
{

struct Point {

public int x;
public int y;

public Point(int x1, int y1) {

x = x1;
y = y1;
}

public bool check50() {

if ((x == 50) && (y == 50))


return true;

return false;
}
}

Main:

static void Main(string[] args)


{
Point p = new Point(50 , 50);
Point p2 = new Point(10, 20);

if (p.check50())
Console.WriteLine("Point p is at 50s");

else
Console.WriteLine("Point p not at 50s");

if(p2.check50())
Console.WriteLine("Point p2 is at 50s");

else
Console.WriteLine("Point p2 not at 50s");
}
}

Console:

The OutOfMemoryException

This exception is thrown by the CLR when your machine runs out of memory. Every time
you create an object using new, some memory will be reserved for it. In case there is
now enough memory, the exception will be triggered.
Let´s write an example now. Supose you want to create a Hashtable that allocated a
large capacity. If there is no memory to do this, the CLR throws the exception.
Take a look at this C# example:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
try
{
Hashtable hatb = new Hashtable(91230000);
}
catch (OutOfMemoryException)
{
Console.WriteLine("CLR out of memory");
}
}
}
}

Console:

The DivideByZeroException

This exception is quite simple: when you are dividing by 0, the CLR throws this
exception.
Take a look at this example:

class Program
{
static void Main(string[] args)
{
int a = 5;
int b = 0;
try {
int res = a / b;
}
catch(DivideByZeroException){
Console.WriteLine("You are dividing by 0");
}
}
}

Console:

Without Properties

class Student
{
static void Main(string[] args)
{
StudentMethod std = new StudentMethod();
std.SetRoll(1);
std.SetName("Abhimanyu");
Console.WriteLine("Roll: {0} and Name: {1}", std.GetRoll(), std.GetName());
Console.ReadKey();
}
}

public class StudentMethod


{
private int Roll = 1;

public int GetRoll()


{
return Roll;
}

public void SetRoll(int r)


{
Roll = r;
}

private string Name = string.Empty;

public string GetName()


{
return Name;
}

public void SetName(string n)


{
Name = n;
}
}

The StudentMethod class has four methods, two for each private field that the class
encapsulates: Roll and Name. As you can see, SetRoll and SetName assign a new values
and GetRoll and GetName return values.

Observe how Main calls the SetRoll and SetName methods, which sets Roll to 1 and
Name to "Abhimanyu" in the StudentMethod instance, std. The call to Console.WriteLine
demonstrates how to read Roll and Name from std, via GetRoll and GetName method
calls, respectively.

This is actually real pain for developers to write such a long set of Methods. Even this is
such a common pattern, that C# has embraced it in the form of a language feature
called properties.

Features of Properties

There are a few reasons to use properties, instead of public fields/methods.

(i) Properties can be virtual.


(ii) You can make the setters for a property private.
(iii) Properties have a 'special' meaning to things that inspect classes at runtime.

With Properties
class Student
{
static void Main(string[] args)
{
StudentMethod std = new StudentMethod();
std.Roll = 1;
std.Name = "Abhimanyu";
Console.WriteLine("Roll: {0} and Name: {1}", std.Roll, std.Name);
Console.ReadKey();
}
}

public class StudentMethod


{
public int Roll { get; set; }
public string Name { get; set; }
}

Notice how the get and set accessors in above example do not have implementations, it
is just an auto-implemented property. In an auto-implemented property, the C#
compiler creates the backing store field behind the scenes, giving the same logic that
exists with traditional properties, but saving you from having to use all of the syntax of
the traditional property. As you can see in the Main method, the usage of an auto-
implemented property is exactly the same as traditional properties.

shortcut way to create properties in c-sharp


You could type "prop" and then press tab, that will generate the following.

public TYPE Type { get; set; }

Then you change "TYPE" and "Type"

public string myString {get; set;}

You can also get the full property typing "propfull" and then tab, that would generate the field and
the full property.

private int myVar;


public int MyProperty {
get { return myVar;}
set { myVar = value;} }

This was a read and write property, but you can also create read-only properties or
write-only properties.

Read-Only Properties

class Student
{
static void Main(string[] args)
{
StudentMethod std = new StudentMethod(1, "Abhimanyu");
Console.WriteLine("Roll: {0} and Name: {1}", std.ro, std.na);
Console.ReadKey();
}
}

public class StudentMethod


{
private int Roll = 1;
private string Name = string.Empty;

public StudentMethod(int r, string n)


{
Roll = r;
Name = n;
}

public int ro
{
get
{
return Roll;
}
}

public string na
{
get
{
return Name;
}
}
}

The StudentMethod class in above example has two read-only properties, Roll and
Name. You can tell that each property is read-only because they only have get accessor.
At some time, values for the Roll and Name must be assigned, which is the role of the
constructor.

The Main method of the Student class instantiates a new StudentMathod object named
std. The instantiation of std uses the constructor of StudentMethod class, which takes int
and string type parameters. In this case, the values are 1 as r and "Abhimanyu" as n.
This initializes the Roll and Name fields of std.

Since the Roll and Name properties of the StudentMethod class are read-only, there is no
other way to set the value of the Roll and Name fields. If you inserted std.Roll = 1 into
the listing, the program would not compile, because Roll is read-only; the same with
Name field. When the Roll and Name properties are used in Console.WriteLine, they work
fine. This is because these are read operations which only invoke the get accessor of the
Roll and Name properties.

Write-Only Properties
class Student
{
static void Main(string[] args)
{
StudentMethod std = new StudentMethod();
std.ro = 1;
std.na = "Abhimanyu";

std.DisplayStudentMethod();

Console.ReadKey();
}
}

public class StudentMethod


{
private int Roll = 1;
private string Name = string.Empty;

public void DisplayStudentMethod()


{
Console.WriteLine("Roll: {0} and Name: {1}", Roll, Name);
}

public int ro
{
set
{
Roll = value;
}
}

public string na
{
set
{
Name = value;
}
}
}

This time, the get accessor is removed from the Roll and Name properties of the
StudentMethod class. The set accessors have been added, assigning value to the backing
store fields, Roll and Name.

The Main method of the Student class instantiates the StudentMethod class with a
default constructor. Then it uses the ro and na properties of std to set the Roll and Name
fields of std to 1 and "Abhimanyu", respectively. This invokes the set accessor of Roll
and Name properties from the std instance.

is and as Operator in C#
Introduction

Look at the example given below,

Circle c = new Circle(32);

object o = c;

int i = (int)o; // it compiles okay but throws an exception at runtime

Here runtime is more suspicious, if the type of object in memory does not match the cast, the
runtime will throw an InvalidCastException. We should be prepared to catch this exception and
handle it appropriately if it occurs. However, catching an exception and attempting to recover in
the event that the type of an object is not what we expected it to be is a rather cumbersome
approach. C# provides two more very useful operators that can help us to perform casting in a
much more elegant manner by using is and as operators. Let's have some talk on is and as
operators too.

is Operator

is operator is used to check whether the run-time type of an object is compatible with a given type
or not. In other word, we use is operator to verify that the type of an object is what we expect it
to be. Let's look its syntax:

expression is type

Example of is Operator

using System;

class Class1

class Class2

public class IsTest

public static void Test(object o)

{
Class1 a;

Class2 b;

if (o is Class1)

Console.WriteLine("o is Class1");

a = (Class1)o;

else if (o is Class2)

Console.WriteLine("o is Class2");

b = (Class2)o;

else

Console.WriteLine("o is neither Class1 nor Class2.");

public static void Main()

Class1 c1 = new Class1();

Class2 c2 = new Class2();

Test(c1);

Test(c2);

Test("Passing String Value instead of class");

Console.ReadKey();

}
In above example, I'll be checking object o is class or not. If passed argument is not class then
application will jump to message 'o is neither class1 nor class2'.

as Operator

as Operator is used to perform conversions between compatible types. Actually, as operator fulfills
a similar role like is but in a slightly truncated manner. Let's look its syntax:

expression as type

Example of is Operator:

using System;

class Class1

class Class2

public class IsTest

public static void Main()

object[] myObjects = new object[6];

myObjects[0] = new Class1();

myObjects[1] = new Class2();

myObjects[2] = "string";

myObjects[3] = 32;

myObjects[4] = null;

for (int i = 0; i < myObjects.Length; ++i)

string s = myObjects[i] as string;

Console.Write("{0}:", i);

if (s != null)
Console.WriteLine("'" + s + "'");

else

Console.WriteLine("not a string");

Console.ReadKey();

In above example, each and every value is being casted into string by using as operator and
assigning it to s string variable which comes at console.

Strings in C# - Part 2

Introduction

String (string) is an alias type of the System.String class. This class provides a set of methods for
working with strings. Let's list some of them that we will cover in this article.

PadLeft()/PadRight(): Returns copies of the current string that has been padded with specific data.

Remove()/Replace(): Receives copy of string with modifications. Deletes a specified number of


characters from this instance beginning at a specified position.

Split(): Separates strings by a specified set of characters and places these strings into an array of
strings.

Trim(): Trim method removes white spaces from the beginning and end of a string.

TrimStart(): Selectively removes a series of characters from the starting position.

TrimEnd(): Remove all trailing punctuations from string.

Substring(): Returns a string that represents a substring of the current string.


ToCharArray(): Returns a character array representing the current string.

Let's discuss about all of them above.

PadLeft()/PadRight() Methods

In C#, PadLeft and PadRight methods can be used to insert characters or can be used to add
characters to the beginning and end of text.

Let's look at program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)

//Simple Use

string str1 = "Abhimanyu";

str1 = str1.PadLeft(20);

Console.WriteLine(str1);

string str2 = "Kumar";

str2 = str2.PadRight(30);

Console.WriteLine(str2); //it will not be visible as it is very close to axis

//Padding with symbol

string str3 = "Vatsa";

char padWith = '*';

Console.WriteLine(str3.PadLeft(20, padWith));
string str4 = "Good Luck";

char padWith1 = '-';

Console.WriteLine(str4.PadLeft(10, padWith1));

Console.ReadKey();

The above code will produce the following output:

Remove()/Replace() Methods

As both names suggest, Remove is used to remove characters from a string and Replace is used to
replace the characters from string. This is often more useful with StringBuilder.

Let's look at program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)


{

//Using Remove

string str1 = "abhimanyu";

str1 = str1.Remove(str1.Length - 1); //Remove(total_length - 1) means will not display


last word

Console.WriteLine(str1);

string str2 = "kumar";

str2 = str2.Remove(0, 2); //Remove(start_location, number_of_digit_to_remove)

Console.WriteLine(str2);

//Using Replace

string str3 = "abhimanyu kumar";

Console.WriteLine(str3);

string str4 = str3.Replace("kumar", "kumar vatsa");

Console.WriteLine(str4);

Console.ReadKey();

The above code will produce the following output:

Split() Method

Separates strings by a specified set of characters and places these strings into an array of strings.
Assume, if you want to split strings on different characters with single character or string
delimiters. For example, split a string that contains "\r\n" sequences, which are Windows newlines.
Let's look at program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)

//Using Split normally

string str1 = "abhimanyu kumar vatsa";

string[] newWordLines = str1.Split(' '); //this will create array of string

foreach (string word in newWordLines)

Console.WriteLine(word);

//Using Split using method1

string str2 = "abhimanyu,dhananjay,sam,suthish,sam";

foreach (string s in Split1(str2, ',')) //Calling Method1 each time

Console.WriteLine(s);

//Using Split using method2

string str3 = "09-08-2011";

Console.WriteLine(str3);

str3 = str3.Replace('-', '/');

Console.WriteLine(str3);
foreach (string s in Split2(str3, '/'))

Console.WriteLine(s);

Console.ReadKey();

//Method1

static string[] Split1(string value, char delimiter)

return value.Split(delimiter);

//Method2

static string[] Split2(string value, char delimiter)

return value.Split(delimiter);

The above code will produce the following output:

Trim() Method
Sometimes we need to remove white spaces or new lines from the beginning or ending of string,
C# provides Trim() method for this.

Let's look at program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO; //for file input/output

namespace ConsoleApplication1

class Program

static void Main(string[] args)

//Using Trim() for white spaces

string str1 = " abhimanyu kumar vatsa. ";

str1 = str1.Trim();

Console.WriteLine(str1);

//Now line trim

string str2 = "abhimanyu kumar vatsa\r\n\r\n";

Console.WriteLine("{0}.",str2); //check dot(.) location on console

str2 = str2.Trim(); //let's trim

Console.WriteLine("{0}.",str2); //now check dot(.) locatiion on console

//Line trim in file

foreach (string lines in File.ReadAllLines("abhimanyu.txt"))

Console.WriteLine("*" + lines + "*"); //before trim

string trimmed = lines.Trim();


Console.WriteLine("*" + trimmed + "*"); //after trim

Console.ReadKey();

Above code will produce the following output:

TrimStart() Method

This is much simpler to understand. Assume you want to selectively remove a series of characters
from the starting position (remember only from a starting position) of a string then C# has a
method for you that is TrimStart() method.

Let's look at the program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)

{
//Using TrimStart()

string str1 = ".\t, abhimanyu kumar vatsa.";

char[] arr1 = new char[] { '\t', ',', ' ', '.' };

str1 = str1.TrimStart(arr1);

Console.WriteLine(str1);

Console.ReadKey();

Above code will produce the following output:

TrimEnd() Method

Programmers have a common requirement to remove all trailing punctuations from a string and
for this C# provides the TrimEnd() method.

Let's look at a program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

{
static void Main(string[] args)

//Using TrimEnd()

string[] str1 = new string[] { "Isn't this so baby?...", "I'm not sure.." };

foreach (string item in str1) //before trimend

Console.WriteLine(item);

foreach (string item in str1) //after trimend

string trimmed = item.TrimEnd('?', '.');

Console.WriteLine(trimmed);

//Using Custom method for trimend

string str2 = "Isn't this so baby?...";

Console.WriteLine(str2); //before custom method call

string cusTrimmed = cusTrimEnd(str2);

Console.WriteLine(cusTrimmed); //after custom method call

Console.ReadKey();

//Custom trimming

static string cusTrimEnd(string getStr)

int removeLen = 0;

for (int i = getStr.Length - 1; i >= 0; i--)

char let = getStr[i];

if (let == '?' || let == '.')

removeLen++;
}

else

break;

if (removeLen > 0)

return getStr.Substring(0, getStr.Length - removeLen);

return getStr;

The above code will produce the following output:

Substring() Method

Programmers sometimes need to extract a word (set of characters) from a string. For that C# has
the Substring() method which will take some values as parameters and displys the result.

Syntax: Substring(start_point, number_of_chars)

Let's look at a program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;
using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)

//Simple use

string str1 = "abhimanyu kumar vatsa";

string subStr1 = str1.Substring(0, 9);

Console.WriteLine("Sub Name: {0}", subStr1);

//Using with one parameter

string str2 = "abhimanyu kumar vatsa";

string subStr2 = str2.Substring(10); //no 2nd parameter will display from 10 to end, it
has only start parameter

Console.WriteLine("Sub Name: {0}", subStr2);

//Finding middle string

string str3 = "abhimanyu kumar vatsa";

string subStr3 = str3.Substring(10, 5);

Console.WriteLine("Sub Name: {0}", subStr3);

Console.ReadKey();

Above code will produce the following output:


ToCharArray() Method

Programmers sometimes require an array buffer from a string, C# has ToCharArray() method that
will do this. The ToCharArray() method returns a new char[] array, which can be used like a
normal array.

Let's look at a program and its output to understand better.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

class Program

static void Main(string[] args)

//String to Array, using method

string str1 = "Abhimanyu Kumar Vatsa";

char[] toChArray = str1.ToCharArray();

for (int i = 0; i < toChArray.Length; i++)

char letter = toChArray[i];

Console.WriteLine(letter);

//Array to String, using custom method

string str2="";
for (int i = 0; i < toChArray.Length; i++)

str2 += toChArray[i];

Console.WriteLine(str2);

Console.ReadKey();

Above code will produce the following output:

Named Arguments

Named Arguments enable us to specify an argument for a particular parameter by associating the
argument with the parameter's name rather than with the parameter's position in the parameter
list. It frees us 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.
In above example, if we replace the non-named arguments by named-arguments then, will have
not tension about the order of arguments.

Optional and Named Arguments in C#

Introduction

One of the new interesting features in Visual Studio 2010 is 'Named and Optional' arguments.
Practically, they are very useful together but both are quite different.

Optional Arguments

Optional Arguments enable us to omit arguments for some parameters. Any call must provide
arguments for all required parameters but can omit arguments for optional parameters. The
parameter which is omitted has default value as part of its definition. If no argument is sent for
that the default value automatically will be used. Optional parameters are defined at the end of the
parameter list after any required parameters.
In above example, we are not sending the value for 'width' parameter because it is Optional. If
you try to send the 'width' parameter value then it will overwrite existed value. For example:

In above example, width value will be replaced by 6.


Definite Assignment Rule in C#

Introduction

In the programming languages like C and C++, we define any variable and accidentally used it as
information before giving any value. C and C++ languages have no such in-built feature which can
recognize it but C# does not allow us to use an unassigned variable this rule is known as Definite
Assignment Rule. We must assign a value to a variable before use it; otherwise we will get a
'compile-time' error.

Consider in C++ Language

Let's take a look at example given below in C++ Language, it has a main method having an
unassigned variable named 'sampleValue' but when we run this, no error comes out. Even this
display some value say it as default value.

Try by assigning some value in variable 'sampleValue' and look at output, its changed (overwrite)
by newer one. Look at image below.

Consider in C# Language

Let's take a look at example given below in C# Language, it has a main method having an
unassigned variable named 'price' but when we run this, a 'compile-time error' comes out. Look at
image given below.
Try by assigning some value in variable 'price' and look at output, error is fixed. Look at image
below.

So, finally at the end we got following points.

(i) A variable must be definitely assigned at each location where its value is obtained.

(ii) A variable must be definitely assigned at each location where it is passed as a reference
parameter.

(iii) All output parameters of a function member must be definitely assigned at each location where
the function member returns.

(iv) The 'this' variable of a 'struct-type' instance constructor must be definitely assigned at each
location where that instance constructor returns.

The Properties in C#:

The usual way of haing fields made them unsafe to be accessed (read and write) by any external class that had an
access to them. We can either make these variables unsafe through a access modifier of “Private”, but then they
can not be used in the other classes.
To have a safer access to the member variables, where we can set the right to read or write of any field in C#, we
have got an extraordinary feature added up as “Properties”

Sample Code:

using System;

namespace SampleProgram

public class Employee

private int emp_id = -1; //field with private access

//Property for the field emp_id as ID

public int ID

get { return emp_id; }

set { emp_id = value; }

private string emp_name = string.Empty;//field with private access with in this class

//Property for the field emp_name as NAME

public string NAME


{

get { return emp_name; }

set { emp_name = value; }

//Lets define the other class to initiate the Main method

public class EmployeeManager

public static void Main(String[] args)

Employee emp = new Employee();

emp.ID = 1011; //initializing id with the property

emp.NAME = “Mahaveer”; //initializing name with the property

Console.WriteLine(“Employee Id:{0}, Employee Name:{1}”, emp.ID,emp.NAME);

Console.ReadKey();

Advantage of using Properties You might ask a question Isn’t it better to make a field public than providing its
property with both set { } and get { } block? After all the property will allow the user to both read and modify the
field so why not use public field instead?

Not always! Properties are not just to provide access to the fields; rather, they are supposed to provide controlled
access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we
can assure that no invalid (or unacceptable) value is assigned to the fields.

Here we go with one more big big advantage of having the Properties are to have a control over the freedom to
allow either write or read alone right to the class using this property with the object instantiated,

Lets see to an example for Read Only Properties:

public class Employee


{

private int emp_id = -1; //field with private access

//Property for the field emp_id as ID

public int ID

get { return emp_id; }

private string emp_name = string.Empty;//field with private access with in this

class

//Property for the field emp_name as NAME

public string NAME

get { return emp_name; }

//Constructor for initializing the fields

public Employee(int employeeId, string employeeName)

emp_id = employeeId;

emp_name = employeeName;

//Lets define the other class to initiate the Main method

public class EmployeeManager

public static void Main(String[] args)


{

Employee emp = new Employee(1011, “Mahaveer”);

Console.WriteLine(“Employee Id:{0}, Employee Name:{1}”, emp.ID, emp.NAME);

Console.ReadKey();

Here in the above example as you can find the fields are not given a set in the property, that makes it a read only
property, hence these read only Properties can not initialized directly. Therefore we have them initialized in the
“Custom Constructor” Employee(int employeeId,string employeeName).

As I said above, we can have both read opnly and write only Properties, I suppose you guys might have even got
an idea of how to get this, just have a look at the below example that can make you understand it much easyly,

Write Only Properties example:

public class Employee

private int emp_id = -1; //field with private access

//Property for the field emp_id as ID

public int ID

set { emp_id = value; }

private string emp_name = string.Empty;//field with private access with in this class

//Property for the field emp_name as NAME

public string NAME

set { emp_name = value; }

//Method to display the Employee fields


public void DisplayEmployee()

Console.WriteLine(“Emplyee ID:{0}, Employee Nmae: {1}”, emp_id, emp_name);

//Lets define the other class to initiate the Main method

public class EmployeeManager

public static void Main(String[] args)

Employee emp = new Employee();

emp.ID = 1011;

emp.NAME = “Mahaveer”;

emp.DisplayEmployee();//To display the field values

Console.ReadKey();

This again as given above, allows the programmer only to have a write performed on the property, and so we have
a method defined for displaying the Property that are written and so we get the output that displays the exact
value that taken up by the Write only property.

Property
A property is like a “virtual field” that contains get and set accesses and provides an interface to the

members of a class. They can be used to get and set values to and from the class members. Properties

can be static or instance members of a class. The get access does not accept any parameter; rather it

returns the value of the member that it is associated with. The set access contains an implicit parameter

called ‘value’.

C# provides a built in mechanism called properties to do the above. In C#, properties are defined using

the property declaration syntax. The general form of declaring a property is as follows.
<acces_modifier> <return_type> <property_name>

get

set

Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any

valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second

part consists of a get accessor and a set accessor.

The following code example illustrates a simple property.

Implementing properties

using System;

namespace ConsoleApplication

class Test

private int number;

public int MyProperty

get

return number;

set

{
number = value;

[STAThread]static void Main(string[]args)

Test test = new Test();

test.MyProperty = 100;

Console.WriteLine(test.MyProperty);

Console.ReadLine();

The following code shows a static property. The static property MyProperty can be accessed without

instantiating the class. A static property can access static members of a class only.

Static Properties
C# also supports static properties, which belongs to the class rather than to the objects of the class. All

the rules applicable to a static member are applicable to static properties also.

The following program shows a class with a static property.

//C# : static Property

using System;

class MyClass

private static int x;

public static int X

get

return x;

}
set

x = value;

class MyClient

public static void Main()

MyClass.X = 10;

int xVal = MyClass.X;

Console.WriteLine(xVal);//Displays 10

Remember that set/get accessor of static property can access only other static members of the class.

Also static properties are invoking by using the class name.

Properties & Inheritance


The properties of a Base class can be inherited to a Derived class.

//C# : Property : Inheritance

//Author: rajeshvs@msn.com

using System;

class Base

public int X

get

Console.Write(“Base GET”);

return 10;

set

Console.Write(“Base SET”);

}
}

class Derived : Base

class MyClient

public static void Main()

Derived d1 = new Derived();

d1.X = 10;

Console.WriteLine(d1.X);//Displays ‘Base SET Base GET 10′

The above program is very straightforward. The inheritance of properties is just like inheritance any

other member.

Properties & Polymorphism


A Base class property can be polymorphicaly overridden in a Derived class. But remember that the

modifiers like virtual, override etc are using at property level, not at accessor level.

//C# : Property : Polymorphism

//Author: rajeshvs@msn.com

using System;

class Base

public virtual int X

get

Console.Write(“Base GET”);

return 10;

set

Console.Write(“Base SET”);

}
class Derived : Base

public override int X

get

Console.Write(“Derived GET”);

return 10;

set

Console.Write(“Derived SET”);

class MyClient

public static void Main()

Base b1 = new Derived();

b1.X = 10;

Console.WriteLine(b1.X);//Displays ‘Derived SET Derived GET 10′

Abstract Properties

A property inside a class can be declared as abstract by using the keyword abstract. Remember that an

abstract property in a class carries no code at all. The get/set accessors are simply represented with a

semicolon. In the derived class we must implement both set and get assessors.

If the abstract class contains only set accessor, we can implement only set in the derived class.

The following program shows an abstract property in action.

//C# : Property : Abstract

//Author: rajeshvs@msn.com

using System;

abstract class Abstract

{
public abstract int X

get;

set;

class Concrete : Abstract

public override int X

get

Console.Write(” GET”);

return 10;

set

Console.Write(” SET”);

class MyClient

public static void Main()

Concrete c1 = new Concrete();

c1.X = 10;

Console.WriteLine(c1.X);//Displays ‘SET GET 10′

The properties are an important features added in language level inside C#. They are very useful in GUI

programming. Remember that the compiler actually generates the appropriate getter and setter

methods when it parses the C# property syntax.

Restricting the visibility

public class Employee

{
private int empID;

private string empName;

internal int ID

get

return empID;

set

empID = value;

internal string Name

get

return empName;

set

empName = value;

}
}

public class Test

public static void Main(string[]args)

Employee emp = new Employee();

emp.Name = “Joydip”;

emp.ID = 259;

System.Console.WriteLine(“The id is:” + emp.ID);

System.Console.WriteLine(“The name is:” + emp.Name);

The keyword “internal” implies that the property’s ID and Name can be accessed from the current

assembly only as they are “internal” to the assembly in which they have been declared.

Indexer
Indexers are also called smart arrays in C# and can be used to treat an object as an array. An indexer

allows an instance of a class or a struct to be indexed as an array, which is useful for looping or iterating

or data binding operations.

The following is the syntax of an indexer declaration.

<Modifier> <Return type> this[arguments]

get
{

Set

The modifier can be one of the following

 private
 public
 protected
 internal

All indexers should accept at least one parameter. Indexers cannot be static. This is because static

methods do not have access to ‘this’. The ‘this’ keyword indicates an instance of the current class. Look

at the code given below.

A simple indexer
namespace ConsoleApplication

using System;

class Employee

private string[]name = new string[10];

public string this[int index]

get

return name[index];
}

set

name[index] = value;

class Test

public static void Main()

Employee emp = new Employee();

emp[0] = “Joydip”;

emp[1] = “Manashi”;

emp[2] = “Jini”;

Console.WriteLine(“The namesare:–”);

for (int i = 0; i < 3;Console.WriteLine(emp[i++]))

Console.ReadLine();

The output of the program is

The names are:–


Joydip

Manashi

Jini

Indexers in inheritance
The indexers of the base class are inherited to its derived classes. This is illustrated in the code shown

below.

using System;

class Base

public int number;

public int this[int index]

get

Console.Write(“Get of the baseclass.”);

return number;

set

Console.Write(“Set of the baseclass.”);

number = value;

}
class Derived: Base{}

class Test

public static void Main()

Derived d = new Derived();

d[0] = 500;

Console.WriteLine(“The value is: “+ d[0]);

The program displays the string “Set of the base class. Get of the base class. The value is: 500”.

Indexers can be polymorphic. We can have the same indexer in the base and the derived classes. Such

indexers are ‘overridden indexers’ and require the keyword virtual to be stated in their declaration in the

base class. The following program illustrates this.

Indexers can be polymorphic


using System;

class Base

protected int number;

public virtual int this[int index]

get

Console.Write(“Get of the baseclass.”);

return number;
}

set

Console.Write(“Set of the baseclass.”);

number = value;

class Derived: Base

public override int this[int index]

get

Console.Write(“Get of the derivedclass.”);

return base.number;

set

Console.Write(“Set of the derivedclass.”);

base.number = value;

}
class Test

public static void Main()

Base obj = new Derived();

obj[0] = 500;

Console.WriteLine(“The value is: “+ obj[0]);

The output of the program is “Set of the derived class. Get of the derived class. The value is: 500”.

Abstract indexers
Indexers can be abstract. We can have abstract indexers in a base class that need to be implemented by

the class subclassing (inheriting from) it. The abstract indexer like an abstract method does not contain

any code in its get or set. This is shown in the example below.

Indexers can be abstract

using System;

abstract class Base

protected int number;

public abstract int this[int index]

get;

set;

}
class Derived: Base

public override int this[int index]

get

return number;

set

number = value;

class Test

public static void Main()

Derived obj = new Derived();

obj[0] = 500;

Console.WriteLine(“The value is: “+ obj[0]);

The output of the program is “The value is: 500″.


Comparison between properties and indexers
Properties are accessed by names but indexers are accessed using indexes. Properties can be static but

we cannot have static indexers. Indexers should always be instance members of the class. The get

accessor of a property does not accept any parameter but the same of the indexer accepts the same

formal parameters as the indexer. The set accessor of a property contains an implicit parameter called

“value”. The set accessor of an indexer contains the same formal parameters as that of the indexer and

also the “value” as an implicit parameter.

Generics are a new feature added in the .NET Framework 2.0. In this article we will look at what

generics are and how they can be used to benefit the developer. The article is also supplemented with

source code in Visual C#.NET.

What are Generics?

If you are coming from a C++ background then you can easily relate generics to C++ templates.

Generics allow you to use the same functionality using different types. Consider that your mother gives

you a shopping list of items you need to buy. These items include shoes, vegetables, fruits and eggs,

clothes. Now you go to a shoe store to buy shoes, you go to some grocery store to buy fruits,

vegetables and eggs and finally you go to some mall to buy clothes. Wow! you are burning lot of gas

and also wasting your time. Why not you just go to Wal-Mart and buy all the items.

In the same way you can use different data types with the same generic collection. The type of the

collection should be specified.

A Simple ArrayList():

Let’s take a simple example of an ArrayList in which you can store any data type since it stores the type

as object. This also means that when you store an integer value in the ArrayList it will be boxed and

when its retrieved it has to be unboxed. This causes low performance.

In the code below we can store different type of data into an ArrayList.

ArrayList myList = new ArrayList();

myList.Add(“AzamSharp”);

myList.Add(“John Doe”);

myList.Add(“Mary”);

myList.Add(23);
foreach (string str in myList)

Console.WriteLine(str); // This will create a runtime exception

The problem as you have already noticed is when you retrieve the values from the ArrayList you don’t

know the type and hence it will throw an exception of “Invalid caste exception”. This error is thrown at

runtime when it tries to convert “23″ to a string.

Using Generic List:

In this case you can use a generic list in which you can store the data which you specify. If any

exception takes place than it you will see it at compile time rather than at compile time.

System.Collections.Generic.List> myStringList = new List<string>();

myStringList.Add(“AzamSharp”);

myStringList.Add(“John Doe”);

myStringList.Add(23); // compile time error will come here

In the example above I used the generic List type. I have indicated that my list will only contain strings

and hence if I try to put any data type other than strings then it will create a compile time error rather

than runtime.

Adding Objects to the Generic Collection:

You can easily add you objects to a generic collection. In the example below I have constructed a

simple User.cs class which will later be added to the Generic List Collection.

using System;

using System.Collections.Generic;

using System.Text;

namespace GenericsDemo

class User
{

// field

private int _userID = 0;

private string _firstName = null;

private string _lastName = null;

// Constructor

public User(int userID,string firstName,string lastName)

_userID = userID;

_firstName = firstName;

_lastName = lastName;

// properties

public int UserID

get { return _userID; }

set { _userID = value; }

public string FirstName

get { return _firstName; }

set { _firstName = value; }

public string LastName


{

get { return _lastName; }

set { _lastName = value; }

}}}

Now we will make users and add to our generic collection:

Adding the objects to the generic collections is pretty simple. The List<T> collection exposes the Add

method which can be used to add the object that you specify in the type.

/*

* As you can see in the method below that I have used Generic List to add

* User objects. Since its generic you can simply add anything in it.

* */

public static void GenericForCollection()

Console.WriteLine(“*****GenericForCollection Method*******”);

// Make a Generic Collection here

System.Collections.Generic.IList> userList = new List<User>();

// Create 5 users and add in the generic collection

for (int i = 1; i <= 5; i++)

// Make a user object and assign some properties

User user = new User(i,”John”+1,”Doe”+i);


// This is the cool thing now (Add in the generic collection)

userList.Add(user);

// print out the list of users from the Generic Collection

foreach (User user in userList)

Console.WriteLine(“UserID: {0}”,user.FirstName);

Console.WriteLine(“FirstName: {0}”, user.FirstName);

Console.WriteLine(“LastName: {0}”, user.LastName);

Console.WriteLine();

}}

Since we have specified that this collection will store the types of User objects any attempt to store

other object will fail and will give you a compile time error. However you can successfully do this:

object o = null;

userList.Add((User)o); // casting an object type to the User Type

Generic Methods:

You can make Generic Methods, Properties, Interfaces, Classes etc. Below I have created a generic

method that accepts a generic list type and a generic type variable. The method simply adds a new item

to the list collection.

/*

* A Generic method to add the item to the collection

* */

public static void Add<T>(List<T> list, T item)

list.Add(item);
}

Now, lets see how we can use the above method.

public void AddNewUser()

System.Collections.Generic.List> users = new List<User>();

Add(users, new User(45, “John”, “Doe”));

Add(users, new User(12, “Mohammad”, “Azam”));

// print the first name of the User

foreach (User u in users)

Console.WriteLine(u.FirstName);

}}

I am simply sending the Generic List and the User object that I need to be added and that’s it. Now the

cool thing is that you can use the same Generic Add Method to add different types of objects. Simply

supply the generic list and the object that you need to add and it will be added to your list.

Method overriding in C# is a feature like the virtual function in C++. Method overriding is a feature that

allows you to invoke functions (that have the same signatures) that belong to different classes in the

same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual

and overrides to accomplish Method overriding. Let’s understand this through small examples.

P1.cs
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();
}
}

Output

BC::Display
The above program compiles and runs successfully to give the desired output. It consists of a base
class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the

function Display() it inherited from the base class BC by providing its on implementatin

of Display(). Class Demo consists of entrypoint function Main(). Inside Main() we first create a

reference b of type BC. Then we create an object of type BC and assign its reference to reference

variable b. Using the reference variable b we invoke the function Display(). As

expected, Display() of class BC is executed because the reference variable brefers to the object of

class BC.

Now we add a twist of lime to the above program.

P2.cs
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();
b = new DC();
b.Display();
}
}

Output

BC::Display
BC::Display
Here we are creating an object of Derived class DC and storing its reference in the reference

variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the

function Display(). Since b contains a reference to object of type DC one would expect the

function Display() of class DC to get executed. But that does not happen. Instead what is executed is

the Display() of BC class. That’s because the function is invoked based on type of the reference and

not to what the reference variable b refers to. Since b is a reference of type BC, the

function Display() of class BC will be invoked, no matter whom b refers to. Take one more example.

P3.cs
class BC
{
public void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();

b = new TC();
b.Display();
}
}

Output

BC::Display
BC::Display
BC::Display
The output of the above program is a receipt of the fact that no matter to whom base class
reference b refers, it invokes the functions of the class that matches its type. But doesn’t this sound

absurd? If b contains the reference to a perticular derived class object, then its supposed to invoke the

function of that class. Well, C# helps us do this by the usage of keywords virtual and override as shown

in the following program.

P4.cs
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();
}
}

Output

BC::Display
DC::Display
The above program compiles and runs successfully to give the expected desired output. The
function Display() of Base class BC is declared as virtual, while the Derived class’s implementation

of Display() is decorated with the modifier override. Doing so enables C# to invoke functions

like Display() based on objects the reference variable refers to and not the type of reference that is

invoking the function. Hence in the above program when b refers to the object of class BC it

invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of
class DC. Let’s see if this holds true for the third generation of derived classes. Take the following

program.

P4.cs
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{
public override void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;
b = new BC();
b.Display();

b = new DC();
b.Display();

b = new TC();
b.Display();
}
}

Output

BC::Display
DC::Display
TC::Display
The above program compiles and runs successfully to give the expected desired output. The
function Display() of Base class BC is declared as virtual, while the implementation of Display() in

successive Derived classes is decorated with the modifier override. Next, we succesively create objects
of each class and store their reference in base class reference variable b and invoke Display(). The

rite versions of Display get invoked based on the object the reference variable refers to. Time for a

tiny teaser! Guess what the output would be in the following program?
P5.cs
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}

class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{

class Demo
{
public static void Main()
{
BC b;

b = new TC();
b.Display();
}
}

Output

DC::Display
Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived

from DC. Hence Display() from Derived class DC gets executed. It’s as if the derived class TC looked

like this:

class TC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}
to the compiler. Take one more example. Guess what its output will be.

P6.cs
class BC
{
public virtual void Display()
{
System.Console.WriteLine("BC::Display");
}
}
class DC : BC
{
public override void Display()
{
System.Console.WriteLine("DC::Display");
}
}

class TC : DC
{
public new void Display()
{
System.Console.WriteLine("TC::Display");
}
}

class Demo
{
public static void Main()
{
BC b;

b = new TC();
b.Display();
}
}

Output

DC::Display
Agreed that TC defines its own new version of Display(). But its version of display is not invoked

as Display() of TC does not override the Display() of the base class. With this understood we are

done with Method overriding in C#.

Q1 – Define Session, SessionId and Session State in ASP.NET.

Answer – A session is the duration of connectivity between a client and a server application.

SessionId is used to identify request from the browser. By default, value of SessionId is stored in a

cookie. You can configure the application to store SessionId in the URL for a “cookieless” session.

Q2 – What is Session Identifier?

Answer – Session Identifier is used to identify session. It has SessionID property. When a page is

requested, browser sends a cookie with a session identifier. This identifier is used by the web server to

determine if it belongs to an existing session. If not, a Session ID (120 – bit string) is generated by the

web server and sent along with the response.


Q3 – What are Advantages and disadvantages of using Session State?

Answer – The advantages of using session state are as follows:

 It is easy to implement.
 It ensures data durability, since session state retains data even if ASP.NET work process
restarts as data in Session State is stored in other process space.
 It works in the multi-process configuration, thus ensures platform scalability.

The disadvantages of using session state are:

 Since data in session state is stored in server memory, it is not advisable to use session state
when working with large sum of data.
 Session state variable stays in memory until you destroy it, so too many variables in the
memory effect performance.

Q4 – What are the Session State Modes? Define each Session State mode supported by
ASP.NET.

Answer – ASP.NET supports three Session State modes.

 InProc
 State Server
 SQL Server

InProc Mode

 This mode stores the session data in the ASP.NET worker process.
 This is the fastest among all of the storage modes.
 This mode effects performance if the amount of data to be stored is large.
 If ASP.NET worker process recycles or application domain restarts, the session state will be lost.

State Server mode

 In this mode, the session state is serialized and stored in memory in a separate process.
 State Server can be maintained on a different system.
 State Server mode involves overhead since it requires serialization and de-serialization of
objects.
 State Server mode is slower than InProc mode as this stores data in an external process.

SQL Server Mode

In this storage mode, the Session data is serialized and stored in a database table in the SQL Server

database.

 This is reliable and secures storage of a session state.


 This mode can be used in the web farms.
 It involves overhead in serialization and de-serialization of the objects.
 SQL Server is more secure than the InProc or the State server mode.
Publishing a Web Site

Provides step-by-step instructions for using the Publish Web Site utility of the Microsoft Visual Web

Developer Web development tool to compile a Web site, and then copy the output to an active Web site.

If you want to deploy a finished Web site to a server, you can use the Publish Web Site utility that is

included with the Microsoft Visual Web Developer Web development tool. The Publish Web Site utility

precompiles the pages and code that are in the Web site and writes the compiler output to a folder that

you specify. You can then copy the output to the target Web server and run the application from there.

Tasks illustrated in this walkthrough include the following:

 Using the Publish Web Site utility to create precompiled output.

Prerequisites

In order to complete this walkthrough, you will need the following:

 Visual Web Developer.


 Access to Microsoft Internet Information Services (IIS) so that you can test the result of
publishing a Web site.

In this walkthrough, it is assumed that you have IIS running on your own computer. Alternatively, you

can use any instance of IIS for which you have permission to create a virtual directory.

Creating the Web Site

Create a new Web site and page by following these steps. For this walkthrough, you will create a file

system Web site.

To create a file system Web site

1. Open Visual Web Developer.


2. On the File menu, click New Web Site.

The New Web Site dialog box appears.

1. Under Visual Studio installed templates, click ASP.NET Web Site.


2. In the left-most Location list, click File System.
3. In the right-most Location list, enter the name of the folder where you want to keep the pages
of the Web site.

For example, type the folder name C:\WebSites.

1. In the Language list, click the programming language that you prefer to work in.
2. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.

Creating a Test Page and Class

For this walkthrough, you will create a Web page with some controls. You will also create a class file that

you will use in the Web page. Creating both a Web page and a separate class will let you see how the

publish process precompiles the contents of the Web site.

You will start by creating a new page, and then adding a button and label to the page.

To create the page and add controls

1. In Solution Explorer, right-click the name of the Web site and click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type SamplePage.aspx.
4. In the Language list, click the programming language that you prefer to work in.
5. Click Add.
6. Switch to Design view.
7. From the Standard group in the Toolbox,drag a Labelcontrol onto the page.
8. From the Standard group in the Toolbox, drag a Button control onto the page and position it
next to the Label control.

Next, you will create the source code for a simple class that has a single property in it. You will use the

class in the code for your page.

To create a class

1. In Solution Explorer, right-click the name of the Web site, point to Add ASP.NET Folder, and
then click App_Code.

A new folder named App_Code appears in your application in Solution Explorer. The App_Code folder is

a special reserved ASP.NET application folder.

1. Right-click the App_Code folder, and then click Add New Item.
2. Under Visual Studio installed templates, click Class.
3. In the Name box, type TestClass.
4. In the Language list, click the programming language that you prefer to work in.

The programming language that you select does not have to be the same as the programming
language that you use in the .aspx page.

1. Click Add.

Visual Web Developer creates a skeleton class file in the programming language that you have specified.

Notice that the extension of the class file name matches the language that you have selected. For

example, if you are creating a class in Microsoft Visual Basic, the file name extension is .vb.

1. Create a property named TestProperty.

When you are finished, the complete class file will look similar to the following:
Visual Basic

Imports Microsoft.VisualBasic

Public Class TestClass

Private TestPropertyValue As String

Public Property TestProperty() As String

Get

Return TestPropertyValue

End Get

Set(ByVal value As String)

TestPropertyValue = value

End Set

End Property

End Class

C#

using System;

public class TestClass

public TestClass() { }

private string TestPropertyValue;

public string TestProperty

get{ return TestPropertyValue; }

set{ TestPropertyValue = value; }

}
}

Now, you can use the class in the page. Notice that you do not have to compile the class file before

using it.

To use the class in the page code

1. Open SamplePage.aspx and switch to Design view.


2. Double-click the Button control to create a Click handler for it.
3. In the Click handler, create an instance of the TestClass that you created in the preceding
procedure, assign a value to the TestProperty property, and then display
the TestProperty value in the Label control.

The complete code will look similar to this:

Visual Basic

Protected Sub Button1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs)

Dim testClass As New TestClass

testClass.TestProperty = “Hello”

Label1.Text = testClass.TestProperty

End Sub

C#

protected void Button1_Click(object sender, EventArgs e)

TestClass testClass = new TestClass();

testClass.TestProperty = “Hello”;

Label1.Text = testClass.TestProperty;

Testing the Site

Before publishing the site, you can test it to make sure that the site works in the way that you expect.

To test the Web site


1. Open the SamplePage.aspx page.
2. Press CTRL+F5.

The page appears in the browser.

1. Click Button and make sure that text appears in the Label control.
2. Close the browser.

Publishing the Web Site

Now that you have a Web site, you can publish it. You can publish the Web site to any location that you

have access to on the local computer or on a network that is using any connection protocol that is

supported by Visual Web Developer. You have the following options for copying the Web site:

 Use a UNC share to copy to a shared folder that is on another computer on the network.
 Use FTP to copy to a server.
 Use the HTTP protocol to copy to a server that supports FrontPage 2002 Server Extensions from
Microsoft.

In this part of the walkthrough, you will publish the Web site to local folder.

To publish the Web site

1. On the Build menu, click Publish Web Site.

The Publish Web Site dialog box appears.

1. In the Target Location box, enter c:\CompiledSite.

Caution:
All data in the target folder and its subfolders will be deleted. Make sure that you do not type the
name of a folder that contains data or contains subfolders with data.

1. For the purposes of this walkthrough, you are publishing to a local folder. You could also publish
to a UNC share. If you wanted to publish to a remote Web site using HTTP or FTP, the Target
Location box is where you would specify the remote server URL.
2. The Allow this precompiled site to be updatable option specifies that all program code is
compiled into assemblies, but that .aspx files (including single-file ASP.NET Web pages) are
copied as-is to the target folder. In this walkthrough, you will not select that option.
3. Click OK.

Visual Web Developer precompiles the contents of the Web site and writes the output to the folder that

you specified. The Output window displays progress messages. If an error occurs during compilation, it

is reported in the Output window.

1. If errors occur during publishing, fix the errors, and then repeat step 1.

Examining the Output of the Publish Web Site Command

It is useful to examine the output of the Publish Web Site command so that you can see what Visual

Web Developer has done with your Web site files.


To examine the output of the Publish Web Site command

1. In Windows Explorer, move to the folder that you specified as the target for the Publish Web
Site command.
2. Using a text editor, such as Notepad, open the SamplePage.aspx file.

Notice that the file does not contain the markup that you originally had in the file. Instead, the .aspx

page is only a placeholder that can be used as part of a URL.

1. Move to the Bin folder.

The folder contains two types of files:

 .compiled files, which correspond to pages.


 .dll files, which contain the executable code for the Web site, such as the class file that you
created.

Remember that the page, its code, and the separate class file that you created have all been compiled

into executable code.

Testing the Published Web Site

You can now test the published Web site by running it.

To test the published Web site

1. Create an IIS virtual directory that points to the target folder.

You can use the IIS administrative tools or alternatively, use the following steps:

1. In Windows Explorer, right-click the name of the target folder, and then click Sharing and
Security.
2. On the Web Sharing tab, click Share this Folder.

The Edit Alias dialog box appears.

1. If you want, change the name of the alias.

The default permissions allow Read access and allow Scripts, such as ASP.NET pages, to run.

1. Click OK to close the Edit Alias dialog box, and then click OK to close the Properties dialog
box.
2. Open the browser and type the following URL:

http://localhost/CompiledSite/SamplePage.aspx

The SamplePage.aspx page appears. However, this time you are viewing the version of the page that

was created by the precompiler for deployment.


Delegates in C#

A delegate in C# allows you to pass methods of one class to objects of


other classes that can call those methods. You can pass method m in
Class A, wrapped in a delegate, to class B and Class B will be able to call
method m in class A. You can pass both static and instance methods. This
concept is familiar to C++ developers who have used function pointers to
pass functions as parameters to other methods in the same class or in
another class. The concept of delegate was introduced in Visulal J++ and
then carried over to C#. C# delegates are implemented in .Net framework
as a class derived from System.Delegate. Use of delegate involves four
steps.

1. Declare a delegate object with a signature that exactly matches the


method signature that you are trying to encapsulate.
2. Define all the methods whose signatures match the signature of the
delegate object that you have defined in step 1.
3. Create delegate object and plug in the methods that you want to
encapsulate.
4. Call the encapsulated methods through the delegate object.

The following C# code shows the above four steps implemented using one
delegate and four classes. Your implementation will vary depending on
the design of your classes.

using System;
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1
{
public void delegateMethod1(string input)
{
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input)
{
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2
{
public MyDelegate createDelegate()
{
MyClass1 c2=new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3
{
public void callDelegate(MyDelegate d,string input)
{
d(input);
}
}
class Driver
{
static void Main(string[] args)
{
MyClass2 c2 = new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 = new MyClass3();
c3.callDelegate(d,"Calling the delegate");
}
}

Event handlers in C#

An event handler in C# is a delegate with a special signature, given


below.

public delegate void MyEventHandler(object sender, MyEventArgs e);

The first parameter (sender) in the above declaration specifies the object
that fired the event. The second parameter (e) of the above declaration
holds data that can be used in the event handler. The class MyEventArgs
is derived from the class EventArgs. EventArgs is the base class of more
specialized classes, like MouseEventArgs, ListChangedEventArgs, etc. For
GUI event, you can use objects of these specialized EventArgs classes
without creating your own specialized EventArgs classes. However, for
non GUI event, you need to create your own specialized EventArgs class
to hold your data that you want to pass to the delegate object. You create
your specialized EventArgs class by deriving from EventArgs class.

public class MyEventArgs : EventArgs


{
public string m_myEventArgumentdata;
}

In case of event handler, the delegate object is referenced using the key
word event as follows:

public event MyEventHandler MyEvent;


Now, we will set up two classes to see how this event handling
mechanism works in .Net framework. The step 2 in the discussion of
delegates requires that we define methods with the exact same signature
as that of the delegate declaration. In our example, class A will provide
event handlers (methods with the same signature as that of the delegate
declaration). It will create the delegate objects (step 3 in the discussion of
delegates) and hook up the event handler. Class A will then pass the
delegate objects to class B. When an event occurs in Class B, it will
execute the event handler method in Class A.

using System;
//Step 1 Create delegate object
public delegate void MyHandler1(object sender,MyEventArgs e);
public delegate void MyHandler2(object sender,MyEventArgs e);
//Step 2 Create event handler methods
class A
{
public const string m_id="Class A";
public void OnHandler1(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id);
}
public void OnHandler2(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id);
}
//Step 3 create delegates, plug in the handler and register with the object that will fire
the events
public A(B b)
{
MyHandler1 d1=new MyHandler1(OnHandler1);
MyHandler2 d2=new MyHandler2(OnHandler2);
b.Event1 +=d1;
b.Event2 +=d2;
}
}
//Step 4 Calls the encapsulated methods through the delegates (fires events)
class B
{
public event MyHandler1 Event1;
public event MyHandler2 Event2;
public void FireEvent1(MyEventArgs e)
{
if(Event1 != null)
{
Event1(this,e);
}
}
public void FireEvent2(MyEventArgs e)
{
if(Event2 != null)
{
Event2(this,e);
}
}
}
public class MyEventArgs : EventArgs
{
public string m_id;
}
public class Driver
{
public static void Main()
{
B b= new B();
A a= new A(b);
MyEventArgs e1=new MyEventArgs();
MyEventArgs e2=new MyEventArgs();
e1.m_id ="Event args for event 1";
e2.m_id ="Event args for event 2";
b.FireEvent1(e1);
b.FireEvent2(e2);
}
}

GUI Event Handling in C#

Event handling in Windows Forms (.NET frame work that supports GUI
application) employ the .NET event handling model described earlier. We
will now apply that model to write a simple application. The application
has one class, MyForm, derived from System.Windows.Forms.Form class.
Class MyForm is derived from Form class. If you study the code and the
three comment lines, you will observe that you do not have to declare the
delegates and reference those delegates using event keyword because
the events (mouse click, etc.) for the GUI controls (Form, Button, etc.)
are already available to you and the delegate is System.EventHandler.
However, you still need to define the method, create the delegate object
(System.EventHandler) and plug in the method, that you want to fire in
response to the event (e.g. a mouse click), into the delegate object.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MyForm : Form
{
private Button m_nameButton;
private Button m_clearButton;
private Label m_nameLabel;
private Container m_components = null;
public MyForm()
{
initializeComponents();
}
private void initializeComponents()
{
m_nameLabel=new Label();
m_nameButton = new Button();
m_clearButton = new Button();
SuspendLayout();
m_nameLabel.Location=new Point(16,16);
m_nameLabel.Text="Click NAME button, please";
m_nameLabel.Size=new Size(300,23);
m_nameButton.Location=new Point(16,120);
m_nameButton.Size=new Size(176, 23);
m_nameButton.Text="NAME";
//Create the delegate, plug in the method, and attach the delegate to the Click event of
the button
m_nameButton.Click += new System.EventHandler(NameButtonClicked);
m_clearButton.Location=new Point(16,152);
m_clearButton.Size=new Size(176,23);
m_clearButton.Text="CLEAR";
//Create the delegate, plug in the method, and attach the delegate to the Click event of
the button
m_clearButton.Click += new System.EventHandler(ClearButtonClicked);
this.ClientSize = new Size(292, 271);
this.Controls.AddRange(new Control[]
m_nameLabel,m_nameButton,m_clearButton});
this.ResumeLayout(false);
}
//Define the methods whose signature exactly matches with the declaration of the
delegate
private void NameButtonClicked(object sender, EventArgs e)
{
m_nameLabel.Text="My name is john, please click CLEAR button to clear it";
}
private void ClearButtonClicked(object sender,EventArgs e)
{
m_nameLabel.Text="Click NAME button, please";
}
public static void Main()
{
Application.Run(new MyForm());
}
}

Imaging that we have a simple Employee class. There are two properties
- Name and Salary. We want a mechanism that will indicate that employee's salary has
changed.Obviously we need create an event inside our Employee class and fire it each
time when salary has changed.
Let's see Employee class source code:

public class Employee


{
public delegate void PropertyChangedHandler(object sender,
PropertyChangeEventArgs args);

public event PropertyChangedHandler PropertyChange;

public void OnPropertyChange(object sender, PropertyChangeEventArgs args)


{
// If there exist any subscribers call the event
if (PropertyChange != null)
{
PropertyChange(this, args);
}
}

public string Name { get; set; }

private int _salary = 5000;


public int Salary
{
get { return _salary; }
set
{
int oldValue = _salary;
_salary = value;
OnPropertyChange(this, new PropertyChangeEventArgs("Salary", value -
oldValue));
}
}
}
PropertyChange is actually our event. PropertyChangeHandler delegate will allow us to
subscribe to the event from other classes. We also want to pass custom arguments to
subscriber, namely the difference between old amount of salary and the new one. That's
why second parameter of the delegate is notEventArgs, as usual, but our custom
class PropertyChangeEventArgs.
Let's see PropertyChangeEventArgs class source code:

public class PropertyChangeEventArgs : EventArgs


{
public string PropertyName { get; internal set; }
public int Difference { get; internal set; }

public PropertyChangeEventArgs(string propertyName, int difference)


{
PropertyName = propertyName;
Difference = difference;
}
}
Now let's see how to subscribe to our event from other class:

class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.PropertyChange += new
Employee.PropertyChangedHandler(PropertyChanged);
employee.Salary = 8000;
Console.ReadLine();
}

public static void PropertyChanged(object sender, PropertyChangeEventArgs


args)
{
if (args.PropertyName == "Salary")
{
Console.WriteLine("Salary amount has changed! Salary difference is : "
+ args.Difference.ToString());
}
}
}
Here is the output:

Listing-1

using System;
using System.Windows.Forms;
using System.Drawing;
public class Butevent:Form
{
TextBox t1 = new TextBox();
Button b1 = new Button();
public Butevent()
{
this.Text = "Program developed by Anand.N";
t1.Location = new Point(20,30);
b1.Text = "Click here to activate";
b1.Location = new Point(20,55);
b1.Size = new Size(150,20);
// Invoking Method or EventHandler
b1.Click+=new EventHandler(OnClick);
this.Controls.Add(t1);
this.Controls.Add(b1);
// Invoking Method or EventHandler
this.Resize += new EventHandler(OnResize);
}
//Applying EventHandler
public void OnResize(object sender,EventArgs ee)
{
MessageBox.Show("oops! Form Resized");
}
//Applying EventHandler
public void OnClick(object sender,EventArgs e)
{
t1.Text = "Hello C#";
}
public static void Main()
{
Application.Run(new Butevent());
}
}

The above example also shows how to handle Resize event. Try resizing the forms
border and observe the result.

Handling MouseEvents

You can handle various Mouse actions by using the events specified in the Control class.
Following listing shows how to handle a simple MouseUp Event:

Listing-2

using System;
using System.Windows.Forms;
using System.Drawing;
public class Mousedemo:Form
{
public Mousedemo()
{
this.MouseUp += new MouseEventHandler(OnMouseup);
}
public void OnMouseup(object sender,MouseEventArgs e)
{
this.Text = "Current Position (" +e.X + " , " + e.Y +")";
}
public static void Main()
{
Application.Run(new Mousedemo());
}
}

Try out the above example and observe the result. Similarly Click, DoubleClick,
MouseEnter, MouseLeave events can be handled in the similar way.

Using KeyBoard Events

Every modern programming language contains all necessary functionalities for handling
KeyBoard related events. C# also provides us with three events KeyPress, KeyUp and
KeyDown which you can use to handle Keyboard events. Listing-3 below shows the
usage of KeyUp Event. Copy the code given below, compile and observe the output.

Listing-3

using System;
using System.Windows.Forms;
using System.Drawing;
public class Keydemo:Form
{
public Keydemo()
{
this.KeyUp += new KeyEventHandler(OnKeyPress);
}
public void OnKeyPress(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString(), "Your input");
}
public static void Main()
{
Application.Run(new Keydemo());
}
}

You might also like