Friday, October 25, 2013

CREATE-REMOVE-ADD IN JSON USING JAVASCRIPT

//CREATING JSON OBJECT
        var Obj = { Languages: [] };

        //ADDING ITEMS TO JSON OBJECT
        Obj.Languages.push({ id: "1", Name: 'C Language' });
        Obj.Languages.push({ id: "2", Name: 'C++ Language' });
        Obj.Languages.push({ id: "3", Name: 'JAVA' });
        Obj.Languages.push({ id: "4", Name: 'JAVASCRIPT' });
        Obj.Languages.push({ id: "5", Name: 'JQUERY' });

        //REMOVING ITEMS FROM JSON OBJECT
        Obj.Languages.pop();

        //REMOVING PARTICULAR ITEM FROM JSON OBJECT
        Obj.Languages.splice(2, 1);

        //ADDING NEW ITEM IN MIDDLE
        //SIGNATURE OF splice(INDEX, COUNT TO DELETE FROM INDEX, JSON OBJECT TO ADD NEW ITEM)
        Obj.Languages.splice(2, 0, { id: 5, Name: 'DOTNET' });

Saturday, October 5, 2013

CALCULATING DISTANCE BETWEEN TWO PLACES ASP.NET

Calculating distance between two places made easy by GOOGLE MAP's DISTANCE MATRIX.  Google Map Matrix is an opensource api which will return Json & Xml as responces for its each request.

Here we can get google map search suggestions too using google map's javascript api.  By this the text box you enter for desired place will show you google map's search suggestions.

Let go to code.

Html in aspx file:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Google Maps</title>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
        type="text/javascript"></script>
    <script type="text/javascript">
        //for getting origin autocomplete google map results
        function OrginAutoComplete() {
            try {
                var input = document.getElementById('TextBox1');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }

        //for getting destination autocomplete google map results
        function DestAutoComplete() {
            try {
                var input = document.getElementById('TextBox2');
                var autocomplete = new google.maps.places.Autocomplete(input);
                autocomplete.setTypes('changetype-geocode');
            }
            catch (err) {
                // alert(err);
            }
        }

        
        google.maps.event.addDomListener(window, 'load', OrginAutoComplete);
        google.maps.event.addDomListener(window, 'load', DestAutoComplete);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0" align="center" width="700">
            <tr>
                <td colspan="2" height="40">
                    <b>Distance calculation using Google API</b>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    Enter Orgin Place
                </td>
                <td class="style1">
                    <asp:TextBox ID="TextBox1" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td height="30">
                    Enter Destination Place
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="300"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="60">
                    <asp:Button ID="btnSearch" runat="server" Text="Calculate Distance" OnClick="btnSearch_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center" height="40">
                    <br />
                    <br />
                    <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
                </td>
            </tr>
        </table>
        <br />
    </div>
    </form>
</body>

</html>

Code in Button Click event:

protected void btnSearch_Click(object sender, EventArgs e)
    {
        //Declare variable to store XML result
        string xmlResult = null;

        //Pass request to google api with orgin and destination details
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + TextBox1.Text + "&destinations=" + TextBox2.Text + "&mode=Car&language=us-en&sensor=false");

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //Get response as stream from httpwebresponse
        StreamReader resStream = new StreamReader(response.GetResponseStream());

        //Create instance for xml document
        XmlDocument doc = new XmlDocument();

        //Load response stream in to xml result
        xmlResult = resStream.ReadToEnd();

        //Load xmlResult variable value into xml documnet
        doc.LoadXml(xmlResult);

        string output = "";

        try
        {
            //Get specified element value using select single node method and verify it return OK (success ) or failed
            if (doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/status").InnerText.ToString().ToUpper() != "OK")
            {
                lblResult.Text = "Invalid City Name please try again";
                return;
            }

            //Get DistanceMatrixResponse element and its values
            XmlNodeList xnList = doc.SelectNodes("/DistanceMatrixResponse");
            foreach (XmlNode xn in xnList)
            {
                if (xn["status"].InnerText.ToString() == "OK")
                {
                    //Form a table and bind it orgin, destination place and return distance value, approximate duration
                    output = "<table align='center' width='600' cellpadding='0' cellspacing='0'>";
                    output += "<tr><td height='60' colspan='2' align='center'><b>Travel Details</b></td>";
                    output += "<tr><td height='40' width='30%' align='left'>Orgin Place</td><td align='left'>" + xn["origin_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Destination Place</td><td align='left'>" + xn["destination_address"].InnerText.ToString() + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Travel Duration (apprx.)</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/duration/text").InnerText + "</td></tr>";
                    output += "<tr><td height='40' align='left'>Distance</td><td align='left'>" + doc.DocumentElement.SelectSingleNode("/DistanceMatrixResponse/row/element/distance/text").InnerText + "</td></tr>";
                    output += "</table>";

                    //finally bind it in the result label control
                    lblResult.Text = output;
                }
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = "Error during processing";
            return;
        }

    }


Let's step into the code

First we need design our aspx page with two text boxes and one button. One for origin, another for destination and button for calculating distance.  In this aspx file we need to refer googles map's javascript api file as follows

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>

and after this there are two javascript functions OrginAutoComplete for getting search suggestions for Origin text box and DestAutoComplete for getting search suggestions for destination text box.  After adding these two functions we need to refer these methods for google map's event listeners. Till now we have completed design and search suggestions part of this demo.  Now lets go to code part which comprises of sending origin and destination details as request to google map's api and gathering the response and parsing it for getting the exact distance, time and exact location details.

If you need explanation for the code, just refer the code block you can get a good idea about this by comment lines which i have mentioned for line by line.

Any Queries Kindly let me know.

Happy coding.... 




Sunday, May 26, 2013

JSON WEBSERVICE IN ASP.NET


Here we will see how to return json from asp.net webservice and how to use in our html or aspx page.

EXPLANATION:
Json is one of the data transfer format like xml.  JSON stands for JAVA SCRIPT OBJECT NOTATION. Now a days may of the application like Google, Facebook, Twitter etc., are using JSON as their data transfer format.  As an asp.net developer you can parse this JSON both in backend coding like C# and client script like JAVASCRIPT.  Taking help of JQuery will be added advantage in parsing the json content.

By using a jquery you can easily call a webservice without any backend technology.  In this case you can create a asp.net webservice that returns json and call you can call it in both html or aspx pages.  This makes webpages lighter & faster.

PROCEDURE :
Lets create a New asp.net empty website project.  Add webservice with your desired name.  Add the following name spaces

System.Web.Script.Serialization
&
System.Web.Script.Services

Now start coding your database function that should return json instead of dataset.  Create a function with return type string and with its arguments.  Now get fill the dataset from the database and then create a multi dimensional array with the size of datatable.  Now lopp your datarows data into the each array item.  Now the data is converted from dataset to array.  Now by using JavaScriptSerializer class convert the array to a json string and return it.

Now on your ASPX or HTML page using jquery ajax call this webservice method by passing the necessary parameters into the data property.   That’s it you will get the result in the result object.

EXAMPLE EXPLANATION:
In my example I have used “northwind” database and getting the employees.  I created a webservice with a method “GetEmployees” which takes a “searchterm” as argument and returns the employees those first name match with the search term.  Below method which I have used to return employees as json

public string GetEmployees(string SearchTerm)
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SELECT e.EmployeeID,e.FirstName,e.LastName,e.Title,e.[Address]  FROM Employees e WHERE FirstName LIKE '%" + SearchTerm + "%'";
            //cmd.CommandType = CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.SelectCommand.Connection = con;
            da.Fill(ds);
            con.Close();
            // Create a multidimensional array
            string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
            int i = 0;
            foreach (DataRow rs in ds.Tables[0].Rows)
            {
                EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Title"].ToString(), rs["Address"].ToString() };
                i = i + 1;
            }

            // Return JSON data
            JavaScriptSerializer js = new JavaScriptSerializer();
            string strJSON = js.Serialize(EmpArray);
            return strJSON;
        }
        catch (Exception ex) { return errmsg(ex); }
    }

I have used this webservice in an html page to fill the employee table using jquery and the html looks as follows.

<head>
    <title></title>
    <script src="App_Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function GetEmployees() {
            try {
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    url: 'NorthWindService.asmx/GetEmployees',
                    data: '{ SearchTerm: "' + $("#txtSearch").val() + '" }',
                    dataType: 'json',
                    success: function (msg) {
                        //alert($("#txtSearch").val());
                        var c = eval(msg.d);
                        $("#empTable").find("tr:gt(0)").remove();
                        for (var i in c) {                           
                            $('#empTable tr:first').after('<tr><td>' + c[i][0] + '</td><td>' + c[i][1] + '</td><td>' + c[i][2] + '</td><td>' + c[i][3] + '</td></tr>');
                        }
                    }
                });
            }
            catch (e) { alert(e); }
        }
        $(document).ready(function () {
            GetEmployees();
        });
    </script>
</head>
<body>
    <input type="text" id="txtSearch" onkeyup="GetEmployees();" />
    <table id="empTable">
        <tr>
            <th>
                FirstName
            </th>
            <th>
                LastName
            </th>
            <th>
                Title
            </th>
            <th>
                Address
            </th>
        </tr>
    </table>
</body>

I have given a link above of a sample project.  Kindly check out that for your reference with a northwind database.


Kindly, let me know if any queries.

Wednesday, March 13, 2013

App_Offline.htm in ASP.NET


One of the most useful features of ASP.NET is the “App_Offline.htm” . It provides a much easy way to make the ASP.NET application offline while we do our modifications on the site.

How we do it?

We just create a file and name it exactly  as ‘app_offline’ and place it in the root of a web application directory that we have configured within IIS., This will make the site offline, unload the application domain from the server, and stop processing any new incoming requests for that application.It will serve the contents of the app_offline.htm file in response to all new dynamic requests for the application.

How we make the site online?

Once we rename/remove the App_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and it will be back to normal.
This feature is first introduced in ASP.NET 2.0 and it is available now in all the later versions.
Just give the App_offline.htm page's content as follows.  This will be displayed for every request to that domain.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <title></title></head><body>    <h1>        WEBSITE IS UNDER MAINTENANCE</h1></body></html>


Kindly share your feedback.

Postback Issue and retrieving values - asp.net dynamic controls


In my last post “CREATINGCONTROLS DYNAMICALLY IN ASP.NET” I have explained about creating controls dynamically in asp.net.
Postback Issue Solving :
By creating controls dynamically for each and every post back the controls will get cleared.  This is due to the lack of initialization of these controls.  If we initialize an asp.net server control in aspx page then there is no need of initializing this control every time, objects will be initiated while parsing the aspx page itself.  By in case of dynamically created controls there will not be any initialization in postbacks so the solution for the controls to stay at postback is – Creating the controls on page load and repeating the creation process in each and every postback.  Now after a change my cs file’s code will look like as follows
    protected void Page_Load(object sender, EventArgs e)
    {
        if (hdfTemp.Value == "1") { CreateForm(); }
    }
    protected void btnGenerateForm_Click(object sender, EventArgs e)
    {
        if (hdfTemp.Value == "0") { CreateForm(); hdfTemp.Value = "1"; }
    }
    public void CreateForm()
    {
        try
        {
            //Create Table
            Table tbl = new Table();
            tbl.ID = "tbl";
            //Creating Table row
            TableRow tr = new TableRow();
            tr.ID = "tr1";
            tbl.Rows.Add(tr);//adding table row to the table
            //Creating table cell
            TableCell tc1 = new TableCell();
            TableCell tc2 = new TableCell();
            //Adding table cells to table rows
            tr.Cells.Add(tc1);
            tr.Cells.Add(tc2);
            //Creating Label
            Label lbl = new Label();
            lbl.Text = "First Name";
            lbl.ID = "lblFirstName";
            //Creating TextBox
            TextBox txt = new TextBox();
            txt.ID = "txtFirstName";
     //Assigning the label and textbox controls as child controls for table cells
            tc1.Controls.Add(lbl);
            tc2.Controls.Add(txt);
            phDCtrls.Controls.Add(tbl);
            tblForm.Visible = true;
        }
        catch (Exception ex) { Response.Write(ex.Message); }

    }
Here in the above code I have use a hidden field for avoiding the generation of dynamic controls on first time page loads, because in this scenario only after clicking on the Generate Controls button the controls should get generated.  If you want controls to be generated on page load then no need of using hidden field.

Retrieving values from dynamically generated controls

Controls can be found on the page with their ids.  While creating controls we have specified a unique id for each control.  With this ids we can find the control on the page using “Findcontrol()” method.  Now let’s get the form values in our example on clicking the save button.

  • We have created an id for textbox as “txtFirstName”.
  • Create a textbox object with name txtFirstName.
  • Equal this textbox object with the result of findcontrol method.  Now you got your textbox on this object.
  • Now the textbox’s text property will gives the value of the textbox.

The sample code on save button click event handler will be as follows.
try
{
    TextBox txt = (TextBox)this.Page.FindControl("txtFirstName");
    ScriptManager.RegisterClientScriptBlock(Page, GetType(), "alert", "alert('" + txt.Text.Trim() + "');", true);
}
catch (Exception ex) { Response.Write(ex.Message); }


If any issues or queries, kindly let me know


Happy coding…

Dynamic Controls in ASP.NET


The situation may occur that controls to be created dynamically at runtime, these controls should react for their events i.e., dynamically generated controls should be event driven.  For handling these kinds of situations this post will be very useful. 
First of all we will see how to create and show controls on the form dynamically with an example.  In this example I’m creating a form with one label and one textbox aligned in a table control.
In asp.net, every control can be added as a child control for other container controls like placeholder control, panel control etc.  In this way here also we will create controls and add those controls to one of the parent controls.
  • Create a place holder control which will hold our dynamically created controls.
  • Create a button in which on this button click we are creating and showing controls on the page.  The code which I have written in aspx page will be as follows.


<asp:Button ID="btnGenerateForm" runat="server" Text="Generate Form" OnClick="btnGenerateForm_Click" />
        <table id="tblForm" runat="server" visible="false">
            <tr>
                <td>
                    <asp:PlaceHolder ID="phDCtrls" runat="server"></asp:PlaceHolder>
                </td>
            </tr>
            <tr>
                <td align="right">
                    <table>
                        <tr>
                            <td>
                                <asp:Button runat="server" ID="btnSave" Text="Save" />
                            </td>
                            <td>
                                <asp:Button runat="server" ID="btnClear" Text="Clear" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
  •  On click event of the Generate form button write the following code.

        try
        {
            //Create Table
            Table tbl = new Table();
            tbl.ID = "tbl";
            //Creating Table row
            TableRow tr = new TableRow();
            tr.ID = "tr1";
            tbl.Rows.Add(tr);//adding table row to the table
            //Creating table cell
            TableCell tc1 = new TableCell();
            TableCell tc2 = new TableCell();
            //Adding table cells to table rows
            tr.Cells.Add(tc1);
            tr.Cells.Add(tc2);
            //Creating Label
            Label lbl = new Label();
            lbl.Text = "First Name";
            lbl.ID = "lblFirstName";
            //Creating TextBox
            TextBox txt = new TextBox();
            txt.ID = "txtFirstName";

      //Assigning the label and textbox controls as child controls for table cells
            tc1.Controls.Add(lbl);
            tc2.Controls.Add(txt);

            phDCtrls.Controls.Add(tbl);
            tblForm.Visible = true;
        }
        catch (Exception ex) { Response.Write(ex.Message); }
  • In the above code I first created a table control for that table control I created a table row and added that row to the table control.  Then created two table cells and added these table cells to the table row.  Now created one label control and one textbox control and added these controls to the table cell.  Finally I added the table control to the place holder control which we have created in the aspx page.  Here as I explained previously the table control is the child for the placeholder control, table row is child for table, table cells are child for table row and label and textbox controls are child for table cells.


In this way we can create controls dynamically.  But the problem in creating these controls dynamically is lacking of view state.  So that for every post back the controls will get disappear.  Try this by clicking on the save button which we have created on aspx page.

The solution for this problem and getting values from these dynamically generated controls will be explained in my next post "Postback Issue and retrieving values - asp.net dynamic controls".

Happy coding…

Tuesday, February 19, 2013

Image resizing in asp.net

Introduction:-

            This tutorial will show you how to generate image thumbnails dynamically from an original big image.

Background:-

            Many of the web developers will show the big images as small by giving the attribute values for the image tag.  This will slow down the webpage loading.  For better performance the best method is creating the small thumbnail images for showing small size image on the web pages.  But for every upload of the images by the user we cannot create a thumbnail image, it’s a tedious process.  I planed to create a method which will create a thumbnail automatically while the image upload and saves in a separate path.  This is a light weight process and easy to use.  The only thing is you have to add one more filed for saving the thumbnail image path while dealing with databases.

Following are the features of this technique.
  • Good Quality.
  • Desired thumbnail size.

Using the code:-

            Below is the method which will generates the thumbnail and saves to the destination folder.

public void GenerateThumbNail(string sourcefile, string destinationfile,int width)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));
        int srcWidth = image.Width;
        int srcHeight = image.Height;
        int thumbWidth = width;
        int thumbHeight;
        Bitmap bmp;
        if (srcHeight > srcWidth)
        {
            thumbHeight = (srcHeight / srcWidth) * thumbWidth;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }
        else
        {
            thumbHeight = thumbWidth;
            thumbWidth = (srcWidth / srcHeight) * thumbHeight;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }

        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
        bmp.Save(Server.MapPath(destinationfile));
        bmp.Dispose();
        image.Dispose();
    }

      In the above method we are passing three parameters first one is the soruce location of the image and the second one is the destination location of the image and the third parameter is the width.  At first we need to include two namespaces

using System.Drawing;
using System.Drawing.Drawing2D;

Then create an instance image from the source file as follows

System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));

After getting the image height and width using the instance of the image we need to set the targetted thumbnail image’s height and width. Create and instance for the bitmap.  By using the below logic we can get the width and height of the targetted thumbnail.  Set the thumbnails’s width and height to the bitmap.

Bitmap bmp;
        if (srcHeight > srcWidth)
        {
            thumbHeight = (srcHeight / srcWidth) * thumbWidth;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }
        else
        {
            thumbHeight = thumbWidth;
            thumbWidth = (srcWidth / srcHeight) * thumbHeight;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }

After this for creating the high quality thumbnails create an instance for the Graphics class with the bitmap.  Set the SmoothingMode and CompositingQuality to HighQuality and InterpolationMode to Hign.  Then draw a rectangle with the thumbnail’s height and width using the rectangle class and place the image inside the rectangle using the DrawImage class.  Now the bitmap image i.e., thumbnail image is ready.  Now save the thumbnail the the destination location using bmp.save(/*destination location*/) method.

            I think mostly this example will help in website development for loading webpages fast with small images instead of loading large image with small sizes.