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();
    }
}

Tuesday, June 25, 2013

Create Xml file in C#

Compiled Code:

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

namespace ConsoleApplication7
{
    class Class2
    {

        public static void Main()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode productsNode = doc.CreateElement("products");
            doc.AppendChild(productsNode);

            XmlNode productNode = doc.CreateElement("product");
            XmlAttribute productAttribute = doc.CreateAttribute("id");
            productAttribute.Value = "01";
            productNode.Attributes.Append(productAttribute);
            productsNode.AppendChild(productNode);

            XmlNode nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("Java"));
            productNode.AppendChild(nameNode);
            XmlNode priceNode = doc.CreateElement("Price");
            priceNode.AppendChild(doc.CreateTextNode("Free"));
            productNode.AppendChild(priceNode);

            // Create and add another product node.
            productNode = doc.CreateElement("product");
            productAttribute = doc.CreateAttribute("id");
            productAttribute.Value = "02";
            productNode.Attributes.Append(productAttribute);
            productsNode.AppendChild(productNode);
            nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("C#"));
            productNode.AppendChild(nameNode);
            priceNode = doc.CreateElement("Price");
            priceNode.AppendChild(doc.CreateTextNode("Free"));
            productNode.AppendChild(priceNode);

            doc.Save(Console.Out);
            Console.ReadLine();
         
        }
    }
}

Friday, June 14, 2013

Using Typeof Operator in C#

Using typeof

// Demonstrate typeof.
using System;
using System.IO;
class UseTypeof {
static void Main() {
Type t = typeof(StreamReader);
Console.WriteLine(t.FullName);
if(t.IsClass) Console.WriteLine("Is a class.");
if(t.IsAbstract) Console.WriteLine("Is abstract.");
else Console.WriteLine("Is concrete.");
}
}
This program outputs the following:
System.IO.StreamReader
Is a class.
Is concrete.

Using "as" Operator in C#

Using as
Sometimes you will want to try a conversion at runtime, but not throw an exception if the
conversion fails (which is the case when a cast is used). To do this, use the as operator,
which has this general form:
expr as type


Here, expr is the expression being converted to type. If the conversion succeeds, then a
reference to type is returned. Otherwise, a null reference is returned. The as operator can
be used to perform only reference, boxing, unboxing, or identity conversions.
The as operator offers a streamlined alternative to is in some cases. For example,
consider the following program that uses is to prevent an invalid cast from occurring:
// Use is to avoid an invalid cast.
using System;
class A {}
class B : A {}
class CheckCast {
static void Main() {
A a = new A();
B b = new B();
// Check to see if a can be cast to B.
if(a is B) // if so, do the cast
b = (B) a;
else // if not, skip the cast
b = null;
if(b==null)
Console.WriteLine("The cast in b = (B) a is NOT allowed.");
else
Console.WriteLine("The cast in b = (B) a is allowed");
}
}

How to Compare Type in C#

How to CompareType

using System;
class A { }
class B : A { }
class UseIs
{
static void Main()
{
A a = new A();
B b = new B();
if (a is A) Console.WriteLine("a is an A");
if (b is A)
Console.WriteLine("b is an A because it is derived from A");
if (a is B)
Console.WriteLine("This won’t display -- a not derived from B");
if (b is B) Console.WriteLine("b is a B");
if (a is object) Console.WriteLine("a is an object");
}

}

The output is shown here:
a is an A
b is an A because it is derived from A
b is a B
a is an object

Tuesday, June 11, 2013

How Garbage Collector works

using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;

        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system 
     // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);

            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            // Determine the best available approximation of the number  
     // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of generation 0 only.
            GC.Collect(0);

Thursday, May 9, 2013

C# -How to use regular expression


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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating arraylist
            ArrayList arrlist = new ArrayList();
            //
            // String containing numbers.
            //
            Console.WriteLine("Enter a Line ");
            string sentence = Console.ReadLine(); //"10 cats, 20 dogs, 40 fish and 1 programmer.";
            //
            // Get all digit sequence as strings.
            //
            string[] digits = Regex.Split(sentence, @"\D+");
            //
            // Now we have each number string.
            //
            foreach (string value in digits)
            {
                //
                // Parse the value to get the number.
                //
                int number;
               // if (int.TryParse(value, out number))
                {
                    arrlist.Add(value);
                    Console.WriteLine(value);
                }
            }
            Console.WriteLine("Using Array-----");
            foreach (object ob in arrlist)
            {
                Console.WriteLine(ob.ToString());
            }
            Console.ReadLine();


            //**********************************************
            // See if we can parse the 'text' string. If we can't, TryParse
            // will return false. Note the "out" keyword in TryParse.
            //
            string text1 = "x";
            int num1;
            bool res = int.TryParse(text1, out num1);
            if (res == false)
            {
                // String is not a number.
            }

            //
            // Use int.TryParse on a valid numeric string.
            //
            string text2 = "10000";
            int num2;
            if (int.TryParse(text2, out num2))
            {
                // It was assigned.
            }

            //
            // Display both results.
            //
            Console.WriteLine(num1);
            Console.WriteLine(num2);
            Console.ReadLine();
            Console.WriteLine("End of program");


        }
    }
}

SQL-Difference between ROW_NUMBER, RANK and DENSE_RANK




Difference between ROW_NUMBER, RANK and DENSE_RANK

What is the Difference between ROW_NUMBER, RANK and DENSE_RANK? Which one to use?
This is very common question in the minds of SQL newbie's.
Lets take 1 simple example to understand the difference between 3.

First lets create some sample data :




-- create table
CREATE TABLE Salaries
(
Names VARCHAR(1),
SalarY INT
)
GO
-- insert data
INSERT INTO Salaries SELECT
'A',5000 UNION ALL SELECT
'B',5000 UNION ALL SELECT
'C',3000 UNION ALL SELECT
'D',4000 UNION ALL SELECT
'E',6000 UNION ALL SELECT
'F',10000
GO
-- Test the data
SELECT Names, Salary
FROM Salaries

Now lets query the table to get the salaries of all employees with their salary in descending order.
For that I'll write a query like this :




SELECT names
        , salary
        ,row_number () OVER (ORDER BY salary DESC) as ROW_NUMBER
        ,rank () OVER (ORDER BY salary DESC) as RANK
        ,dense_rank () OVER (ORDER BY salary DESC) as DENSE_RANK
FROM salaries



>>Output
NAMES
SALARY
ROW_NUMBER
RANK
DENSE_RANK
F
10000
1
1
1
E
6000
2
2
2
A
5000
3
3
3
B
5000
4
3
3
D
4000
5
5
4
C
3000
6
6
5
Interesting Names in the result are employee A, B and D. 
Row_number assign different number to them.
Rank and Dense_rank both assign same rank to A and B.
But interesting thing is what RANK and DENSE_RANK assign to next row?
Rank assign 5 to the next row, while dense_rank assign 4.
The numbers returned by the DENSE_RANK function do not have gaps and always have consecutive ranks.  The RANK function does not always return consecutive integers.  The ORDER BY clause determines the sequence in which the rows are assigned their unique ROW_NUMBER within a specified partition.

So question is which one to use?
Its all depends on your requirement and business rule you are following.
1. Row_number to be used only when you just want to have serial number on result set. It is not as intelligent as RANK and DENSE_RANK.
2. Choice between RANK and DENSE_RANK depends on business rule you are following. Rank leaves the gaps between number when it sees common values in 2 or more rows. DENSE_RANK don't leave any gaps between ranks.
So while assigning the next rank to the row RANK will consider the total count of rows before that row and DESNE_RANK will just give next rank according to the value.
So If you are selecting employee’s rank according to their salaries you should be using DENSE_RANK and if you are ranking students according to there marks you should be using RANK(Though it is not mandatory, depends on your requirement.)

SQL-Insert Data into chunks in database


//Insert Data into chunks in database

declare @minID int
declare @maxID int
declare @batchStart int
declare @batchSize int

set @batchSize = 25000

select @minID = min(id), @maxID = max(id)
from sourceTable

set @batchStart = @minID

while @batchStart <= @maxID begin
insert into DestinationTable(....)
select ...
from sourceTable s
where s.id between @batchStart and @batchStart + @batchSize - 1

set @batchStart = @batchStart + @batchSize
end

SQL-Important Sql table Queries


1.how to check sql server version
Ans-select @@version

---------------------------------------
2.how to check how many tables
Ans-select * from sys.tables

-----------------------------------------
3.how to show complete structure of table
Ans-EXEC sp_help TableName;

-----------------------------------------
4.How to show all temp tables in sql server
Ans-select * from tempdb.sys.objects

---------------------------------------------
5.How to list all indexes
SELECT T.Name, I.name FROM sys.indexes I INNER JOIN Sys.tables t ON t.object_id = I.Object_ID WHERE index_id >= 1 -- skip heep

-------------------------------------------
6.How to list all indexes with all details
select * from sys.indexes

-------------------------------------------
7.How to get first and last date of month
DECLARE @Month int
DECLARE @Year int

set @Month = 2
set @Year = 2005

select DATEADD(month,@Month-1,DATEADD(year,@Year-1900,0)) /*First*/

select DATEADD(day,-1,DATEADD(month,@Month,DATEADD(year,@Year-1900,0))) /*Last*/


-----------------------------------------
8.Display every Nth row

Query:
SELECT id
FROM employees
GROUP BY id
HAVING MOD(id, N) = 0;

-------------------
9.Age in years

DECLARE @dob  datetime
SET @dob='1992-01-09 00:00:00'

SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal
    ,CONVERT(int,ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound
    ,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc

----------------------------------------

10.Date diffrence

DATEDIFF(datepart,startdate,enddate)

-----------------------------------------
11.Update Table using Join

UPDATE employee e LEFT JOIN employee_salary s ON e.id=s.employee_id
SET s.salary='50000'
where e.first_name='Admin'

SQL-Complex queries in SQL


  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

AngularJS Basics - Part 1

                                                                  AngularJS What is AngularJS ·          Framework by googl...