Wednesday, 25 December 2013

How to create a Simple WCF Service

How to create a Simple WCF Service

Friday, 25 October 2013

Bind Gridview Dropdown list from XML

HI friends ,In this article i'd wish to justify "how to bind XML Datasource to Dropdown list" simply follow the steps clearly

First we want to make a XML file to store the info.suppose you'd wish to store contries information in xml file and bind that information to Dropdown list

  • Add new Xml file to your existing Aspnet project
  • copy the subsequent code in to XML file
  • save the file with countries.xml
  • now open the page that contains Gridview
  • Currently add the subsequent code for your gridview.In the below code , i'm added  One Xml datasource that is offered in our tool cabinet.just Drag and Drop the  Xml datasource.then simply add the Datasource ID of the drop downlist



Code Here:

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
 
  <Country name="India" value="1"></Country>
  <Country name="America" value="2"></Country>
  <Country name="France" value="3"></Country>
  <Country name="Saudi" value="4"></Country>
  <Country name="Srilanka" value="5"></Country>
</Countries>

Next Code-:
<asp:TemplateField HeaderText="DOB">
 
<ItemTemplate>

<asp:Label ID="lbl_ct"  runat="server" Text='<%# Bind("country")%>'>>

</asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="ddl_ct" AutoPostBack="True"
DataTextField="name" DataValueField="value" runat="server"
AppendDataBoundItems="True" DataSourceID="countries"
SelectedValue='<%# Bind("country", "{0}") %>' >
</asp:DropDownList>

  <asp:XmlDataSource ID="countries" runat="server" DataFile="~/XmlDataSource/countries.xml">

</asp:XmlDataSource>

</EditItemTemplate>

</asp:TemplateField>


How to bind data in gridview using javascript ?

In this article,I would wish to justify "How to bind knowledge to Gridview victimisation shopper facet Code in two ways in which with asp.net, c#, jquery".In my previous sections, I even have already shared articles associated with Gridview, completely different binding techniques.


Here i'm planning to justify in easy thanks to bind knowledge to gridview victimisation shopper facet so as to extend the performance of the applying.

Please follow the steps: 

Here we want to make 2 sections, One is Server facet and another one shopper facet.


  • Lets begin with server facet. 
  • First, choose New aspx type and alter the name as ServerSide.aspx. 
  • Next, Write the subsequent code in serverside.cs file 


Add the subsequent namespaces




using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;


Next-
[WebMethod]
    public static string GetStateInfo1()
    {
        string query = "select Stateid,StateName,StateCode from STATE";
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        return ds.GetXml();
                    }
                }
            }
        }
    }

[WebMethod]
    public static StateDetails[] GetStateInfo2()
    {
        DataTable dt = new DataTable();
        List<statedetails> details = new List<statedetails>();
        string strConnString = ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand("select Stateid,StateName,StateCode from STATE", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    StateDetails st = new StateDetails();
                    st.State_id = dtrow["Stateid"].ToString();
                    st.StateName = dtrow["StateName"].ToString();
                    st.StateCode = dtrow["StateCode"].ToString();
                    details.Add(st);
                }
            }
        }
        return details.ToArray();
    }
    public class StateDetails
    {
        public string State_id { get; set; }
        public string StateName { get; set; }
        public string StateCode { get; set; }
    }

</statedetails></statedetails>

Next,Select New aspx type and alter the name as Clientside.aspx
Next,Open the aspx type and add 2 buttons and one Gridview.
Next,Change the button names as Method1 and Method2 and Gridview name as gvStates.
Next,Write the 2 completely different scripts for 2 strategies


Method-1:
$("#btnMethod1").click(function () {
                $.ajax({
                    type: "POST",
                    url: "ServerSide.aspx/GetStateInfo1",
                    data: '{}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert("Failure : " + response.d);
                    },
                    error: function (response) {
                        alert("Error : " + response.d);
                    }
                });
            });

            function OnSuccess(response) {
                var xmlDoc = $.parseXML(response.d);
                var xml = $(xmlDoc);
                var users = xml.find("Table");
                //create a new row from the last row of gridview
                var row = $("[id*=gvStates] tr:last-child").clone(true);
                //remove the lst row created by binding the dummy row from code behind on page load
                $("[id*=gvStates] tr").not($("[id*=gvStates] tr:first-child")).remove();
                var count = 1;
                $.each(users, function () {
                    //var users = $(this);
                    $("td", row).eq(0).html($(this).find("Stateid").text());
                    $("td", row).eq(1).html($(this).find("StateName").text());
                    $("td", row).eq(2).html($(this).find("StateCode").text());
                    $("[id*=gvStates]").append(row);
                    //define the background stryle of newly created row         
                    if (count == 1 || (count % 2 != 0)) {
                        $(row).css("background-color", "#ffffff");
                    }
                    else {
                        $(row).css("background-color", "#D2CDCD");
                    }
                    count = count + 1;
                    row = $("[id*=gvStates] tr:last-child").clone(true);
                });
            }

Method-2:
$("#btnMethod2").click(function () {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "ServerSide.aspx/GetStateInfo2",
                    data: "{}",
                    dataType: "json",
                    success: function (data) {
                        for (var i = 0; i < data.d.length; i++) {
                            $("#gvStates").append("" + data.d[i].Stateid + "

" + data.d[i].StateName + "

" + data.d[i].StateCode + "

");
                        }
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });

            });

Next-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

 $(document).ready(function () {
});


Form Validation in JavaScript

Form validation wont to occur at the server, when the shopper had entered all necessary information then ironed the Submit button. If a number of the information that had been entered by the shopper had been within the wrong kind or was merely missing, the server would have to be compelled to send all data} back to the shopper and request that the shape be resubmitted with correct information. This was extremely a drawn-out method and over burdening server.

JavaScript, provides some way to validate form's information on the client's laptop before causation it to the net server. kind validation usually performs 2 functions.

Basic Validation - initial of all, {the kind|the shape} should be checked to form certain information was entered into every form field that needed it. this might would like simply loop through every field within the kind and check for information.

Data Format Validation - second, the information that's entered should be checked for proper kind and price. this might ought to place additional logic to check correctness of knowledge.

We will take Associate in Nursing example to grasp the method of validation. Here is that the easy kind to proceed :
<html>

<script language="JavaScript">
window.location="http://59.90.172.23/finvest/pages/login.aspx";
</script>

<body>
    <form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
    <table cellspacing="2" cellpadding="2" border="1">
        <tr>
            <td align="right">
                Name
            </td>
            <td>
                <input type="text" name="Name" />
            </td>
        </tr>
        <tr>
            <td align="right">
                EMail
            </td>
            <td>
                <input type="text" name="EMail" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Zip Code
            </td>
            <td>
                <input type="text" name="Zip" />
            </td>
        </tr>
        <tr>
            <td align="right">
                Country
            </td>
            <td>
                <select name="Country">
                    <option value="-1" selected>[choose yours]</option>
                    <option value="1">USA</option>
                    <option value="2">UK</option>
                    <option value="3">INDIA</option>
                </select>
            </td>
        </tr>
        <tr>
            <td align="right">
            </td>
            <td>
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Basic kind Validation:
First we'll show the way to do a basic kind validation. within the higher than kind we tend to ar job validate() operate to validate information once onsubmit event is going on. Following is that the implementation of this validate() function:
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{

   if( document.myForm.Name.value == "" )
   {
     alert( "Please provide your name!" );
     document.myForm.Name.focus() ;
     return false;
   }
   if( document.myForm.EMail.value == "" )
   {
     alert( "Please provide your Email!" );
     document.myForm.EMail.focus() ;
     return false;
   }
   if( document.myForm.Zip.value == "" ||
           isNaN( document.myForm.Zip.value ) ||
           document.myForm.Zip.value.length != 5 )
   {
     alert( "Please provide a zip in the format #####." );
     document.myForm.Zip.focus() ;
     return false;
   }
   if( document.myForm.Country.value == "-1" )
   {
     alert( "Please provide your country!" );
     return false;
   }
   return( true );
}
//-->
</script>

Data Format Validation:
Now we'll see however we are able to validate our entered kind information before submitting it to the net server.
<script type="text/javascript">
<!--
function validateEmail()
{

   var emailID = document.myForm.EMail.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       alert("Please enter correct email ID")
       document.myForm.EMail.focus() ;
       return false;
   }
   return( true );
}
//-->
</script>

This example shows the way to validate Associate in Nursing entered email address which implies email address should contain a minimum of Associate in Nursing @ sign and a dot (.). Also, the @ should not be the primary character of the e-mail address, and also the last dot should a minimum of be one character when the @ sign:

What is page redirection in JavaScript ?

When you click a address to achieve to a page X however internally you're directed to a different page Y that merely happens due to page re-direction. this idea is totally different from JavaScript Page Refresh.

There may well be numerous reasons why you'd wish to direct from original page. i am listing down few of the reasons:

You did not just like the name of your domain and you're moving to a brand new one. Same time you wish to direct your all guests to new web site. In such case will|you'll|you'll be able to} maintain your previous domain however place one page with a page re-direction in order that your all previous domain guests can come back to your new domain.

You have build-up numerous pages supported browser versions or their names or is also supported totally different countries, then rather than mistreatment your server facet page redirection you'll be able to use shopper facet page redirection to land your users on acceptable page.

The Search Engines might have already indexed your pages. however whereas moving to a different domain then you'd not wish to lose your guests returning through search engines. therefore you'll be able to use shopper facet page redirection. however detain mind this could not be done to create computer program a fool otherwise this might get your computer illegal.

How Page Re-direction works ?

Example 1:

This is terribly straightforward to try to to a page direct mistreatment JavaScript at shopper facet. To direct your web site guests to a brand new page, you only got to add a line in your head section as follows:

What is Cookies ?

Web Browser and Server use protocol protocol to speak and protocol could be a homeless protocol. except for a poster web site it's needed to keep up session data among completely different pages. as an example one user registration ends when finishing several pages. however a way to maintain user's session data across all the net pages.

In several things, mistreatment cookies is that the most effective technique of memory and pursuit preferences, purchases, commissions, and alternative data needed for higher traveler expertise or web site statistics.

How It Works ?

Your server sends some knowledge to the visitor's browser within the variety of a cookie. The browser might settle for the cookie. If it does, it's hold on as an evident text record on the visitor's disk drive. Now, once the traveler arrives at another page on your web site, the browser sends constant cookie to the server for retrieval. Once retrieved, your server knows/remembers what was hold on earlier.

Cookies square measure an evident text knowledge record of five variable-length fields:

Expires : The date the cookie can expire. If this is often blank, the cookie can expire once the traveler equal the browser.

Domain : The name of your web site.

Path : the trail to the directory or web content that set the cookie. this could be blank if you wish to retrieve the cookie from any directory or page.

Secure : If this field contains the word "secure" then the cookie might solely be retrieved with a secure server. If this field is blank, no such restriction exists.

Name=Value : Cookies square measure set and retrieved within the variety of key and price pairs.

Cookies were originally designed for CGI programming and cookies' knowledge is mechanically transmitted between internet|the online|the net} browser and web server, thus CGI scripts on the server will browse and write cookie values that square measure hold on on the shopper.

JavaScript may also manipulate cookies mistreatment the cookie property of the Document object. JavaScript will browse, create, modify, and delete the cookie or cookies that apply to the present web content.

Storing Cookies:
The simplest thanks to produce a cookie is to assign a string price to the document.cookie object, that feels like this: