जगदीश खोलिया

Tuesday, July 9, 2013

Find table row id (inside HeaderTemplate) in a DataList control

Below is the code for finding table row id inside a datalist control:
protected void datalistData_ItemDataBound(object sender, DataListItemEventArgs e)
{
      if (e.Item.ItemType == ListItemType.Header)
     {
          HtmlControl trTableRow = e.Item.FindControl("trOffline") as HtmlControl;
         //where trOffline is row id
     }
}

Monday, April 29, 2013

Extension Methods

Extension methods allow you to easily extend a type, such as an integer or string, without re-compiling or modifying the type or Extension methods enable you to "add" methods to existing types without creating a new derived type. Extension methods are a special kind of static method (shared in vb) , but they are called as if the method is native to the type.
One important thing to extension methods is if that you create an extension method with the same name as another method in that type, the compiler will bind the method call to the native method, not any extension. An extension method is only called when there is no native method found.

Steps To Create Extension Methods?
  1. Create a public static class. e.g. :  public static class Extensions{  }
  2. Define functions. 
     public static class Extensions
     {
      public string GetFirstThreeCharacters(String str)
      {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
      }
    }
  3. Make the functions an extension method.
To make our C# version of our function, we need an extension method to mark the function as static (so that it can be accessed at any time without the need for declaring anything) and secondly, mark the first parameter with the this keyword. This keyword basically tells the CLR that when this extension method is called, to use "this" parameter as the source. See the following:
 public static class Extensions
 {
    public static string GetFirstThreeCharacters(this String str)
    {
        if(str.Length < 3)
        {
            return str;
        }
        else
        {
            return str.Substring(0,3);
        }
      }
  }

Monday, March 4, 2013

Delay signing

During development process you will need strong name keys to be exposed to developer which is not a good practice from security point of view.In such situations you can assign the key later on and during development you can use delay signing.
Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.  
More you can find out in this link:
http://msdn.microsoft.com/en-us/library/t07a3dye.aspx

Wednesday, February 27, 2013

Finding duplicate records from a table in sql server

 By using row_number() function :
;with dup as(select customer_id, firstname,lastname,row_number() over(partition by firstname,
lastname order by customer_id desc) as numOfDup from customer_details)
select * from dup where numOfDup > 1 order by customer_id

 By using dense_rank() function :
;with dup as(select customer_id,firstname,lastname,dense_rank() over(partition by firstname,lastname
order by customer_id desc) as numOfDup from customer_details)
select * from dup where numOfDup > 1 order by customer_id


 By using rank() function :
;with dup as(select customer_id,firstname,lastname,rank() over(partition by firstname,lastname
order by customer_id desc) as numOfDup from customer_details)
select * from dup where numOfDup > 1 order by customer_id

 By using self join()
select distinct cd1.customer_id,cd1.firstname,cd1.lastname from customer_details cd1
join customer_details cd2
on cd1.firstname=cd2.firstname
and cd1.lastname=cd2.lastname
and cd1.customer_id > cd2.customer_id order by cd1.customer_id

 By using sub query
SELECT * FROM customer_details
    WHERE customer_id NOT IN (SELECT MIN(customer_id)
    FROM customer_details
    GROUP BY FirstName, LastName)

Tuesday, February 12, 2013

Control 'grid 1' of type 'GridView' must be placed inside a form tag with runat=server.

Because calling GridView.RenderControl(htmlTextWriter)raises 
an exception that aserver control was rendered outside of a form.
We can avoid this exception byoverriding VerifyRenderingInServerForm
 
public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered
     for the specified ASP.NET
     server control at run time. */
} 
 
*Note that there is nothing inside the function. 
 

Thursday, January 31, 2013

WCF Sessions

WCF sessions are different than the session object in ASP.NET , support different behaviors, and are controlled in different ways.WCF sessions are very different from ASP.NET Sessions. In short,

ASP.NET Sessions are:
  1. Always server-initiated.
  2. Implicitly unordered.
  3. Provide a way to preserve data across multiple requests.There is unique session id generated at the server and passed back and forth between client and server via URL or cookies.
WCF Sessions are:
  1. Initiated and terminated by the calling application (WCF Client).
  2. Ordered message delivery.
  3. Sessions correlate a group of messages into a conversation.This correlation depdending upon the binding can be taken care at message or transport level.
  4. No data storage is involved with WCF Session.

To configure sessions in WCF, one should know the following three elements:

  1. Binding – Because all bindings do not support sessions. Only WS-*, NetTcpBinding and NetNamedPipeBinding have session support so selection of appropriate binding is necessary.
  2. SessionMode – This service contract specifies service’s possible expectation for session from incoming client request. It has three self describing values:
    *)Allowed – Service can accept sessionful clients as well as sessionless.
    *)Required – Service will entertain only those clients who have session, sessionless client cannot    connect to service.
    *)NotAllowed – Service can interact only with sessionless clients. Just opposite to Required.
  3. InstanceContextMode – This is a service behavior that controls instantiation of actual service class. It has the following values:
    *)PerCall – Each request made to server will be served by a new instance of service class.
    *)PerSession – A Session will have its dedicated service instance and all requests pertaining to the session will be served by that instance only. All sessions will have their individual dedicated service instances.
    *)Single –All requests to the service will be served by a single unique instance of service class.  
There are 3 things to remember for WCF session:
1) Sessionful binding. 
      (
          <endpoint address="http://localhost:750" binding="wsHttpBinding" 
           contract="wcfservice.Iservice" name="wcfSessionTest"/>
       )
2) SessionMode service contract.
   ( 
      [ServiceContract(SessionMode = SessionMode.Allowed)]
      public interface Iservice 
      {
         //some code…
      }
   ) 
3) InstanceContextMode service behavior. 
      (
          [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
            public class serviceclass : Iservice
           { // some code… }
       )

Friday, December 14, 2012

Delegate with example

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegate delegate_name()

Example:
public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.) 
 Sample program using delegate :

public delegate double Delegate_MyFirst(int Num1,int Num2);
class Class1
{
    static double AddVal(int val1,int val2)
    {
        return val1 + val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_MyFirst Objdel = new Delegate_MyFirst(AddVal);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use delegate for processing
        double dblResult = Objdel(v1,v2);
        Console.WriteLine ("Result :"+dblResult);
        Console.ReadLine();
    }
}

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void Main()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}
 
Delegate is added using the += operator and removed 
using the -= operator.  

Thursday, October 25, 2012

CHARINDEX vs PATINDEX

The CHARINDEX and PATINDEX functions return the starting position of a pattern you specify.
Both functions take 2 parameters.For CHARINDEX, the pattern cannot include wildcard characters. 
With PATINDEX, you must include percent signs before and after the pattern, unless you are looking for the pattern as the first (omit the first %) or last (omit the last %) characters in a column.  The second argument is a character expression  in which searches for the specified pattern.
Retrive File Extension from given File Name  using charindex and patindex :
Example of CHARINDEX:

DECLARE @FileName VARCHAR(200)
SET @FileName='jagdish.doc'
SELECT SUBSTRING(@FileName,charindex('.', @FileName)+1 ,LEN(@FileName)) AS Extention

GO

Examples of PATINDEX:

DECLARE @FileName VARCHAR(200)
SET @FileName='jagdish.doc'
SELECT SUBSTRING(@FileName,patindex('%.%', @FileName)+1 ,LEN(@FileName)) AS Extention

Thursday, August 16, 2012

Post data to external URL

 Java script code for posting data to external URL:
 There are 2 Methods of doing this:
1)  <script language="javascript" type="text/javascript">    
        function submitForm(formName, formAction, newWindow) {
            var arrayStr = document.getElementById('<%= hdnData.ClientID %>').value;           
            var frm = createForm(formName, formAction, newWindow);
            var inputArray = arrayStr.split('&');
            for (var j = 0; j < inputArray.length; j++) {
                var temp = inputArray[j].split('=');
                if (isArray(temp) && temp.length == 2) {
                    createfrmInuput(frm, temp[0], temp[1])
                }
            }
            frm.submit();
        }
        //Check whether variable is array
        function isArray(obj) {
            if (obj.constructor.toString().indexOf('Array') == -1)
                return false;
            else
                return true;
        }
        function createForm(name, action, newWindow) {
            var frmJagdish= document.createElement('FORM');
            frmJagdish.method = 'POST';
            frmJagdish.name = name;
            frmJagdish.action = action;
            //if (newWindow)
            //frmJagdish.target = '_blank';
            document.body.appendChild(frmJagdish);
            return frmJagdish;
        }
        function createfrmInuput(parentForm, name, value) {
            var inuptVar = document.createElement('INPUT');
            inuptVar.type = 'hidden';
            inuptVar.name = name;
            inuptVar.value = value;
            parentForm.appendChild(inuptVar);
        }
    </script>

ASP.Net design :
<body onload="submitForm('PostedData','http://jagdishkholiya.blogspot.com',true);return false;">
    <form id="frmJagdish" runat="server">
    <asp:HiddenField ID="hdnData" runat="server" />
    </form>
</body>

Code behind :
hdnData.Value = "firstname=jagdish&lastname=kholiya&mobileno=9999999999"

2) <html xmlns="http://www.w3.org/1999/xhtml">
    <head >
    <title></title>
   </head>
   <body>
    <form id="frmTest" method="post" action="http://jagdishkholiya.blogspot.in"
    runat="server">
    <asp:HiddenField ID="firstname" runat="server" />
    <asp:HiddenField ID="lastname" runat="server" />
    <asp:HiddenField ID="mobilenumber" runat="server" />
    <asp:HiddenField ID="city" runat="server" />
    <asp:HiddenField ID="email" runat="server" />  
    </form>
    <script language="javascript" type="text/javascript">
        document.forms[0].submit();
    </script>
   </body>
   </html>

Code Behind:

  firstname.Value ="Jagdish";
  lastname.Value = "Kholiya";
  mobilenumber.Value ="9999999999";                  
  city.Value = "Gurgaon";
  email.Value = "jagdish.kholiya@gmail.com";

Thursday, July 12, 2012

What's the Difference between WCF and Web Services?


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. Using WCF, 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 WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which 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
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.

[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.
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 by WCF 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.