Professional Documents
Culture Documents
Execute Non Query
Execute Non Query
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
UPDATE
DELETE
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.
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.
The screenshot below displays the value of the first cell i.e. first row and first column being returned.
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.
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.
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.
<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>
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.
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.
5. Can you please explain the request flow in ASP.NET MVC framework?
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.
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.
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.
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.
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.
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:
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.
[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.
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.
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.
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>
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.
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
“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.
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;
}
}
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.
First of all, we will be creating a new domain model class inside the model folder say
“Student.cs” as:
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;
});
},
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;
Now, for Adding a new student, AddNewStudent() function does the following:
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”.
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.
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.
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.
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.
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:
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.
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),
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.
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:
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:
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
//Instantiate ServiceHost
studentServiceHost = new
ServiceHost(typeof(StudentService.StudentService),
httpBaseAddress);
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.
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.
Now let’s first create a WCF service and later host 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.
<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).
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.
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
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.
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.
//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);
}
});
}
//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.
//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.
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.
“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.
[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.
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.
[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.
[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.
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).
ASP.NET MVC 3
ASP.NET MVC 4
ASP.NET MVC 5
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.
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.
//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).
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.
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
page (.aspx) has it’s own controller (code behind i.e. Very clean separation of concerns. View and Controller are
Because of this coupled behavior, automated testing is Testability is key feature in ASP.NET MVC. Test driven
Purpose was to give developers, the same experience of a ASP.NET MVC approach is stateless as that of the web. So
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
ASP.NET WebForms model follows a Page Life cycle. in ASP.NET MVC model.
HTML. In ASP.NET Web Forms, minimal knowledge of In MVC, detailed knowledge of HTML, JavaScript and
It’s good for small scale applications with limited team It’s better as well as recommended approach for large-scale
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.
[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ….. }
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
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:
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.
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.
(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.
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:
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:
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); }
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.
We can send a request to server using HTTP GET and POST methods as follows:
xmlHttp.send();
xmlHttp.send();
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.
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.
<ContentTemplate>
<asp:Button ID=”btnTestButton”
runat=”server”
OnClick=”btnTestButton_Click”
Text=”Test Button” />
</ContentTemplate>
</asp:UpdatePanel>
<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” />
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.
“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.
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.
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.
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>
Same like audio, HTML 5 defined standard way of embedding video files.Supported
video formats are MP4, WebM and Ogg.
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:
<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.
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.
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
frame
frameset
noframe
applet
big
center
basefront
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….
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.
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.
});
6. Validating an email.
Validating an email address is very common task on HTML form.
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 T value;
//Program.cs (main)
namespace ConsoleApplication1
Console.WriteLine(g.value.ToString());
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:
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
String st = s.Substring(6);
int x = Int16.Parse(st);
return x;
Coverts all the characters from a String into upper/lower case. Example:
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:
ToReplace function.
The ToReplace function searches for a string/char to be replaced with a new string/char value.
Example:
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.
For example:
St s = new St();
//Adding values to the struct members
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication
{
class Program
{
Console.Read();
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();
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");
}
Main:
class Program
{
Console:
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;
DialogResult result;
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;
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
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:
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.
-Class Plane
using System;
using System.Text;
class Plane
{
public String type;
public String company;
~Plane() {
type = "N/A";
company = "N/A";
Console.WriteLine("Destructor in action");
}
- Main
- Console
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.
int oidNum = 0;
try
{
conn.Open();
oidNum = (int)cmd.ExecuteScalar();
oidNum++;
cmd.ExecuteNonQuery();
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.
The idea is simple and the best way to learn this is by a small example.
Code:
xmlDoc.AppendChild(declaration);
xmlDoc.AppendChild(books);
books.AppendChild(book1);
//Child 2 for BOOK
book2.SetAttribute("name", "People");
book2.SetAttribute("type", "magazine");
books.AppendChild(book2);
xmlDoc.Save(@"C:\XML\" + "xmlTest.xml");
Output:
Code:
For the first book element, we are going to add inner text:
XmlDocument xmlDoc = new XmlDocument();
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.
books = xmlDoc.GetElementsByTagName("book-2");
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.
Code:
xmlDoc.AppendChild(xmlDec);
xmlDoc.AppendChild(docType);
root.SetAttributeNode(xmlAtt);
xmlDoc.AppendChild(root);
root.AppendChild(xmlComment);
root.AppendChild(book1);
//Creating a Fragment
xmlDoc.DocumentElement.AppendChild(xmlDocFragment);
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.
using System;
class Program
{
struct Point {
public int x;
public int y;
x = x1;
y = y1;
}
return false;
}
}
Main:
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();
}
}
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
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();
}
}
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.
You can also get the full property typing "propfull" and then tab, that would generate the field and
the full property.
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 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 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
object o = c;
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
{
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
Test(c1);
Test(c2);
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
myObjects[2] = "string";
myObjects[3] = 32;
myObjects[4] = null;
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.
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.
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
//Simple Use
str1 = str1.PadLeft(20);
Console.WriteLine(str1);
str2 = str2.PadRight(30);
Console.WriteLine(str3.PadLeft(20, padWith));
string str4 = "Good Luck";
Console.WriteLine(str4.PadLeft(10, padWith1));
Console.ReadKey();
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
//Using Remove
Console.WriteLine(str1);
Console.WriteLine(str2);
//Using Replace
Console.WriteLine(str3);
Console.WriteLine(str4);
Console.ReadKey();
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
Console.WriteLine(word);
Console.WriteLine(s);
Console.WriteLine(str3);
Console.WriteLine(str3);
foreach (string s in Split2(str3, '/'))
Console.WriteLine(s);
Console.ReadKey();
//Method1
return value.Split(delimiter);
//Method2
return value.Split(delimiter);
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
str1 = str1.Trim();
Console.WriteLine(str1);
Console.ReadKey();
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
{
//Using TrimStart()
str1 = str1.TrimStart(arr1);
Console.WriteLine(str1);
Console.ReadKey();
TrimEnd() Method
Programmers have a common requirement to remove all trailing punctuations from a string and
for this C# provides the TrimEnd() method.
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.." };
Console.WriteLine(item);
Console.WriteLine(trimmed);
Console.ReadKey();
//Custom trimming
int removeLen = 0;
removeLen++;
}
else
break;
if (removeLen > 0)
return getStr;
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
//Simple use
string subStr2 = str2.Substring(10); //no 2nd parameter will display from 10 to end, it
has only start parameter
Console.ReadKey();
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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
class Program
Console.WriteLine(letter);
string str2="";
for (int i = 0; i < toChArray.Length; i++)
str2 += toChArray[i];
Console.WriteLine(str2);
Console.ReadKey();
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.
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:
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.
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.
(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 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 int ID
private string emp_name = string.Empty;//field with private access with in this class
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,
public int ID
class
emp_id = employeeId;
emp_name = employeeName;
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,
public int ID
private string emp_name = string.Empty;//field with private access with in this class
emp.ID = 1011;
emp.NAME = “Mahaveer”;
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
Implementing properties
using System;
namespace ConsoleApplication
class Test
get
return number;
set
{
number = value;
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.
using System;
class MyClass
get
return x;
}
set
x = value;
class MyClient
MyClass.X = 10;
Console.WriteLine(xVal);//Displays 10
Remember that set/get accessor of static property can access only other static members of the class.
//Author: rajeshvs@msn.com
using System;
class Base
public int X
get
Console.Write(“Base GET”);
return 10;
set
Console.Write(“Base SET”);
}
}
class MyClient
d1.X = 10;
The above program is very straightforward. The inheritance of properties is just like inheritance any
other member.
modifiers like virtual, override etc are using at property level, not at accessor level.
//Author: rajeshvs@msn.com
using System;
class Base
get
Console.Write(“Base GET”);
return 10;
set
Console.Write(“Base SET”);
}
class Derived : Base
get
Console.Write(“Derived GET”);
return 10;
set
Console.Write(“Derived SET”);
class MyClient
b1.X = 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.
//Author: rajeshvs@msn.com
using System;
{
public abstract int X
get;
set;
get
Console.Write(” GET”);
return 10;
set
Console.Write(” SET”);
class MyClient
c1.X = 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
{
private int empID;
internal int ID
get
return empID;
set
empID = value;
get
return empName;
set
empName = value;
}
}
emp.Name = “Joydip”;
emp.ID = 259;
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
get
{
Set
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
A simple indexer
namespace ConsoleApplication
using System;
class Employee
get
return name[index];
}
set
name[index] = value;
class Test
emp[0] = “Joydip”;
emp[1] = “Manashi”;
emp[2] = “Jini”;
Console.WriteLine(“The namesare:–”);
Console.ReadLine();
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
get
return number;
set
number = value;
}
class Derived: Base{}
class Test
d[0] = 500;
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
class Base
get
return number;
}
set
number = value;
get
return base.number;
set
base.number = value;
}
class Test
obj[0] = 500;
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.
using System;
get;
set;
}
class Derived: Base
get
return number;
set
number = value;
class Test
obj[0] = 500;
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
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
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
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
In the code below we can store different type of data into an ArrayList.
myList.Add(“AzamSharp”);
myList.Add(“John Doe”);
myList.Add(“Mary”);
myList.Add(23);
foreach (string str in myList)
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
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.
myStringList.Add(“AzamSharp”);
myStringList.Add(“John Doe”);
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.
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
// Constructor
_userID = userID;
_firstName = firstName;
_lastName = lastName;
// properties
}}}
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.
* */
Console.WriteLine(“*****GenericForCollection Method*******”);
userList.Add(user);
Console.WriteLine(“UserID: {0}”,user.FirstName);
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;
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
/*
* */
list.Add(item);
}
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
expected, Display() of class BC is executed because the reference variable brefers to the object of
class BC.
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
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
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.
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
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.
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.
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.
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.
In this storage mode, the Session data is serialized and stored in a database table in the SQL Server
database.
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.
Prerequisites
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.
Create a new Web site and page by following these steps. For this walkthrough, you will create a file
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.
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
You will start by creating a new page, and then adding a button and label to the page.
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
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
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.
When you are finished, the complete class file will look similar to the following:
Visual Basic
Imports Microsoft.VisualBasic
Get
Return TestPropertyValue
End Get
TestPropertyValue = value
End Set
End Property
End Class
C#
using System;
public TestClass() { }
}
}
Now, you can use the class in the page. Notice that you do not have to compile the class file before
using it.
Visual Basic
ByVal e As System.EventArgs)
testClass.TestProperty = “Hello”
Label1.Text = testClass.TestProperty
End Sub
C#
testClass.TestProperty = “Hello”;
Label1.Text = testClass.TestProperty;
Before publishing the site, you can test it to make sure that the site works in the way that you expect.
1. Click Button and make sure that text appears in the Label control.
2. Close the browser.
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.
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
1. If errors occur during publishing, fix the errors, and then repeat step 1.
It is useful to examine the output of the Publish Web Site command so that you can see what Visual
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
Remember that the page, its code, and the separate class file that you created have all been compiled
You can now test the published Web site by running it.
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 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
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#
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.
In case of event handler, the delegate object is referenced using the key
word event as follows:
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);
}
}
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:
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee();
employee.PropertyChange += new
Employee.PropertyChangedHandler(PropertyChanged);
employee.Salary = 8000;
Console.ReadLine();
}
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.
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());
}
}