Popular Posts

Thursday, August 9, 2012

Life Cycle of ASP.NET Application

ASP.Net life cycle specifies, how:
  • ASP.Net processes pages to produce dynamic output
  • The application and its pages are instantiated and processed
  • ASP.Net compiles the pages dynamically
The ASP.Net life cycle could be divided into two groups:
  1. Application Life Cycle
  2. Page Life Cycle

ASP.Net Application Life Cycle:

The application life cycle has the following stages:
  • User makes a request for accessing application resource, a page. Browser sends this request to the web server.
  • A unified pipeline receives the first request and the following events take place:
    • An object of the ApplicationManager class is created.
    • An object of the HostingEnvironment class is created to provide information regarding the resources.
    • Top level items in the application are compiled.
  • Response objects are created . the application objects: HttpContext, HttpRequest and HttpResponse are created and initialized.
  • An instance of the HttpApplication object is created and assigned to the request. The request is processed by the HttpApplication class. Different events are raised by this class for processing the request.

ASP.Net Page Life Cycle:

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.
The page life cycle phases are:
  • Initialization
  • Instantiation of the controls on the page
  • Restoration and maintenance of the state
  • Execution of the event handler codes
  • Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an ASP.Net page:
  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

ASP.Net Page Life Cycle Events:

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.
Following are the page life cycle events:
  • PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.
  • Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
  • InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
  • LoadViewState . LoadViewState event allows loading view state information into the controls.
  • LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.
  • PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
  • Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
  • LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
  • PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
  • PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
  • SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
  • UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Wednesday, August 8, 2012

Example for Abstract class and Interface

 
 
Abstract Class:
-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be overridden
-If a class contains at least one abstract method then it must be declared as an “Abstract Class”
-Abstract classes can not be instantiated (i.e. we can not create objects), but a reference can be created
-Reference depends on child class object’s memory
-Abstract classes are also called as “Partial abstract classes”
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as “Fully Abstract Class” (Interface)
Interface:
-If a class contains all abstract methods then that class is known as “Interface”
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces can not be instantiated, but a reference can be created
 
 
 
  
 
 
 

Abstract Class Employee

 
 using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Employee.

    /// 

    
    public abstract class Employee
    {
        //we can have fields and properties 


        //in the Abstract class

        protected String id;
        protected String lname;
        protected String fname;

        //properties


        public abstract String ID
        {
            get;
            set;
        }

        public abstract String FirstName
        {
            get;
            set;
        }
        
        public abstract String LastName
        {
            get;
            set;
        }
        //completed methods


        public String Update()
        {
            return "Employee " + id + " " + lname + " " + fname +                      " updated";
        }
        //completed methods


        public String Add()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " added";
        }
        //completed methods


        public String Delete()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " deleted";
        }
        //completed methods


        public String Search()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " found";
        }

        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore i keep it uncompleted and 

        //let each implementation 

        //complete it the way they calculate the wage.


        public abstract String CalculateWage();
        
    }
}
 
 
 
using System;

namespace AbstractsANDInterfaces
{
    /// 


    /// Summary description for Employee.

    /// 

    
    public abstract class Employee
    {
        //we can have fields and properties 


        //in the Abstract class

        protected String id;
        protected String lname;
        protected String fname;

        //properties


        public abstract String ID
        {
            get;
            set;
        }

        public abstract String FirstName
        {
            get;
            set;
        }
        
        public abstract String LastName
        {
            get;
            set;
        }
        //completed methods


        public String Update()
        {
            return "Employee " + id + " " + lname + " " + fname +" updated";
        }
        //completed methods


        public String Add()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " added";
        }
        //completed methods


        public String Delete()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " deleted";
        }
        //completed methods


        public String Search()
        {
            return "Employee " + id + " " + 
                      lname + " " + fname + 
                      " found";
        }

        //abstract method that is different 


        //from Fulltime and Contractor

        //therefore i keep it uncompleted and 

        //let each implementation 

        //complete it the way they calculate the wage.


        public abstract String CalculateWage();
        
    }
}
 
 
 
 
 
 

Interface Employee

using System;


namespace AbstractsANDInterfaces
{
    /// <summary>


    /// Summary description for IEmployee.

    /// </summary>

    public interface IEmployee
    {
        //cannot have fields. uncommenting 


        //will raise error!
        //        protected String id;
        //        protected String lname;
        //        protected String fname;


        //just signature of the properties 

        //and methods.

        //setting a rule or contract to be 

        //followed by implementations.


        String ID
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
        
        String LastName
        {
            get;
            set;
        }
        
        // cannot have implementation


        // cannot have modifiers public 

        // etc all are assumed public

        // cannot have virtual


        String Update();

        String Add();

        String Delete();

        String Search();

        String CalculateWage();
    }
}

 

 

 

Difference between Abstract Class and Interface

Feature Interface Abstract class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

MS REPORT EXPRESSIONS

Code to Print line by line:


=First(Fields!ADDRESSLINE_1.Value, "Info_TBL_CLIENTMASTER")+","+System.Environment.NewLine+First(Fields!ADDRESSLINE_2.Value, "Info_TBL_CLIENTMASTER")+","+System.Environment.NewLine +First(Fields!ADDRESSLINE_3.Value, "Info_TBL_CLIENTMASTER")+","+System.Environment.NewLine+"Tel :"+First(Fields!PHONE_1.Value, "Info_TBL_CLIENTMASTER")


Expression to hide data if data doesn't exist:


IIF(First(Fields!FAX.Value, "Info_TBL_CLIENTMASTER") Is Nothing,".",","+System.Environment.NewLine +"FAX :"+ Format(First(Fields!FAX.Value, "Info_TBL_CLIENTMASTER"))+".")

Tuesday, July 17, 2012

javascript validation to enter landno(eg:040-123456)

<script type="text/javascript">

function NumericTextBox(evt)
{
  
    var charCode = evt.keyCode;
   
        if(evt.ctrlKey == true)
        {
        if(charCode == 67 || charCode == 86)
        {
         return true;
        }
        }
        if (charCode == 8 || //backspace
                charCode == 46 || //delete
                charCode == 13 || //enter key
                                charCode == 189)   //hipen key
    {
        return true;
    }
    else if (charCode >= 37 && charCode <= 40) //arrow keys
    {
        return true;
    }
       
    else if (charCode >= 48 && charCode <= 57) //0-9 on key pad
    {
        if (evt.shiftKey == true)
            return false;

        return true;
    }
    else if (charCode >= 96 && charCode <= 105) //0-9 on num pad
    {
        if (evt.shiftKey == true)
            return false;

        return true;
    }
    else
        return false;
}

    </script>



<asp:TextBox ID="txtMobile" runat="server" size="50" onkeydown="return NumericTextBox(event);"
                                ToolTip="Enter Mobile No" MaxLength="16"></asp:TextBox>

Javascript Validations

Any interactive web site has form input - a place where the users input different kind of information. This data is passed to ASP script, or some other technology and if the data contains an error, there will be a delay before the information travels over the Internet to the server, is examined on the server, and then returns to the user along with an error message.
If you run a validation of the user’s form input before the form is submitted, there will be no wait time and redundant load on the server. "Bad data" are already filtered out when input is passed to the server-based program. It also allows to simplify server-based program.
Client side form validation usually done with javascript. For the majority of your users, JavaScript form validation will save a lot of time up front, but double-checking the data on the server remains necessary, in case the user has turned JavaScript off.
Form data that typically are checked by a JavaScript could be:
validateFormOnSubmit ( )
This is a main function that calls a series of subfunctions, each of which checks a single form element for compliance. If the element complies than sufunction returns an empty string. Otherwise it returns a message describing the error and highlight appropriate element with yellow.
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateUsername(theForm.username);
  reason += validatePassword(theForm.pwd);
  reason += validateEmail(theForm.email);
  reason += validatePhone(theForm.phone);
  reason += validateEmpty(theForm.from);
     
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }

  return true;
}
 
 
validateEmpty ( )
The function below checks if a required field has been left empty. If the required field is blank, we return the error string to the main function. If it’s not blank, the function returns an empty string.
function validateEmpty(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow';
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}


validateUsername ( )
The function below checks if the user entered anything at all in the username field. If it’s not blank, we check the length of the string and permit only usernames that are between 5 and 15 characters. Next, we use the JavaScript regular expression /\W/ to forbid illegal characters from appearing in usernames. We want to allow only letters, numbers and underscopes.
function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a username.\n";
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        fld.style.background = 'Yellow';
        error = "The username is the wrong length.\n";
    } else if (illegalChars.test(fld.value)) {
        fld.style.background = 'Yellow';
        error = "The username contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}


validatePassword ( )
The function below checks the password field for blankness and allow only letters and numbers - no underscopes this time. So we should use a new regular expression to forbid underscopes. This one /[\W_]/ allow only letters and numbers. Next, we want to permit only passwords that contain letters and at least one numeral. For that we use the seacrh() method and two more regular expressions: /(a-z)+/ and /(0-9)/.
function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
        error = "The password is the wrong length. \n";
        fld.style.background = 'Yellow';
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = 'Yellow';
    } else {
        fld.style.background = 'White';
    }
   return error;
}  


validateEmail ( )
Next we want to see if the email address the user entered is real. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign.
At first we check if the user entered anything at all in the email field. Next, we use regular expression and the test() method to check the field for a compliance. Also we will use trim() function that will trim leading whitespace off the string. This won’t be perfect validation — it is possible to slip not compliant addresses by it — but it's normally good enough.

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}


validatePhone ( )
The function below checks if the phone number is valid. At first we use regular expression and the replace() method to clear out any spacer characters. Next, we use the isNaN() function to check if the phone number contain only numbers. At last we check the length of the string and permit only phone numbers with 10 digits.
function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}
 
 
HTML Form
This script accompanies an HTML form. When the user clicks the Submit button on the form, the form data is sent to a JavaScript validation function that checks each field to make sure that it is in the appropriate format. The HTML form could look something like this:
<html>
<head>
<title>WebCheatSheet - JavaScript Tutorial</title>
</head>
<body>
<h1>WebCheatSheet - JavaScript Tutorial</h1>

<form name="demo" onsubmit="return validateFormOnSubmit(this)" action="test.htm">
<table summary="Demonstration form">
  <tbody>
  <tr>
    <td><label for="username">Your user name:</label></td>
    <td><input name="username" size="35" maxlength="50" type="text"></td>
  </tr>  
  <tr>
    <td><label for="pwd">Your password</label></td>
    <td><input name="pwd" size="35" maxlength="25" type="password"></td>
  </tr>  
  <tr>
    <td><label for="email">Your email:</label></td>
    <td><input name="email" size="35" maxlength="30" type="text"></td>
  </tr>  
  <tr>
    <td><label for="phone">Your telephone number:</label></td>
    <td><input name="phone" size="35" maxlength="25" type="text"></td>
  </tr>  
  <tr>
    <td>
        <label for="from">Where are you :</label></td>
    <td><input name="from" size="35" maxlength="50" type="text"></td>
  </tr>  
  <tr>
    <td>&nbsp;</td>
    <td><input name="Submit" value="Send" type="submit" ></td>
    <td>&nbsp;</td>
  </tr>
  </tbody>
</table>
</form>


</body>
</html>

Javascript to enter only digits in asp.net

<script type="text/javascript">
    function AllowNumsOnly(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
 else
        return true;
}
    </script>



<asp:TextBox ID="txt_Qty" runat="server" onkeypress="return AllowNumsOnly(event);"></asp:TextBox>

Thursday, June 28, 2012

Difference b/w Webservices & WCF


Web Service in ASP.NET

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

WCF Service

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. UsingWCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • Service Orientation
  • Interoperability
  • Multiple Message Patterns
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • AJAX and REST Support
  • Extensibility

Difference between Web Service in ASP.NET & WCF Service

WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCFservices are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializerwhich is better in Performance as compared to XmlSerializer.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized

Important difference between DataContractSerializer and XMLSerializer

  • A practical benefit of the design of the DataContractSerializer is better performance overXmlserializer.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereasDataCotractSerializer
  • Explicitly shows the which fields or properties are serialized into XML
  • The DataContractSerializer can translate the HashTable into XML

Using the Code

The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized

[DataContract] 
public class Item 
{ 
    [DataMember] 
    public string ItemID; 
    [DataMember] 
    public decimal ItemQuantity; 
    [DataMember] 
    public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.
Important difference between DataContractSerializer and XMLSerializer.
  • A practical benefit of the design of the DataContractSerializer is better performance over XML serialization.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereasDataContractSerializer explicitly shows which fields or properties are serialized into XML.
  • The DataContractSerializer can translate the HashTable into XML.

Developing Service

To develop a service using ASP.NET, we must add the WebService attribute to the class andWebMethodAttribute to any of the class methods.

Example

[WebService] 
public class Service : System.Web.Services.WebService 
{ 
      [WebMethod] 
      public string Test(string strMsg) 
      { 
          return strMsg; 
      } 
}
To develop a service in WCF, we will write the following code:
[ServiceContract] 
public interface ITest 
{ 
       [OperationContract] 
       string ShowMessage(string strMsg); 
} 
public class Service : ITest 
{ 
       public string ShowMessage(string strMsg) 
       { 
          return strMsg; 
       } 
}
The ServiceContractAttribute specifies that an interface defines a WCF service contract,
OperationContract attribute indicates which of the methods of the interface defines the operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using URL of the service file.
WCF Service can be hosted within IIS or WindowsActivationService.
  • Compile the service type into a class library
  • Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
  • Copy the web.config file into the virtual directory.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.
WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.
WCF provides attributes MessageContractAttributeMessageHeaderAttribute andMessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as a response to the request.
The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated byWCF can be customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

Here are the 10 important differences between WCF Services and ASP.NET Web Services:

Thursday, May 31, 2012

Ajax Introduction


AJAX-->

When you want a user to send data to your server — once they have filled out a form, for example — they normally have to submit the form and then wait as the entire page is refreshed. Similarly, if you want to retrieve new data from the server, you have no choice but to load a whole new page.
This is inefficient, time-consuming, and particularly frustrating if there’s only a small amount of data being sent back and forth. In this tutorial, you’ll be introduced to Ajax, a technology that allows you to send these requests through small JavaScript calls, meaning the user doesn’t have to wait for the page to refresh.


What is “Ajax”?

Ajax is actually a family of technologies that have been available for years. The means to make requests to the server using only JavaScript were built into Internet Explorer 5.5, but the possibilities of the technology were overlooked. It was only in 2005 that the techniques were rediscovered and used, notably to excellent effect in Google’s .
The term Ajax, which stands for “Asynchronous JavaScript and XML”, was first coined by Jesse James Garrett in his somewhat infamous article,
So let’s take each of those parts in isolation. Ajax is:
Asynchronous
This means that when you send a request, you wait for the response to come back, but are free to do other things while you wait. The response probably won’t come back immediately, so you set up a function that will wait for the response to be sent back by the server, and react to it once that happens.
JavaScript
JavaScript is used to make a request to the server. Once the response is returned by the server, you will generally use some more JavaScript to modify the current page’s document object model in some way to show the user that the submission went through successfully.
XML
The data that you receive back from the server will often be packaged up as a snippet of XML, so that it can be easily processed with JavaScript. This data can be anything you want, and as long as you want.
There’s nothing really new about what is happening here. We’re requesting a file (which will often be a server-side script, coded in something like PHP), and receiving a page as the response. This is how the web works already — the only difference is that now we can make these requests from JavaScript.

Cross-browser Ajax

Unfortunately Ajax is supported slightly differently in IE than it is Safari, Opera and Mozilla-based browsers like Firefox. This leaves us with two possible routes: using code branching to send the right code to each browser based on which model they support, or using a JavaScript library that wraps up the Ajax code into a single object, and means you don’t have to worry about browser incompatibilities.
We’re going for the latter option, and will be using a JavaScript library. There are dozens of them in existence, each with their own boons and vices. Popular examples include prototype, Dojo, and the Yahoo UI library. For the duration of this tutorial, we’re going to be using a very useful library called » Sarissa. Sarissa contains methods that will create the request for us, and also methods that help with processing the XML that we receive back in the response. This means we don’t have to mess with the intricacies of Ajax, and allows our code to be quite elegant.

AJAX Toolkit Watermark extender example

AJAX  Toolkit provides a variety of controls and extenders.
In this blog  I would discuss use of Watermarkextender to
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%>

  2. <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
  3. <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </cc1:ToolkitScriptManager>

  4. <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />

  5. <cc1:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1"  TargetControlID="TextBox2" WatermarkText="Enter username here" runat="server">
  6. </cc1:TextBoxWatermarkExtender>
Above code is example of  TextBoxWatermarkExtender .
It has two important properties "TargetControlID" and "WatermarkText"
TargetControlID: tells to which control this extender is attached.
WatermarkText: tells the text which would be displayed in target control attached with TextBoxWatermarkExtender.
Note1: When you are using  ajax toolkit controls always use ToolkitScriptManager instead of ScriptManager.

Note2:If you got the error(Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35').
Use the ScriptManager instead of  ToolkitScriptManager .