Wednesday, July 10, 2013

How to call code behind method from jquery

ASPX PAGE
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!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 runat="server">
    <title></title>
    <script src="myjavascript.js" type="text/javascript"></script>
    <script type = "text/javascript">
        function DisplayMessageCall() {

            var pageUrl = '<%=ResolveUrl("~/WebService/HelloWorld.asmx")%>'

            $('#<%=lblOutput.ClientID%>').html('Please wait...');

            $.ajax({
                type: "POST",
                url:  "Default4.aspx/DisplayMessage",
                data: "{'NameInfo':'" + $('#<%=txtName.ClientID%>').val()
                    + "','Location':'" + $('#<%=txtLocation.ClientID%>').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccessCall,
                error: OnErrorCall
            });

        }

        function OnSuccessCall(response) {
            $('#<%=lblOutput.ClientID%>').html(response.d);
        }

        function OnErrorCall(response) {
            alert(response.status + " " + response.statusText);
        }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h2>&nbsp;Call Webmethod using JQuery AJax (With Multiple Input)</h2>
Enter your Name: <asp:TextBox ID="txtName" runat="server" Text=""></asp:TextBox><br />
Enter Location: <asp:TextBox ID="txtLocation" runat="server" Text=""></asp:TextBox><br />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me"
            OnClientClick="DisplayMessageCall();return false;" onclick="btnGetMsg_Click" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

    </div>
    </form>
</body>
</html>



CODE BEHIND PAGE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class Default4 : System.Web.UI.Page
{
    [WebMethod]
        public static string DisplayMessage(string NameInfo, string Location)
        {
            //Creating Delay
            System.Threading.Thread.Sleep(1000);
            return "Welcome " + NameInfo + ", Your location is " + Location;
        }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnGetMsg_Click(object sender, EventArgs e)
    {

    }

}

How to use toggle in Jquery

ASPX PAGE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!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 runat="server">
    <script src="myjavascript.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {

        alert("I am ready!");
            $("div.test").add("p.quote").html("a little test").toggle(3000);
      });

   
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="test">
  <p class="quote"> this is division...</p>
    </div>
    </form>
</body>
</html>

How to bind gridview with Jquery

ASPX Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default9.aspx.cs" Inherits="Default9" %>

<!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 runat="server">
    <title></title>
    <script src="myjavascript.js" type="text/javascript"></script>
    <script type="text/javascript">
       
        $(function () {
            $("div.test").toggle(15000)
            $.ajax({

            type: "POST",
            url: "Default9.aspx/GetCustomers",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    });

    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Table");
        var row = $("[id*=gvCustomers] tr:last-child").clone(true);
        $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
        $.each(customers, function () {
            var customer = $(this);
            $("td", row).eq(0).html($(this).find("RBDID").text());
            $("td", row).eq(1).html($(this).find("BATCHID").text());
            $("td", row).eq(2).html($(this).find("REQUESTID").text());
            $("[id*=gvCustomers]").append(row);
            row = $("[id*=gvCustomers] tr:last-child").clone(true);
        });
    }
</script>


</head>
<body>
    <form id="form1" runat="server">
    <div class="test">
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
    Font-Size="10pt" RowStyle-BackColor="#A1DCF2" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor = "White">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="RBDID" HeaderText="CustomerID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="BATCHID" HeaderText="CustomerID" />
        <asp:BoundField ItemStyle-Width="150px" DataField="REQUESTID" HeaderText="City" />
    </Columns>
</asp:GridView>

<asp:Button runat="server" ID="b1" Text="click me" />
    </div>
    </form>
</body>
</html>


Code Behind Page

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

public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindDummyRow();
        }
    }

    private void BindDummyRow()
    {
        DataTable dummy = new DataTable();
        dummy.Columns.Add("RBDID");
        dummy.Columns.Add("BATCHID");
        dummy.Columns.Add("REQUESTID");
        dummy.Rows.Add();
        gvCustomers.DataSource = dummy;
        gvCustomers.DataBind();
    }



    [WebMethod]
    public static string GetCustomers()
    {
        string query = "select top 10 RBDID,BATCHID,REQUESTID From dbo.RG_ResponseBatchData";
        SqlCommand cmd = new SqlCommand(query);
        return GetData(cmd).GetXml();
    }
    private static DataSet GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;

                }
            }
        }
    }

}


Sunday, July 7, 2013

Access server side function using JQuery.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Website1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script lang="javascript" src="JQuery.js" type="text/javascript"></script>
    <script lang="javascript">
            function chk()
            {
            $.ajax (
            {
                type: "POST",
                url: "WebForm1.aspx/show",  // show is the name of function 
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType:"json",
                async: true,
                cache: false,
                success: function (msg) 
                {
                    $('#div1').text(msg.d); 
                },
                error: function (x, e)
                {
                alert("The call to the server side failed. " + x.responseText);
                }
            });
                return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="div1" style="width:500px; height:40px; background-color:aqua">

            This is hidable.

        </div>

    <div>
        <asp:TextBox ID="Text"  CssClass="abc" Text="" runat="server"></asp:TextBox>
        <asp:Button ID="btnShow" OnClientClick="return chk();" runat="server" OnClick="btnShow_Click" Text="Javascript" />
    </div>
    </form>
</body>
</html>

Thursday, June 27, 2013

Complex Queries in SQL- Part1

  1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);
  2. To select ALTERNATE records from a table. (ODD NUMBERED)select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);
  3. Find the 3rd MAX salary in the emp table.select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <= e2.sal);
  4. Find the 3rd MIN salary in the emp table.select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal >= e2.sal);
  5. Select FIRST n records from a table.select * from emp where rownum <= &n;
  6. Select LAST n records from a tableselect * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);
  7. List dept no., Dept name for all the departments in which there are no employees in the department.select * from dept where deptno not in (select deptno from emp); 
    alternate solution:  select * from dept a where not exists (select * from emp b where a.deptno = b.deptno);
    altertnate solution:  select empno,ename,b.deptno,dname from emp a, dept b where a.deptno(+) = b.deptno and empno is null;
  8. How to get 3 Max salaries ?select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <= b.sal) order by a.sal desc;
  9. How to get 3 Min salaries ?select distinct sal from emp a  where 3 >= (select count(distinct sal) from emp b  where a.sal >= b.sal);
  10. How to get nth max salaries ?
    select distinct hiredate from emp a where &n =  (select count(distinct sal) from emp b where a.sal >= b.sal);
  11. Select DISTINCT RECORDS from emp table.select * from emp a where  rowid = (select max(rowid) from emp b where  a.empno=b.empno);
  12. How to delete duplicate rows in a table?delete from emp a where rowid != (select max(rowid) from emp b where  a.empno=b.empno);
  13. Count of number of employees in  department  wise.select count(EMPNO), b.deptno, dname from emp a, dept b  where a.deptno(+)=b.deptno  group by b.deptno,dname;
  14.  Suppose there is annual salary information provided by emp table. How to fetch monthly salary of each and every employee?
select ename,sal/12 as monthlysal from emp;
  1. Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
  1. Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;
  1. Select  all record  from emp where job not in SALESMAN  or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
  1. Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.
select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');
  1. Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
  1. Select all records where ename may be any no of  character but it should end with ‘R’.
select * from emp where ename like'%R';
  1. Count  MGR and their salary in emp table.
select count(MGR),count(sal) from emp;
  1. In emp table add comm+sal as total sal  .
select ename,(sal+nvl(comm,0)) as totalsal from emp;
  1. Select  any salary <3000 from emp table. 
select * from emp  where sal> any(select sal from emp where sal<3000);
  1. Select  all salary <3000 from emp table. 
select * from emp  where sal> all(select sal from emp where sal<3000);
  1. Select all the employee  group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
  1. How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
  1. How to retrive record where sal between 1000 to 2000?
    Select * from emp where sal>=1000 And  sal<2000
  2. Select all records where dept no of both emp and dept table matches.
    select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
  3. If there are two tables emp1 and emp2, and both have common record. How can I fetch all the recods but common records only once?
    (Select * from emp) Union (Select * from emp1)
  4. How to fetch only common records from two tables emp and emp1?
    (Select * from emp) Intersect (Select * from emp1)
  5.  How can I retrive all records of emp1 those should not present in emp2?
    (Select * from emp) Minus (Select * from emp1)
  6. Count the totalsa  deptno wise where more than 2 employees exist.
    SELECT  deptno, sum(sal) As totalsal
    FROM emp
    GROUP BY deptno
    HAVING COUNT(empno) > 2


Message Contract in Wcf

Consume Class:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Enter a Key");
                string _AuthorId = Console.ReadLine();
                ServiceReference1.ServiceClient sc = new ServiceReference1.ServiceClient();
                ServiceReference1.Author a = sc.GetAuthorInfo(_AuthorId);
                if (a != null)
                {
                    Console.WriteLine(a.ArticleId);
                    Console.WriteLine(a.FirstName);
                    Console.WriteLine(a.LastName);

                }
                else
                {
                    Console.WriteLine("Key is not valid");
                }
                    Console.ReadLine();
            }
            catch (FaultException<string> e1)
            {
                Console.WriteLine(e1.Message);
                Console.WriteLine(e1.Reason);
                Console.WriteLine(e1.Detail);
            }
        }
    }
}



Service.Cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    private const string _AuthorId = "Gulshan";
    SqlConnection con;

    SqlDataAdapter dap;
    DataSet ds;
    public bool CreateConnection(AuthorRequest Req)
    {
        con = new SqlConnection();
        con.ConnectionString = "Data Source=xxxx;Initial Catalog=Master;User Id=xxxxx;Password=xxxxxx;";

        dap = new SqlDataAdapter("SELECT EMP_ID FROM Employee_Test1 where EMP_ID='"+Req._AuthorId+"'", con);
        ds = new DataSet();
        dap.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string x = "Data Exists";
            return true;

        }
        else
        {
            return false;
        }
       


    }


    public AuthorResponse GetAuthorInfo(AuthorRequest Req)
    {
        bool b=CreateConnection(Req);
        if (b == true)
        {

            //if (Req._AuthorId != _AuthorId)
            //{
            //    string _Error = "Invalid Author Id";
            //    throw new FaultException<string>(_Error);
            //}
            AuthorResponse au = new AuthorResponse();
            au.Obj = new Author();
            au.Obj.FirstName = "Gulshan Kumar";
            au.Obj.LastName = "Arora";
            au.Obj.ArticleId = "11001";
            return au;

        }
        else
        {
            AuthorResponse au = new AuthorResponse();
            au.Obj = null;
            return au;

        }
     
    }
}


Interface:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
    [OperationContract]
    [FaultContract(typeof(string))]
    AuthorResponse GetAuthorInfo(AuthorRequest Req);


}
[MessageContract]
public class AuthorRequest
{
    [MessageHeader(Name = "AuthorId")]
    public string _AuthorId;


}
[MessageContract]
public class AuthorResponse
{
    [MessageBodyMember]
   public Author Obj;

}

[DataContract]
public class Author
{
    [DataMember]
    public string FirstName;

    [DataMember]
    public string LastName;

    [DataMember]
    public string ArticleId;
}


Server.Transfer v/s Response.Redirect

Server.Transfer v/s Response.Redirect
Both “Server” and “Response” are objects of ASP.NET. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another page. Both are used for the same purpose but still there are some differences are there between both that are as follows:

      Syntactically both are different, if you want to transfer the user to a page named newpage.aspx then syntax for both methods will be,

Response.Redirect(“newpage.aspx”) and Server.Transfer(“newpage.aspx”)

      Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.

Roundtrip means in case of Response.Redirect it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes But in case of Server.Transfer it directly communicate with the server to change the page hence it saves a roundtrip in the whole process.

How to make generic provider

How to make generic provider




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using System.Configuration;

public partial class Default2 : System.Web.UI.Page
{



    //This Function is to Create Connection
    public static DbConnection CreateConnection(string provider, string connection)
    {
        DbConnection con = null;
        if (con == null)
        {
            try
            {
                DbProviderFactory dp = DbProviderFactories.GetFactory(provider);
                con = dp.CreateConnection();
                con.ConnectionString = connection;
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.Message);
            }
        }
        return con;
    }



    //This Function gets all DataProvider name and information
    public static DataTable GetAllProvider()
    {
        DataTable dt = DbProviderFactories.GetFactoryClasses();
        return dt;
    }

    public static string GetConnectionString(string userProviderName)
    {
        string retreive = null;

        try
        {

       

        ConnectionStringSettingsCollection c = ConfigurationManager.ConnectionStrings;
        if (c != null)
        {
            foreach (ConnectionStringSettings cs in c)
            {
                if (cs.ProviderName == userProviderName)
                {
                   retreive=  cs.ConnectionString;
                   // retreive = cs.ProviderName;
                    break;
                }
            }
        }
        return retreive;

        }
        catch (Exception)
        {
            throw;
           
           
        }
       
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = GetAllProvider();

        for (int i = 0; i < dt.Rows.Count; i++)
            DropDownList1.Items.Add(dt.Rows[i][2].ToString());
        GridView1.DataSource = GetAllProvider();
        GridView1.DataBind();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string _connctionstring = DropDownList1.SelectedItem.Text;
        string s = null;
        if (DropDownList1.SelectedIndex == 0)
        {
             s=GetConnectionString(_connctionstring);
             Response.Write(s);

        }
        else if (DropDownList1.SelectedIndex == 1)
        {
            s = GetConnectionString(_connctionstring);
            Response.Write(s);
        }
        else if (DropDownList1.SelectedIndex == 2)
        {
            s = GetConnectionString(_connctionstring);
            Response.Write(s);
        }
        else if (DropDownList1.SelectedIndex == 3)
        {
            s = GetConnectionString(_connctionstring);
            Response.Write(s);
        }
    }
}




change in web.config


<connectionStrings>
<clear/>  "This Tag is very important else it will not work"
<add name="Sql" connectionString="data source=72.233.78.98;uid=sa; pwd=xxxxxxxx;database=PG_SystemDB" providerName="System.Data.SqlClient"/>
<add name="Odbc" connectionString="data source=72.233.78.98;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.Odbc"/>
<add name="Oledb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.Oledb"/>
<add name="OracleClient" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.OracleClient"/>
</connectionStrings>

Differences Between C++ Templates and C# Generics (C# Programming Guide)

Differences Between C++ Templates and C# Generics (C# Programming Guide)


C# Generics and C++ templates are both language features that provide support for parameterized types. However, there are many differences between the two. At the syntax level, C# generics are a simpler approach to parameterized types without the complexity of C++ templates. In addition, C# does not attempt to provide all of the functionality that C++ templates provide. At the implementation level, the primary difference is that C# generic type substitutions are performed at runtime and generic type information is thereby preserved for instantiated objects. For more information, see Generics in the Runtime (C# Programming Guide).
The following are the key differences between C# Generics and C++ templates:
C# generics do not provide the same amount of flexibility as C++ templates. For example, it is not possible to call arithmetic operators in a C# generic class, although it is possible to call user defined operators.
C# does not allow non-type template parameters, such as template C<int i> {}.
C# does not support explicit specialization; that is, a custom implementation of a template for a specific type.
C# does not support partial specialization: a custom implementation for a subset of the type arguments.
C# does not allow the type parameter to be used as the base class for the generic type.

How to get Ram Details in C#

How to get Ram Details in C#

using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
class Blittable
{
    int x;
}

class Program
{
    public static unsafe void Main()
    {
        int i;
        object o = new Blittable();
        int* ptr = &i;
        IntPtr addr = (IntPtr)ptr;

        Console.WriteLine(addr.ToString("x"));

        GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned);
        addr = h.AddrOfPinnedObject();
        Console.WriteLine(addr.ToString("x"));

        h.Free();
    }
}

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...