Tuesday, December 6, 2011

How to call Server Side function from Client Side Code in asp.net


You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.
Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.
Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:
<form id="form1" runat="server">    
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>
        <div>
        <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />
        <br />
        <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>
        &nbsp;
        <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox>&nbsp;<br />
            </div>
    </form>
Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.
<connectionStrings>
            <removename="all"/>
            <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
      </connectionStrings>
Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.
C#
public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            conn = new SqlConnection(connection);
            string sql = "Select ContactName from Customers where CustomerId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            return contNm;
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }
VB.NET
 Public Shared Function GetContactName(ByVal custid As StringAs String
        If custid Is Nothing OrElse custid.Length = 0 Then
            Return String.Empty
        End If
        Dim conn As SqlConnection = Nothing
        Try
            Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
            conn = New SqlConnection(connection)
            Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
            Dim cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("CustID", custid)
            conn.Open()
            Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
            Return contNm
        Catch ex As SqlException
            Return "error"
        Finally
            conn.Close()
        End Try
    End Function
Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
VB.NET
<System.Web.Services.WebMethod()> _
    Public Shared Function GetContactName(ByVal custid As StringAs String
   End Function
At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.
function CallMe(src,dest)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
 }
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server">    
………
Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
C#
if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur""javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
            txtId2.Attributes.Add("onblur""javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
        }
VB.NET
If (Not Page.IsPostBack) Then
                  txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
                  txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If
As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.
Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.
Troubleshooting: ‘PageMethods Is 'Undefined'’ error
1.    Try setting EnablePageMethods="true" in the script manager tag
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
2.    Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server"> 
    </form>
</body>
3.    Page methods needs to be static in code behind.

9:32 PM by Dilip kakadiya · 0

Monday, December 5, 2011

Encrypt & Decrypt Data in asp.net with c#

Copy Belove code IN Default.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
http://www.w3.org/1999/xhtml"> 


Id 
Name 
without decrypt
Copy Belove code in default.aspx.cs page 
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 System.Data.SqlClient; 
using System.Security.Cryptography; 
using System.IO;using System.Text; 
public partial class _Default : System.Web.UI.Page 

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=DataDirectory\Database.mdf;Integrated Security=True;User Instance=True"); 
protected void Page_Load(object sender, EventArgs e) 


//Encrypt Text public string EncryptText(string str) 
{ return Encrypt(str, "&%#@?,:*"); 

// Decrypt the text 
public string DecryptText(string strText) 
{ return Decrypt(strText, "&%#@?,:*"); 

//The function used to encrypt the text 
private string Encrypt(string strText, string strEncrKey) 

byte[] byKey = { }; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD,0xEF }; 
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0,8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText); 
MemoryStream ms = new MemoryStream(); 
CryptoStream cs=new CryptoStream(ms, des.CreateEncryptor(byKey, IV),CryptoStreamMode.Write); 
cs.Write(inputByteArray,0,inputByteArray.Length); 
cs.FlushFinalBlock(); 
return Convert.ToBase64String(ms.ToArray()); 

//The function used to decrypt the text private string Decrypt(string strText, string sDecrKey) 

byte[] byKey = { }; 
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 
byte[] inputByteArray = new byte[strText.Length]; 
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0,8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
inputByteArray = Convert.FromBase64String(strText); 
MemoryStream ms = new MemoryStream(); 
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); 
cs.Write(inputByteArray, 0, inputByteArray.Length); 
cs.FlushFinalBlock(); 
System.Text.Encoding encoding = System.Text.Encoding.UTF8; 
return encoding.GetString(ms.ToArray()); 


protected void btnAdd_Click(object sender, EventArgs e) 

string name = EncryptText(txtName.Text); 
con.Open(); 
SqlCommand cmd = new SqlCommand("Insert into emp values('"+name+"')",con); cmd.ExecuteNonQuery(); 
con.Close(); 

protected void btnSelect_Click(object sender, EventArgs e) 

con.Open(); 
SqlCommand cmd = new SqlCommand("Select * from emp where id='"+txtId.Text+"'",con); 
SqlDataReader dr = cmd.ExecuteReader(); 
while (dr.Read()) 

string name = DecryptText(dr[1].ToString()); 
txtName.Text = name; 
txtWde.Text = dr[1].ToString(); 

con.Close(); 


11:19 PM by Dilip kakadiya · 0

Thursday, December 1, 2011

How to detect browser and Operating System (OS) with ASP.NET


You can use "Request.UserAgent" if you're programming ASP.NET, otherwise it quite simple to get through other programming languages or the client script by Javascript.
Back to the returns of "Request.UserAgent" which is for an example
"Mozilla/5.0 (Windows; U; Windows NT 5.1; da; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13"..
Some of these information's returns which browser system, browser version, operating system and version you are using, which is very usefully, when you're trying to determine the user operating system. If you knows the user operating system (You can request it in ASP.NET by "Request.Browser.Platform", and wants to know know the specific version like 2000, XP and Vista.
You can check if the OS version number is in the User agent. If you're looking in the example I did post above this text, you can see a Windows NT number, that's the number who indicate the specific Windows version. "Windows NT 5.1" means that this user is using Windows XP.

9:04 PM by Dilip kakadiya · 0

how to call web service from JQuery

Download source


Making ajax calls to an ASP.NET web service using jQuery is too easy.  In this post I’ll explain how to do it!
Start by creating a new web project and adding a new ASMX web service:



Open the new web service and uncomment the following line to allow the web service to be called from script.

[System.Web.Script.Services.ScriptService]
 The web service should already have a method called HelloWorld; first I will use jQuery to call this method. 
Create a new page and add a reference to the jQuery library.  Add a button and a label to the form; when the button is clicked I will call the web service and display the result in the label.  My form looks like this:

<form id="form1" runat="server">
<div>
        <asp:Button ID="btnGo" Text="Go" OnClientClick="CallService(); return false;" 
runat="server" />
 
        <asp:Label ID="lblResult" Text="&nbsp;" Width="100%" runat="server" />
    </div>
</form>

You can see I’ve set the OnClientClick property of the button to call a JavaScript function called CallService which I will implement in a moment. I have set the text of my label to a non breaking space and set the width to 100%. This is because I will add a CSS class to the label while calling my web service to show an ajax loader.  Here is the CSS class:

.loading
{
 background-image: url('ajax-loader.gif');
 background-repeat: no-repeat;
}

Finally I need to add the jQuery:

<script type="text/javascript">
    function CallService() {
        $("#lblResult").addClass("loading");
        $.ajax({
            type: "POST",
            url: "MyService.asmx/HelloWorld",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: Success,
            error: Error
        });
    }
 
    function Success(data, status) {
        $("#lblResult").removeClass("loading");
        $("#lblResult").html(data.d);
    }
 
    function Error(request, status, error) {
        $("#lblResult").removeClass("loading");
        $("#lblResult").html(request.statusText);
    }
</script>

The CallService function uses the jQuery ajax function to make the call.  Most of the options are self explanatory. The url needs to be the name of the web service followed by a forward slash and name of the method to call. The contentType is the type to use when sending data to the server, here I’m using JSON. The dataType tells jQuery what type of data to expect back from the call, here I am also using JSON which evaluates the response as JSON and sends a JavaScript object to the successful callback function.  success and error are the functions called upon success or error.  I’m not using data here but will use it in the next example to pass parameters to the web service. For a full list of ajax options have a lookhere.
You can see that the success function is passed two arguments; the first is the data returned from the call, and the second is some text that represents the status of the call. Here the data can be accessed using ‘data.d’.
The error function can have three parameters; the first is the XMLHttpRequest, the second a string describing the error and the third an optional exception object.  In this function I am setting the text of the label to the status text of the request on error.
Before making the ajax call I add the loading CSS class to the label, which is then removed in each of the callbacks. This shows the animation during the call which is then removed once a response has been recieved. To see this working add the following line to the top of the HelloWorld method in the web service to force a delay:
System.Threading.Thread.Sleep(1000);

Now I can run the application and on clicking the button the web service is called and the text ‘Hello World’ will appear in the label… magic…







So the next step would be sending parameters to the web service.  Add a new method to the service that looks like this:

[WebMethod]
public int Add(int value1, int value2)
{
    return value1 + value2;
}

Now create a new webform like so:

<table>
    <tbody>
        <tr>
            <th>
                Value 1:
            </th>
            <td>
                <asp:TextBox ID="txtValue1" runat="server" />
            </td>
        </tr>
        <tr>
            <th>
                Value 2:
            </th>
            <td>
                <asp:TextBox ID="txtValue2" runat="server" />
            </td>
        </tr>
    </tbody>
</table>
 
<asp:Button ID="btnGo" Text="Go" OnClientClick="CallService(); return false;" runat="server" />
 
<asp:Label ID="lblResult" Text="&nbsp;" Width="100%" runat="server" />

Upon clicking the button we will pass the values entered in the text boxes to the web service and display the result of the values added together in the label. Here is the jQuery to do this:

<script type="text/javascript">
function CallService() {
        $.ajax({
            type: "POST",
            url: "MyService.asmx/Add",
            data: "{ 'value1': " + $("#txtValue1").val() + ", 'value2': " + $("#txtValue2").val() + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            error: OnError
        });
    }
 
    function OnSuccess(data, status) {
        $("#lblResult").html(data.d);
    }
 
    function OnError(request, status, error) {
        $("#lblResult").html(request.statusText);
    }
</script>

The parameters are passed to the web service using the data option. Here I am passing the parameters as a JSON string appending the values from the text boxes on the form.  Running this form now allows two values to be entered and the result to be displayed in the label:












8:10 PM by Dilip kakadiya · 0