AJAX using JQuery and ASP.net

November 21st, 2009

This is my first article on JQuery. Although I am using JQuery for more than two years I was unable to write any article on that due to lack of time. In the following simple example I will try to explain how you can send AJAX request from you asp.net application using JQuery and web services. So let’s start our journey.

For this example I have used the Customers table from Northwind database.

Create a default.aspx page and add the following code in the body portion of the aspx page

<form id=”form1″ runat=”server”>

    // asp.net dropdown list

    <asp:DropDownList ID=”Customers” runat=”server” AutoPostBack=”false”>

    </asp:DropDownList>

    // div to hold the details regarding customers

    <div id=”CustomerDetails” >

    </div>       

</form>

 

Just make sure that the AutoPostBack property of your DropdownList is set to false AutoPostBack=”false”.

 

 

Then go to the cs page i.e. defaul.aspx.cs and add the following code in the page Load method.

 

if(!IsPostBack)

{

   // usually we define the connection string in web.config but for making it simple defined here

   string connect = @”Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind;User ID=sa;Password=password”;

   //query to select customer data

   string query = “SELECT CustomerID, CompanyName FROM Customers”;

   using (SqlConnection conn = new SqlConnection(connect))

   {

      using (SqlCommand cmd = new SqlCommand(query, conn))

      {

            conn.Open();

            Customers.DataSource = cmd.ExecuteReader();

            Customers.DataValueField = “CustomerID”;

            Customers.DataTextField = “CompanyName”;

            Customers.DataBind();

      }

   } 

  }

 

Now add an entity class customer.cs and add the following code in it.

 

public string CustomerID { get; set; }

public string CompanyName { get; set; }

public string Address { get; set; }

public string City { get; set; }

public string Region { get; set; }

public string PostalCode { get; set; }

public string Country { get; set; }

public string Phone { get; set; }

public string Fax { get; set; }

 

Now a webservice WebService.asmx in the project and add the following method in it.

 

[WebMethod]

public ClsCustomer GetCustomerDetailByID(string CustomerID)

{

   try

   {      

      Customer c = new Customer();

      

      string connect = @”Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind;User ID=sa;Password=password”;

      string query = “SELECT CustomerID,CompanyName, Address, City, Region, PostalCode,” +

     “Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID”;

 

        if (CustomerID != null )

        {

            using (SqlConnection conn = new SqlConnection(connect))

            {

                using (SqlCommand cmd = new SqlCommand(query, conn))

                {

                    cmd.Parameters.AddWithValue(“CustomerID”, CustomerID);

                    conn.Open();

                  

                    SqlDataReader rdr = cmd.ExecuteReader();

                    if (rdr.HasRows)

                    {

                        while (rdr.Read())

                        {

                            // Load the data in the customer object          

                            c.CustomerID = rdr["CustomerID"].ToString();

                            c.CompanyName = rdr["CompanyName"].ToString();

                            c.Address = rdr["Address"].ToString();

                            c.City = rdr["City"].ToString();

                            c.Region = rdr["Region"].ToString();

                            c.PostalCode = rdr["PostalCode"].ToString();

                            c.Country = rdr["Country"].ToString();

                            c.Phone = rdr["Phone"].ToString();

                            c.Fax = rdr["Fax"].ToString();

                        }

                    }

                }

            }

        }

        // return customer object

        return c;

        }

        catch (System.Exception ex)

        {

            return null;

        }

    }

 

Now again go back to the default.aspx page and prepare AJAX request using jquery. First include the jQuery library in the head section of the default.aspx page. (you can easily download the jquery file from internet)

 

<script type=”text/javascript” src=”Script/jquery-1.3.2.min.js”></script>

 

Now add the following javascript code

 

<script type=”text/javascript”>

    // this method will be called when the page is loaded in the browser

     $(document).ready(function()

     {

        //attach change event on asp dropdown list with id Customers.

        $(‘#Customers’).change(function() {

        // send ajax request.

        $.ajax({

        type: “POST”,

        contentType: “application/json; charset=utf-8″,

        //pass parameter with the ajax request

        data: “{ CustomerID: ‘” + $(‘#Customers’).val() + “‘}”,

        //calling webservice

        url: “FatchCustomers.asmx/GetCustomerDetailByID”,

        //return type will be JSON

        dataType: “json”,

        //on success call this method.

        success: BuildTable,

        error:TransacionFailed

       });

    });

  });

 

   function TransacionFailed() {

  

          $(‘#CustomerDetails’).empty();

          $(‘#CustomerDetails’).append

            (result.status + ‘ ‘ + result.statusText);

           

   }

function BuildTable(msg) {

      var table = ‘<table cellpadding=”5px” cellspacing=”5px” border=”1px”><thead><tr><th>Customer Id</th>  <th>Customer Name</th> <th>Address</th><th>City</th> <th>Region</th><th>PostalCode</th><th>Country</th><th>Phone</th><th>Fax</th></thead><tbody>’;

      //brows the returned JSON DATA

      for (var cd in msg) {

          var row = ‘<tr>’;

          row += ‘<td>’ + msg[cd].CustomerID + ‘</td>’;

          row += ‘<td>’ + msg[cd].CompanyName + ‘</td>’;

          row += ‘<td>’ + msg[cd].Address + ‘</td>’;

          row += ‘<td>’ + msg[cd].City + ‘</td>’;

          row += ‘<td>’ + msg[cd].Region + ‘</td>’;

          row += ‘<td>’ + msg[cd].PostalCode + ‘</td>’;

          row += ‘<td>’ + msg[cd].Country + ‘</td>’;

          row += ‘<td>’ + msg[cd].Phone + ‘</td>’;

          row += ‘<td>’ + msg[cd].Fax + ‘</td>’;

          row += ‘</tr>’;

          table += row;

      }

     

      table += ‘</tbody></table>’;

      $(‘#CustomerDetails’).html(table);

     

     

  }   

    </script>

 

We are done. I always prefer jquery over asp.net ajax as it is far more easier and lite weight.

AJAX, ASP.net, JQuery , , , ,

Get the day from date value in SQL Server

October 29th, 2009

There is a nice function available in SQL server to find out the day name for any given date you can use it in your query.

select datename (dw, ‘10/10/2009′) as [day]

SQL SERVER ,

Installing Cache on Red Hat Linux

May 15th, 2009

Cache installation steps on Red Hat Linux

 

Download the cache setup files for your Linux version. and then Uzip the files.
Start the Terminal window in Linux.
Go to the cache setup foldcer. eg. cd  /root/cache-2007/
Run  ./cinstall  command
The cache installation script will be start and ask you some question regarding installation .

 

1 )      It will display the Linux version which is supported with this version of cache and ask you to choose by asking  “Is this the correct type of your system”. Select accordingly.

2 )      Next it will ask “Enter instance name”. Type the name of the instance for example cache07.

3 )      Then it will ask “Enter directory name for this installation ”. Type the path for your installation e.g /xyz/abc/.

4 )      If the directory you provide does not exist  it will ask “Do you want to create it”. Type Yes.

5 )      Next it will ask u about the setup type “Standard or Custom”. Type 1 for standard.

6 )      Next it will ask u about Unicode support. Reply accordingly.

7 )      Then it will ask u about Security Settings. Select accordingly.

8 )      Then it will ask u about the Group which is allowed to start and stop the cache instance.

9 )      Then it will ask u about licence key. “Are u want to enter the licence Key”. Type yes if you want to provide a licence key.

10)  It will then show u the provide option as installation summary and will ask u to proced. Type yes … and the installation will start.

11)  After the installation if every thing goes fine it will show u the URL of System Management Portal.

12)  Done

 

 

 

Cache, Linux , ,

Restore Cache Backup From Cache Terminal

May 15th, 2009

It is quite easy to restore the cache classes backup using cache studio but some times we have a scenario where we have to restore the cache classes backup from the cache terminal. Usually we need this in Linux. We can achive this goal by using a simple command.

$system.OBJ.Load(”path to the xml File”,”ck”) 

Just start cache terminal go to the specific namespace by typeing

zn “Namespace Name”

and then run the command 

w $system.OBJ.Load(”path to the xml File”,”ck”) 

and the xml file will be restored in the current namespace.

Cache , , , ,

Calling WSDL WebService From PHP.

May 15th, 2009

Web service is a way of comunication over the internet. It is  Language independent. We can call Web service from PHP by using Curl Library. For that we have to enable the Php_curl library from the php.ini file.

<?php

             // URL of the Web Service
              $url=”http://localhost/Test/Service1.asmx/Test?name=”.$_POST["fcurrency"];
             // initiate the Curl library.
              $ch = curl_init();     
             // initiate the Curl library.
             // for reference see:- (http://www.php.net/curl_setopt)
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($ch, CURLOPT_URL, $url);
              // get the Response from the WebService
              //for reference see:- (http://www.php.net/curl_exec)
              $x=curl_exec($ch);

?>

PHP , ,

Calling Cache Store Procedure through SQL

May 15th, 2009

We can call a cache SP from SQL in the following way.

Define SP in Cache:-

Class User.test Extends %Persistent
{
 
   ClassMethod t1(p as %String) As %String [ SqlProc ]
  {
     s ^Asad($H)=p
     q 1
  }
}

Query to Call this SP:-
select Test_t1(’Test1′) from SQLUser.Test

Example to calling SP if the class is in package:-

Class TestPkg.test Extends %Persistent
{

ClassMethod t1(p As %String) As %String [ SqlProc ]
{
      s ^Asad($zdt($H))=p
      q 1
}
}

SQL Query :-

 

select TestPkg.Test_t1(’Test1′) from TestPkg.Test 

 

This is the way how you can call cache store procedures from SQL. This is very helpful in the scenarios when using cache with other languages like java or .net.

Cache , , , ,

REACT^STU1 routine ALternative

April 9th, 2009

REACT^STU1 routine woks fine on cache version 5.21 (Linux). but surprisingly the command does not work in the cache 2007.x and cache 2008.x for Linux the command works fine for the windows version of cache but did not work accordingly in the Linux. This command is used to refresh the cache.cpf files changes in the cache without restarting the cache instance. for example if you change cache.cpf file programmatically and want cache to reflect those changes without restart you need to run the REACT^STU1 command on previous version of cache for Linux(5.21) but in cache 2007 and 2008 you need to add the following command before that command.

do ##class(Config.Configuration).CPFImport($p($zu(86),”*”,1))
and then write the following command
REACT^STU1($p($zu(86),”*”,1),0,2,1)
this will solve your problem .

Cache , , , , ,

Using BackgroundWorker Class

March 19th, 2009

When running a large task on windows from application the application may seems to be un-responsive and some time it looks that the application is in the state of non-responding.

 Start a new Windows Form Application. Drag a button and a Label on the form write the following lines of code in the click event of the button.

for (int i = 0; i < 10; i++)
{
     label1.Text =
” Itreation No “
+ i.ToString();
     System.Threading.
Thread
.Sleep(1000);
 }

Now run the application and u will see that the text on the label is not updating and the application looks like non-responsive.

To overcome this problem the BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events (DoWork , ProgressChanged , RunWorkerCompleted )  that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox.

 To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

  //Create a background worker

private System.ComponentModel.BackgroundWorker backgroundWorker1;

Call this method from the constructor of the form to initialize the background worker object.

private void InitializeBackgoundWorker()
{
    //create a new Background Worker
     this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();     
      
     
// backgroundworker can report progress updates.

   this.backgroundWorker1.WorkerReportsProgress = true;
       
     
// Set up the BackgroundWorker object by attaching event handlers. 

     backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
     backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}

 


private int showMessage(BackgroundWorker worker, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
label1.Text = ” Itreation No “ + i.ToString();
System.Threading.Thread.Sleep(1000);
// call the worker object to show the progress.
//This will call the backgroundWorker1_ProgressChanged Method.

worker.ReportProgress(i * 10);
}
return 1;
}

 


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;


// Assign the result to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.

e.Result = showMessage(worker, e);
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// You can show a progress bar or what ever you want to indicate progress
// This event will fire when you call the ReportProgress method of the Background Worker Object

}

C# , , , , , ,

Advance Screen Scrapping

February 16th, 2009

In the Previous article we disscuss the Simple Screen Scraping task using C#. Now we are moving towards advance Screen Scrapping in this we will Scrap the data which required user to login first. This is a very interesting and challenging task. In the following code we will scrap data from the elance site.

// Create the Web Request Object and pass it the URL of the Login page.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(”https://secure.elance.com/php/reg/main/signInAHR.php”);

// Set that request is coming from some browser e.g. Fire Fox.

req.UserAgent = “User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5″;

// assign a new cookie to the cookie container.

req.CookieContainer = new CookieContainer();

// Set values for the request

req.Method = “POST”;
req.ContentType = “application/x-www-form-urlencoded”;
req.KeepAlive = true;
req.Accept = “text/javascript, text/html, application/xml, text/xml, */*”;
req.Referer = “https://secure.elance.com/php/reg/main/signInIframe.php”;

Now the most trickey section we have to send the user name and password to the requested page.I almost every case the user name and password are sent as post data. so we have to create a post data accordingly.

strNewValue = “referrer=http://www.elance.com/p/landing/provider.html”;
strNewValue += “&mode=signin”;
strNewValue += “&login_name=elance_User”;
strNewValue += “&password=elance_pwd”;
strNewValue += “&email1=”;
strNewValue += “&email2=”;

byte[] byteArray = Encoding.UTF8.GetBytes(strNewValue);

// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;

// Get the request stream.
Stream dataStream = req.GetRequestStream();

// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

// Do the request to get the response
HttpWebResponse wr = (HttpWebResponse)req.GetResponse();

// get the Login Cookie
CookieContainer ccTemp = req.CookieContainer;

Now you can use this cookie Container with every further request you send to the site and in response you will get the logged-in data.

C# , , , , ,

Simple Screen Scraping in C#

January 26th, 2009

In C# Microsoft has provided HttpWebRequest and HttpWebResponse classes for the screen Scraping task. you have to write only few lines to get the work done.

String URL = @”www.abcd.com”;
// Prepare the HttpWebRequest
System.Net.HttpWebRequest htpreq = (HttpWebRequest)System.Net.WebRequest.Create(URL); 
// Define Method Get
htpreq.Method =“GET”; 
// Get the Response

System.Net.WebResponse htpRes = htpreq.GetResponse(); 

// Read the Response Stream
System.IO.StreamReader sr = new System.IO.StreamReader(htpRes.GetResponseStream()); 
 //get the response in string format.
String result = sr.ReadToEnd();
// Create a text File name test.text
System.IO.StreamWriter file = System.IO.File.CreateText(”test.text”);
// write the results in the file
file.Write(result);
// Close the File
file.Close();


Done.

C# , , , , ,