Monday, October 31, 2011

importane links

imp links


slideshow clientside


http://codepronet.blogspot.com/search/label/Ajax

silverlight

http://codepronet.blogspot.com/2009/07/silverlight-with-wcf-service.html

Previous and next functionality with jcarousellite

http://www.gmarwaha.com/jquery/jcarousellite/#install


oops coffee-example

http://www.sum-it.nl/enoo.html


oops....

http://manishagrahari.blogspot.in/2011/08/oops.html




all topics important links


http://twitter.com/#!/a5hpat

Slideshow using Javascript

This is a web application for displaying a slideshow using Asynchronous javascript and XML or AJAX, a simple SlideshowClient web application having next/previous manual image switching and normal Start/Stop slideshow options.This application basically using client side scripting using javascript and XMLHTTPRequest.Our ultimate aim is to show the images and switch them without posting the page back.So definitely we should use any client side scripting language for this asynchronous behavior and ofcourse javascript do the job.
If we are only using images, then we can directly change image control source within the javascript. But here we want some description or some display information for each image.So i choose a simple xml file to store the data required for the slideshow. I only added description here as informational data but we can add more details as per the requirement.

<?xml version="1.0" encoding="utf-8" ?>
<SlideshowClient>
<Slideshow>
<SlideshowId>1200</SlideshowId>
<ImagePath>/Images/IMG_1573.jpg</ImagePath>/>
<Description>Colors of Life</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1201</SlideshowId>
<ImagePath>/Images/IMG_1209.jpg</ImagePath>/>
<Description>Leaf on the Floor</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1202</SlideshowId>
<ImagePath>/Images/IMG_1229.jpg</ImagePath>/>
<Description>Street Light</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1203</SlideshowId>
<ImagePath>/Images/IMG_1295.jpg</ImagePath>/>
<Description>Sunset</Description>
</Slideshow>
<Slideshow>
<SlideshowId>1204</SlideshowId>
<ImagePath>/Images/IMG_1201.jpg</ImagePath>/>
<Description>BackWater</Description>
</Slideshow>
</SlideshowClient>

In the web page i added some HTML controls required for the slideshow. So now comes the question. How it actually works? its not much complicated.I am using the hero XMLHttpRequest for getting the data from the server each time user interacts with the application.

//cross browser object for XMLHttpRequest
var xmlHttpRequest = (window.XMLHttpRequest) ? new window.XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xmlHttpRequest.open("GET", "/Data/SlideshowClientData.xml", false);
xmlHttpRequest.send(null);
//fetching the responseXML from the request
xmlDoc = xmlHttpRequest.responseXML;


We are fetching the response from responseXML attribute of the request object.So how we are going to parse this xml data? For parsing the xml data we use element.selectSingleNode("ElementName")and showing Next/Previous image and its description. But when i checked this behavior in different browsers i found this method is not supported in some browsers. So i tried for some workarounds and finally found Wrox's article XPath support in Firefox. I added selectSingleNode prototype for Element for cross browser compatibility. If selectSingleNode method is not supported i am prototyping the method.

function ElementProtoType() {
if (document.implementation.hasFeature("XPath", "3.0")) {
//Some of the browsers not supporting selectSingleNode
Element.prototype.selectSingleNode = function(xPath) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(xPath, this, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (result != null && result.singleNodeValue != null) {
result.singleNodeValue.nodeTypedValue = result.singleNodeValue.textContent;
return result.singleNodeValue;
}
else {
return null;
}
}
}
}


So now everything looks good and Next/previous will work in almost all browsers. So our basic logic for changing the image looks like,

function ShowNextImage() {
if (xmlDoc != null) {
var flag = false;
//Getting Previous image from data xml.
for (var i = 0; i < xmlDoc.documentElement.childNodes.length; i++) {
var element = xmlDoc.documentElement.childNodes[i];
if (element.nodeType == 1 && element.selectSingleNode("SlideshowId") != null &&
element.selectSingleNode("SlideshowId").nodeTypedValue == currentSlideshowId + 1) {
document.getElementById('slideshowimg').src = element.selectSingleNode("ImagePath").nodeTypedValue;
document.getElementById('description').innerHTML = element.selectSingleNode("Description").nodeTypedValue;
currentSlideshowId = currentSlideshowId + 1;
flag = true;
break;
}
}

if (!flag && interval != null && anchor != null) {
StopSlideshow(anchor);
}
}
}


I tested this application in almost all latest browsers including IE, Firefox, Google Chrome, Safari and it is working good.

PS : If we use larger size images adjust the timer according to the loading time for image otherwise in some browsers while playing the slideshow it wont get time to load the image and it'll only slide through the description.

Windows Communication Foundation (WCF)

Introduction to WCF








Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Below figures shows the different technology combined to form WCF.








Advantage

WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
WCF services provide better reliability and security in compared to ASMX web services.
In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Disadvantage

Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.



how to use WCF in C# with a simple example?

First add one blank solution.

Add new project to this









Select "WCF Service Library" as shown in above figure.

Delete the two files IService1.cs and Service1.cs

Now add two classes with the names IMyClass.cs and MyClass.cs








Now define the service contract and operation contract in iMyclass

The sample code is as given,

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

using System.ServiceModel;
using System.Runtime.Serialization;

namespace WcfServiceLibrary1
{
[ServiceContract]
public interface IMyClass
{
[OperationContract]
string[] Answers(int a, int b);
}
}

Implement that interface in the Myclass

The sample code is as given,

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

namespace WcfServiceLibrary1
{
public class MyClass : IMyClass
{
#region IMyClass Members

public string[] Answers(int a, int b)
{
string[] result = new string[5];
if (a > b)
result[0] = a.ToString() + " is greater than " + b.ToString();
else if (a == b)
result[0] = a.ToString() + " is Equal to " + b.ToString();
else
result[0] = a.ToString() + " is Smaller than " + b.ToString();

result[1] = "Addition is " + (a + b).ToString();
result[2] = "Multiplication is " + (a * b).ToString();
if (a > b)
{
if (b != 0)
{
result[3] = "Division is " + (a / b).ToString();
}
else
{
result[3] = "Division is " + "infinite";
}
}
else if (a < b)
{
if (a != 0)
{
result[3] = "Division is " + (b / a).ToString();
}
else
{
result[3] = "Division is " + "infinite";
}
}
else
{
if (a != 0 && b != 0)
{
result[3] = "Division is " + "1";
}
else
{
result[3] = "Division is " + "infinite";
}

}
if (a > b)
result[4] = "Substraction is " + (a - b).ToString();
else if (a < b)
result[4] = "Substraction is " + (b - a).ToString();
else
result[4] = "Substraction is " + "0";

return result;
}
#endregion
}
}




Now build the solution. It is necessary that your solution will build; if it doesn't then fix the error(s) then re-build.

Now add one more project to the solution as given below:









Again delete the two files Service1.svc.cs and IService1.cs

Add the reference of the dll which we have generated by building.

Open the service1.svc file and make the changes to make similar to the following line

<%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceLibrary1.MyClass" CodeBehind="MyClass.cs %>

Save it.

Now right click and select View in browser. It will show an error. No problem just take the url.

For me it gave the url : http://localhost:54640/Service1.svc

Now right click on web.config and select "Edit WCF Configuration"

Delete the Endpoints (whatever you have) then also delete the service.

Now, click on the "Create a new Service".

Click on the browse button --> Go to bin folder. You will find two Dlls over there ,

Double click both one by one so you can be given this screen,







Select That. And click on next.

Select the contract by repeating above step generally it has been given. Click next button

Select HTTP and click next. Again next.

Now It will ask for the address give the address which we have got I am giving this address http://localhost:54640/Service1.svc

Proceed ahead and click finish.

In the end point section, Give Name Basic







Now Click on the Services it will give you following screen,







Click on link says "click to create"

Again give the name "Basic"

Now go to advanced => Service Behaviour.

Which Gives you following screen

Right click on service behavior and add new .






Click on add button,

Select ServiceMetadata.

Go to top and do like the following screen.






Just save now and exit.

Refresh the url now it will gives you something instead of error.

Actually I have forgotten one setting no problem we will do that now

Again edit web.config by right clicking as done previously.

Try to reach following screen ,









Just enable httpgetenabled so it will look like,









Again save and exit.

Now refresh the page again it is ready to work.

Your refreshed page now look like this,







You can test the wcf from visual studio command prompt by writing

Wcftestclient http://localhost:54640/Service1.svc

Please provide your own url over here.

Now add website to our solution,

Add service reference give namespace that you want to give rest of the thing is simple as we do in the webservice.

Sample code to use this

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ServiceReference1;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

MyClassClient obj = new MyClassClient("Basic");
string[] datas = obj.Answers(5, 10);
foreach (string data in datas)
{
Response.Write(data);
}
}
}

For more details download the source code I have given to source demo solution as I have explained and one other download and check out that.


cheers

Tuesday, October 25, 2011

CLR architecture

The .NET Framework CLR is very tightly integrated with the SQL Server 2005 database engine. In fact, the SQL Server database engine hosts the CLR. This tight level of integration gives SQL Server 2005 several distinct advantages over the .NET integration that's provided by DB2 and Oracle. You can see an overview of the SQL Server 2005 database engine and CLR integration in Figure 3-1.

As you can see in Figure 3-1, the CLR is hosted within the SQL Server database engine. A SQL Server database uses a special API or hosting layer to communicate with the CLR and interface the CLR with the Windows operating system. Hosting the CLR within the SQL Server database gives the SQL Server database engine the ability to control several important aspects of the CLR, including

Memory management
Threading
Garbage collection

The DB2 and Oracle implementation both use the CLR as an external process, which means that the CLR and the database engine both compete for system resources. SQL Server 2005's in-process hosting of the CLR provides several important advantages over the external implementation used by Oracle or DB2. First, in-process hosting enables SQL Server to control the execution of the CLR, putting essential functions such as memory management, garbage collection, and threading under the control of the SQL Server database engine. In an external implementation the CLR will manage these things independently. The database engine has a better view of the system requirements as a whole and can manage memory and threads better than the CLR can do on its own. In the end, hosting the CLR in-process will provide better performance and scalability.








Figure 3-1: The SQL Server CLR database architecture

Enabling CLR support

By default, the CLR support in the SQL Server database engine is turned off. This ensures that update installations of SQL Server do not unintentionally introduce new functionality without the explicit involvement of the administrator. To enable SQL Server's CLR support, you need to use the advanced options of SQL Server's sp_configure system stored procedure, as shown in the following listing:

sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CLR Database object components

To create .NET database objects, you start by writing managed code in any one of the .NET languages, such as VB, C#, or Managed C++, and compile it into a .NET DLL (dynamic link library). The most common way to do this would be to use Visual Studio 2005 to create a new SQL Server project and then build that project, which creates the DLL. Alternatively, you create the .NET code using your editor of choice and then compiling the code into a .NET DLL using the .NET Framework SDK. ADO.NET is the middleware that connects the CLR DLL to the SQL Server database. Once the .NET DLL has been created, you need to register that DLL with SQL Server, creating a new SQL Server database object called an assembly. The assembly essentially encapsulates the .NET DLL. You then create a new database object such as a stored procedure or a trigger that points to the SQL Server assembly. You can see an overview of the process to create a CLR database object in Figure 3-2.



Figure 3-2: Creating CLR database objects

ASP.NET Cookies Overview

Cookies are small pieces of text, stored on the client's computer to be used only by the website setting the cookies. This allows webapplications to save information for the user, and then re-use it on each page if needed. Here is an example where we save a users choice of background color:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Cookies</title>
</head>
<body runat="server" id="BodyTag">
<form id="form1" runat="server">
<asp:DropDownList runat="server" id="ColorSelector" autopostback="true" onselectedindexchanged="ColorSelector_IndexChanged">
<asp:ListItem value="White" selected="True">Select color...</asp:ListItem>
<asp:ListItem value="Red">Red</asp:ListItem>
<asp:ListItem value="Green">Green</asp:ListItem>
<asp:ListItem value="Blue">Blue</asp:ListItem>
</asp:DropDownList>
</form>
</body>
</html>

The page simply contains a DropDownList control, which automatically posts back each time a new item is selected. It has 3 different colors, besides the default one, which is simply white. Once a new item is selected, the ColorSelector_IndexChanged method is fired, from our CodeBehind file:

using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Cookies["BackgroundColor"] != null)
{
ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
}
}

protected void ColorSelector_IndexChanged(object sender, EventArgs e)
{
BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
HttpCookie cookie = new HttpCookie("BackgroundColor");
cookie.Value = ColorSelector.SelectedValue;
cookie.Expires = DateTime.Now.AddHours(1);
Response.SetCookie(cookie);
}
}


Okay, two different parts to be explained here. First, the Page_Load method, which is called on each page request. Here we check for a cookie to tell us which background color should be used. If we find it, we set the value of our dropdown list to reflect this, as well as the background color of the page, simply by accessing the style attribute of the body tag.

Then we have the ColorSelector_IndexChanged method, which is called each time the user selects a new color. Here we set the background color of the page, and then we create a cookie, to hold the value for us. We allow it to expire after one hour, and then we set it by calling the SetCookie method on the Response object.

Try running the example, and set a color. Now close the browser, and start it up again. You will see that the choice of color is saved, and it will remain saved for an hour. However, nothing prevents you from saving the choice for much longer. Simply add a bigger value to the expiry date, or set an absolute value for it.

Caching in ASP.NET

Introduction:



Caching is one of the coolest features in Asp.net. Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. A very common example where you want to use caching is datagrid paging. I am sure you all are familiar with datagrid paging which enables you to view the records in multiple pages. Each time you visit a different page all the records are fetched from the database. This becomes very expensive operation. Caching can save a lot of expensive operations since you can store all the records in the cache object and use the cache object as the data source. In this article we will see some important features that caching provides.

Output Caching:

Output caching is used for pages and is also known as Page-level caching. All you need to do to enable output caching is to add a directive in your html view of the aspx page. The output directive can be written like this:

@ OutputCache Duration="60" VaryByParam="none"

The page will be cached for 60 seconds the VaryByParam attribute is set to "none" which means that there is no sort of caching implemented. Hence if the first user requested page which contains item1 than the second user will also see item1 even if he is requesting item2.

That's why we always specify what the caching depends on.

@ OutputCache Duration="60" VaryByParam="Category"

In the above OutputCache directive you can notice that I changed the VaryByParam attribute to "Category" which means that now the result of caching depends upon Category. Here Category represents the name of the column in the database.

Programmatic Page Caching

You can also use caching programmatically, meaning that you can change the value of cache depending upon the tasks performed by the user. The Response.Cache class let's you access the functionality to work with the cache object.

You can change the expiration time on the Cache using the SetExpires method of the Response.Cache class.

Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(10));

In the same way you can also use Response.Cache.VaryByParams to set the Params programmatically.

Accessing Caching in the Class Libraries

Sometimes you will need to access the caching object in the class library. You cannot use Response class anymore since its only limited to the asp.net code behind page. For accessing cache in class library you will have to use HttpContext.Current.Cache. Also don't forget to include System.web namespace.

Data Caching

Caching is one of the coolest features in Asp.net. Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. Data Caching can tremendously increase performance since each time the data is requested you can turn to the Cache object rather than going to the database and fetching the result.



You all must be familiar with datagrid paging where you can display certain number of records in the datagrid control and use the numeric or next-previous buttons to view the other records. All the records are fetched for each and every page in the datagrid. Meaning that if you have 40000 records in the database and you are using paging. Each time you click to go to the next page you retrieve 40000 records. This is way too much performance kill. That's why for this task we can use Data Caching, let's see how we can use data caching to make our application more efficient.

private void Button3_Click(object sender, System.EventArgs e)

{

if(Cache["MyArticles"] == null)

{

// Go to the database and fetch the result in the DataSet



// Assign the dataset to the Cache object



// Cache["MyArticles"] = ds

}

else

{

// This means that Cache is not empty and there is data in the cache

// Extract the value of Cache object to the DataSet

// DataSet ds = (DataSet) Cache["MyArticles"]

}

}

The above example is pretty much simple and as you have also noticed that the syntax for using Data Caching is very similar to the ViewState object. By using this technique you will only get the data from the database if the Cache is empty. And if you see the page source you will not find any hidden fields since Cache is stored in memory rather than in page source.

Caching Page Fragments

Fragment Caching refers to caching the sections of the page. These sections are most commonly UserControls. Page fragment caching allows you to cache the small portion of the page instead of caching the whole page.

Let's see some examples of fragment caching and how it can be used.

@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"

In the Page directive above we have cached CategoryID and SelectedID for 120 seconds. Both of these are the query string parameters.

This means that if the first user request CategoryID = 2 and the second user request the same CategoryID than the second user will recieve the contents from the cache object instead of going to the database and pulling records.

@ OutputCache Duration="120" VaryByParam="none" VaryByControl="Category"

The VaryByControl attribute can only be used in fragment caching. You can use this to cache the value of the controls. These controls can be any server controls like dropdownlist or datagrid.
When using fragment caching you only need to put the cache directive in the user control and not on the page.

You can use different type of tools to monitor your performance before and after caching is used. Some of the good tools are NProf and ACT

Monday, October 24, 2011

IIS USER AUTHENTICATION TUTORIAL

Welcome to the the Internet Information Server (IIS) User Authentication Tutorial. This page provides detailed information on the various methods of authentication in IIS.


Tutorial Sections:

Basic Authentication
Cookie Authentication
NTLM / Integrated windows Authentication
ISAPI Authentication Filters


************************************************************************************

Basic Authentication:

Basic authentication is a standard which nearly all browsers support. When you access a site and you see a standard popup window which asks for your username and password, your are using basic authentication. An example from Internet Explorer can be found below.





How to configure in IIS:

Open the MMC and select the site or directory you wish to protect
Right click and select properties on that site / directory
Select the directory security tab
Click the "edit" button on authentication control
Enable basic authentication
Now your site is setup to support basic authentication you need to change the NTFS permissions for the directory you want to protect and add any users or groups you wish to have access
When IUSR_MACHINENAME does not have access to a directory or you disable anonymous access the basic authentication windows will popup


Advantages:

Requires no additional software


Disadvantages:

Choosing basic authentication in conjunction with NT users can be dangerous, the reason is that the username and password are sent in plain text. If someone maliciously acquires an NT username and password they will have rights on the server and can do damage.
The basic authentication login box is generated by the web browser, as such you can not control the look and feel of this dialog
This requires that you create NT users and groups for all web site users. This can be difficult to administer, particularly with large number of users.




************************************************************************************

Cookie Authentication:

Cookie authentication makes use of functionality at the scripting level to provide user authentication.


How to configure in IIS:

This does not require specific IIS server configuration but rather ASP script configuration
The following code would need to be placed at the top of each page you wanted to protect:

<% If Session("login") = FALSE Then Response.Redirect "LoginPage.asp" Else Response.Write "You are logged in" End If %>
The following code is an example of a simple login form:
<% if request.form("password") = "yourpass" then session("login") = TRUE end if %>

<form method="POST" action="login.asp"
<input type="text" name="password" size="20"><input type="submit" value="login" name="login"></p>
</form>


This code could be expanded to tie into a database and track usernames as well as passwords but the concept is the same as this hardcoded sample with a password of "yourpass".

Advantages:

Can use custom designed login form
Can store usernames and passwords independently of NT users


Disadvantages:

This will only protect ASP scripts (not images, html etc)
This requires that users browsers support cookies and have them enabled
protection must be implemented on a per page basis (for example a directory can not be protected)

************************************************************************************
NTLM / Windows Integrated Authentication:

NTLM is similar to basic authentication in that it works with a popup window generated by the browser. The main difference is that the supplied information is encrypted and passed securely to the client. In order to accomplish this the browser must have special functionality.









How to configure in IIS:

Open the MMC and select the site or directory you wish to protect
Right click and select properties on that site / directory
Select the directory security tab
Click the "edit" button on authentication control
Disable basic authentication and enable NTLM / Integrated Windows Authentication
Now your site is setup to support NTLM authentication you need to change the NTFS permissions for the directory you want to protect and add any users or groups you wish to have access


Advantages:

Requires no additional software
Username and password passed securely without using SSL


Disadvantages:

The NTLM authentication login box is generated by the web browser, as such you can not control the look and feel of this dialog
This requires that you create NT users and groups for all web site users. This can be difficult to administer, particularly with large number of users.
Clients must use Internet Explorer (no other web browser supports NTLM)



************************************************************************************
ISAPI Filter Authentication:

The Internet Server Application Programmer Interface provides low level access to the entire web server request and event chain. Because of this it can intercept requests before the web server handles them and provides the greatest authentication flexibility.


How to configure in IIS:

In the MMC the filter needs to be loaded under the ISAPI filters tab under the site properties
This assumes you have a valid authentication filter to load, if not you would first need to develop one using VC++ or purchase a commercial product.

Advantages:

High performance
Can provide flexibility to work with or without cookies and support failing over between them
Independent of the NT user base
Protects all types of files not just ASP scripts
Can support multiple web site on the same server


Disadvantages:

Requires purchase of commercial product or complex development of your own filter

process vs thread

A process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.
Thread is used to allocate and distribute the CPU work scheduling, many programs a re assigned to different threads and they are most of the time independent of each other.





The major difference between threads and processes

1.Threads(Light weight Processes) share the address space of the process that created it; processes have their own address.

2.Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

3.Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.

4.Threads have almost no overhead; processes have considerable overhead.

5.New threads are easily created; new processes require duplication of the parent process.

6.Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.

7.Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.If we consider running a word processing program to be a process, then the auto-save and spell check features that occur in the background are different threads of that process which are all operating on the same data set (your document).

C# Delegates

Delegates

People often find it difficult to see the difference between events and delegates. C# doesn't help matters by allowing you to declare field-like events which are automatically backed by a delegate variable of the same name. This article aims to clarify the matter for you. Another source of confusion is the overloading of the term "delegate". Sometimes it is used to mean a delegate type, and at other times it can be used to mean an instance of a delegate type. I'll use "delegate type" and "delegate instance" to distinguish between them, and "delegate" when talking about the whole topic in a general sense.

Delegate types

In some ways, you can think of a delegate type as being a bit like an interface with a single method. It specifies the signature of a method, and when you have a delegate instance, you can make a call to it as if it were a method with the same signature. Delegates provide other features, but the ability to make calls with a particular signature is the reason for the existence of the delegate concept. Delegates hold a reference to a method, and (for instance methods) a reference to the target object the method should be called on.

Delegates types are declared with the delegate keyword. They can appear either on their own or nested within a class, as shown below.

namespace DelegateArticle
{
public delegate string FirstDelegate (int x);

public class Sample
{
public delegate void SecondDelegate (char a, char b);
}
}

This code declares two delegate types. The first is DelegateArticle.FirstDelegate which has a single parameter of type int and returns a string. The second is DelegateArticle.Sample.SecondDelegate which has two char parameters, and doesn't return anything (because the return type is specified as void).

Note that the delegate keyword doesn't always mean that a delegate type is being declared. The same keyword is used when creating instances of the delegate type, using anonymous methods.

The types declared here derive from System.MulticastDelegate, which in turn derives from System.Delegate. In practice, you'll only see delegate types deriving from MulticastDelegate. The difference between Delegate and MulticastDelegate is largely historical; in betas of .NET 1.0 the difference was significant (and annoying) - Microsoft considered merging the two types together, but decided it was too late in the release cycle to make such a major change. You can pretty much pretend that they're only one type.

Any delegate type you create has the members inherited from its parent types, one constructor with parameters of object and IntPtr and three extra methods: Invoke, BeginInvoke and EndInvoke. We'll come back to the constructor in a minute. The methods can't be inherited from anything, because the signatures vary according to the signature the delegate is declared with. Using the sample code above, the first delegate has the following methods:


public string Invoke (int x);
public System.IAsyncResult BeginInvoke(int x, System.AsyncCallback callback, object state);
public string Endinvoke(IAsyncResult result);

As you can see, the return type of Invoke and EndInvoke matches that of the declaration signature, as are the parameters of Invoke and the first parameters of BeginInvoke. We'll see the purpose of Invoke in the next section, and cover BeginInvoke and EndInvoke in the section on advanced usage. It's a bit premature to talk about calling methods when we don't know how to create an instance, however. We'll cover that (and more) in the next section.
Delegate instances: the basics

Now we know how a delegate type is declared and what it contains, let's look at how to create an instance of such a type, and what we can do with it.
Creating delegate instances

Note: this article doesn't cover the features of C# 2.0 and 3.0 for creating delegate instances. I cover the C# 2.0 features in my article about C# 2.0. When I eventually get round to writing about C# 3.0, I'm sure I'll cover the new features for lambda functions etc at that point. By concentrating on the explicit manner of creating instances in C# 1.0/1.1, I believe it will be easier to understand what's going on under the hood. When you understand the basics, it's clearly worth knowing the features these later versions provide - but if you try to use them without having a firm grasp on the basics, you may well get confused.

As mentioned earlier, the key points of data in any particular delegate instance are the method the delegate refers to, and a reference to call the method on (the target). For static methods, no target is required. The CLR itself supports other slightly different forms of delegate, where either the first argument passed to a static method is held within the delegate, or the target of an instance method is provided as an argument when the method is called. See the documentation for System.Delegate for more information on this if you're interested, but don't worry too much about it - it's largely irrelevant from a C# point of view. C# only supports creating what MSDN calls a closed instance delegate type.

So, now that we know the two pieces of data required to create an instance (along with the type itself, of course), how do we tell the compiler what they are? We use what the C# specification calls a delegate-creation-expression which is of the form new delegate-type (expression). The expression must either be another delegate of the same type (or a compatible delegate type in C# 2.0) or a method group - the name of a method and optionally a target, specified as if you were calling the method, but without the arguments or brackets. Creating copies of a delegate is fairly rare, so we will concentrate on the more common form. A few examples are listed below:

// The following two creation expressions are equivalent,
// where InstanceMethod is an instance method in the class
// containing the creation expression (or a base class).
// The target is "this".
FirstDelegate d1 = new FirstDelegate(InstanceMethod);
FirstDelegate d2 = new FirstDelegate(this.InstanceMethod);

// Here we create a delegate instance referring to the same method
// as the first two examples, but with a different target.
FirstDelegate d3 = new FirstDelegate(anotherInstance.InstanceMethod);

// This delegate instance uses an instance method in a different class,
// specifying the target to call the method on
FirstDelegate d4 = new FirstDelegate(instanceOfOtherClass.OtherInstanceMethod);

// This delegate instance uses a static method in ths class containing
// the creation expression (or a base class).
FirstDelegate d5 = new FirstDelegate(StaticMethod);

// This delegate instance uses a static method in a different class
FirstDelegate d6 = new FirstDelegate(OtherClass.OtherStaticMethod);

The constructor we mentioned earlier has two parameters - an object and an IntPtr. The object is a reference to the target (or null for static methods) and the IntPtr is a pointer to the method itself.

One point to note is that delegate instances can refer to methods and targets which wouldn't normally be visible at the point the call is actually made. For instance, a private method can be used to create a delegate instance, and then the delegate instance can be returned from a public member. Alternatively, the target of an instance may be an object which the eventual caller knows nothing about. However, both the target and the method must be accessible to the creating code. In other words, if (and only if) you can call a particular method on a particular object, you can use that method and target for delegate creation. Access rights are effectively ignored at call time. Speaking of which...
Calling delegate instances

Delegate instances are called just as if they were the methods themselves. For instance, to call the delegate referred to by variable d1 above, we could write:

string result = d1(10);

The method referred to by the delegate instance is called on the target object (if there is one), and the result is returned. Producing a complete program to demonstrate this without including a lot of seemingly irrelevant code is tricky. However, here's a program which gives one example of a static method and one of an instance method. DelegateTest.StaticMethod could be written as just StaticMethod in the same way that (within an instance method) you could write InstanceMethod instead of this.InstanceMethod - I've included the class name just to make it clear how you would reference methods from other classes.

using System;

public delegate string FirstDelegate (int x);

class DelegateTest
{
string name;

static void Main()
{
FirstDelegate d1 = new FirstDelegate(DelegateTest.StaticMethod);

DelegateTest instance = new DelegateTest();
instance.name = "My instance";
FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod);

Console.WriteLine (d1(10)); // Writes out "Static method: 10"
Console.WriteLine (d2(5)); // Writes out "My instance: 5"
}

static string StaticMethod (int i)
{
return string.Format ("Static method: {0}", i);
}

string InstanceMethod (int i)
{
return string.Format ("{0}: {1}", name, i);
}
}

The C# syntax is just a short-hand for calling the Invoke method provided by each delegate type. Delegates can also be run asynchronously if they provide BeginInvoke/EndInvoke methods

__doPostBack

Hi everyone. Today I am going to talk about __doPostBack function, because there is some confusion in using _dopostback.

You can see this __doPostBack function in your asp.net generated HTML code.
The function takes two arguments:

1) eventTarget

2) eventArgument

1) EventTarget contains the ID of the control that causes the postback

eventArgument contains any additional data associated with the control.


When a page is posted back to the server ASP .NET inspects __EVENTTARGET and __EVENTARGUMENT values and this way it can decide which of the controls caused the page to be postedback and what is the event that has to be handled.
In any asp.net page the two hidden fields, “__EVENTTARGET” and “__EVENTARGUMENT,” are automatically declared. The value of the eventTarget and eventArgument are stored in the hidden fields. The two hidden variables can be accessed from the code behind using the forms or params collection.

If we inspect the code of the __doPostBack function, we can see that it first sets the values of two hidden fields created by ASP .NET named __EVENTTARGET and __EVENTARGUMENT with the two parameters passed to the function. After this, the page is submitted back to the server. When a page is posted back to the server ASP .NET inspects __EVENTTARGET and __EVENTARGUMENT values and this way it can decide which of the controls caused the page to be postedback and what is the event that has to be handled. The ID of the control which causes the postback is stored in the __EVENTTARGET hidden field, so you can find the control which caused the postback.


<a id="LinkButton1" href="javascript:__doPostBack('LButton3','')">LinkButton</a>
You can see the fucntion call "__doPostBack('LButton3','')" in href and the argument passed for eventTarget is "LButton3" which is the id of the linkbutton control (EventSource)

Example

I am going to talk aamirhasan.aspx Page.

in aamirhasan.aspx Page

1) Add two hidden fields inside the form as given below

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

2) Add javascript under the Head tag as given below

<script><br /> function __doPostBack(eventTarget, eventArgument) {<br /> document.Form1.__EVENTTARGET.value = eventTarget;<br /> document.Form1.__EVENTARGUMENT.value = eventArgument;<br /> document.Form1.submit();<br /> }<br /> </script>

3) add two control given below

<a id="LButton3" href="javascript:__doPostBack('Button2','')">LinkButton</a>

<asp:button onclick="Button2_Click" id="Button2" runat="server" text="Button">

4) add function in your cs page

protected void Button2_Click(object sender, EventArgs e)
{
Response.Write("Welcome to Student Academic Blog");
}

5) You also need some code in the code behind to capture the postback and fire the event:

In the PageLoad method:

if (Request.Form["__EVENTTARGET"] == "Button2")
{
//fire event
Button2_Click(this, new EventArgs());
}

This will capture the posted variable "__EVENTTARGET" and cause it to fire the event "Button2_Click". You can also pass an event argument along with the target in case you need to pass something to your code behind:

javascript:__doPostBack("Button2', '<event argument="" here="">')

This would be captured in the code behind as Request.Form["__EVENTARGUEMENT"]

So this is how you can use __doPostBack

Enjoy it</event></asp:button>