Friday, 23 December 2016

WCF SOAP AND REST


WCF
1. It is also based on SOAP and return data in XML form.
2. It is the evolution of the web service(ASMX) and support various protocols like 3. TCP, HTTP, HTTPS, Named Pipes, MSMQ.
4. The main issue with WCF is, its tedious and extensive configuration.
5. It is not open source but can be consumed by any client that understands xml.
6. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest
1. To use WCF as WCF Rest service you have to enable webHttpBindings.
2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
5. It support XML, JSON and ATOM data format.

Where to use:-

1. In my opinion, SOAP services with SOA architecture are well suited in enterprise applications. SOA architecture includes several key factors like service versioning, scalability, deployment and maintaining of services.
2. REST services are best suited in Internet-facing applications, which can take advantage of HTTP caching and other features.

// SOME OF THE MORE FEATURES ARE GIVEN BELOW



iffernce between normal WCF service and RESTful WCF Service
There is no more difference between WCF service and REST service only main difference is that How Client accesses our Service.
Normal WCF service runs on the SOAP format but when we create REST service then client can access your service in different architecture style like JSON

REST uses4 HTTP methods to insert/delete/update/retrieve information which is below:
GET - Retrive a specific representation of a resource
PUT - Creates or updates a resource with the supplied representation
DELETE - Deletes the specified resource
POST - Submits data to be processed by the identified resource

Where to Use RESTful WCF Service There are some scenario’s where we can use RESTful service like
1) Less Overhead because there is no use of SOAP object
2) Testing is very easy
3) Standardization is very nice

Creation of RESTful WCF Service Step1.
Create a new WCF project in VS 2008/20010

Step 2:
Delete a Service Model node from Web.config

Step 3.
Build the Solution then Right click on the svc file and Click on View Markup button
And add following code to the markup

Factory="System.ServiceModel.Activation.WebServiceHostFactory"

Step 4
Add following references to the WCF Service Application project, if you are using VS2010
Microsoft.Http.dll
Microsoft.Http.Extension.dll
System.ServiceModel.Web.dll


Step 5

  [ServiceContract]
    public interface IService1
    {

        [OperationContract(Name = " AddTwoNumber ")]
        [WebInvoke(UriTemplate = "/", Method = "POST")]
         int AddTwoNumber(int i, int j);

       

        [OperationContract(Name = " SubTwoNumber")]
        [WebGet(UriTemplate = "/")]
        int SubTwoNumber(int i, int j);

      
    }

Add your code in your service like here I have created 2 methods like AddTwonumber which takes two parameter I and j
In the above code we use
WebInvoke :- means invoke web method

Webinvoke takes Two parameters like
1. Method Type there are 4 types of method
a.Post C.Invoke
b.Get d.Delete
2. UriTemplate = "/ADD” tells what would be URI for this particular method


Like this we can create RESTful service.

More differences:
Web Service is an abstract term encompassing a large variety of data providers for distributed systems. Perhaps you are referring to ASMX web services, which can still be found in the wild but aren't really widely used in new development these days.

WCF Service is Microsoft's implementation of SOAP. There are others implementations or you could roll your own (not recommended).

SOAP is a kind of stateful, session-based, message-based web service. It's good if your service is designed as a set of complex actions.

REST is a stateless, sessionless, resource-based web service. It's good if your service is designed to access data and perform simple CRUD operations on it. SOAP and REST are mutually exclusive. A service cannot be both. There are ways to manipulate vanilla WCF to make is RESTful but these techniques are becoming deprecated. If you want to implement a RESTful web service there are two main choices in the Microsoft world: WCF Data Services and ASP.NET Web API.



property

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class property
    {
    }
    class Student
   {
      private string code = "N.A";
      private string name = "not known";
      private int age = 0;
     
      // Declare a Code property of type string:
      public string Code
      {
         get
         {
            return code;
         }
         set
         {
            code = value;
         }
      }
     
      // Declare a Name property of type string:
      public string Name
      {
         get
         {
            return name;
         }
         set
         {
            name = value;
         }
      }
     
      // Declare a Age property of type int:
      public int Age
      {
         get
         {
            return age;
         }
         set
         {
            age = value;
         }
      }
      public override string ToString()
      {
         return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
      }
   }
  
   class ExampleDemo
   {
      public static void MainProperty()
      {
     
         // Create a new Student object:
         Student s = new Student();
        
         // Setting code, name and the age of the student
         s.Code = "001";
         s.Name = "Zara";
         s.Age = 9;
         Console.WriteLine("Student Info: {0}", s);
        
         //let us increase age
         s.Age += 1;
         Console.WriteLine("Student Info: {0}", s);
         Console.ReadKey();
      }
   }
}

private constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class privateConstructor
    {
    //{
    //    Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.
        public static string st = string.Empty;
        public  string st1 = string.Empty;
        public string stw()
        {
            return "sttest";
        }
        public privateConstructor(string st1, string st2)
        {
            Console.WriteLine("Hi"+st1+"and hi"+st1);

        }
        private privateConstructor()
        {
            Console.WriteLine("This is the private cinstructor that can not instiated0");

        }

    }
    class program
    {
        public static void Main5(string[] ar)
        {
            privateConstructor objPrivatecontructor = new privateConstructor("hi p1","p2");
            objPrivatecontructor.st1 = "test";
        }
    }

}

Polymorphism

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class Polymorphism
    {

    }
    ////compie time polymorphis start here
    //public class Class1
    //{
    //    public void NumbersAdd(int a, int b)
    //    {
    //        Console.WriteLine(a + b);
    //    }
    //    public void NumbersAdd(int a, int b, int c)
    //    {
    //        Console.WriteLine(a + b + c);
    //    }
    //}
    //public class Compiletimepolymorphis
    //{
    //    public static void main(string[] args)
    //    {
    //        Class1 objClass1 = new Class1();
    //        objClass1.NumbersAdd(12,5);
    //        objClass1.NumbersAdd(12, 12, 13);
    //    }
    //}

    ///Compile time poly morphis end here
    ///
    ///Run time poly morphis star here
    ///
    public class Bclass
    {
        public virtual void Sample1()
        {
            Console.WriteLine("Base Class");
        }
    }
    // Derived Class
    public class DClass : Bclass
    {
        public override void Sample1()
        {
            Console.WriteLine("Derived Class");
        }
    }
    // Using base and derived class
    class ProgramPloy
    {
        static void MainPlohy(string[] args)
        {
            // calling the overriden method
            DClass objDc = new DClass();
            objDc.Sample1();
            // calling the base class method
            Bclass objBc = new DClass();
            objBc.Sample1();
          
            Console.ReadLine();
        }
    }
}

partial class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class Partialclass
    {
        public partial class student
        {
            public void GetStudentDetails()
            {
                //developer is working on student details module
            }
            //some other function for same modules..
        }

        public partial class student
        {
            public void GetStudentResults()
            {
                //developer is working on student results module
            }

            //some other function for same modules..
        }
    }
}

InterfaceTest

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class InterfaceTest
    {
        interface myclass
        {
            string Animal();
            string Animal1();
  
            // {
            //     string stranimaltext ="Dog has four leg";
            //     return stranimaltext;

            // }
            //public static void Refrencefunction()
            //{
            //}

        }
        class Aceeessabstract : myclass
        {
            public string Animal()
            {
                string stranimaltext = "Cow has four leg";
                return stranimaltext;

            }
            public string Animal1()
            {
                string stranimaltext = "Buffalow1 has four leg";
                return stranimaltext;

            }

        }


        static void Main2(string[] args)
        {
            Aceeessabstract objAb = new Aceeessabstract();
            Console.WriteLine(objAb.Animal());
            Console.WriteLine(objAb.Animal1());
            Console.Read();
        }
    }
}

Delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class Delegate
    {
    }
    public delegate int NumberChanger(int w);
    namespace DelegateAppl
    {
        class TestDelegate
        {
            static int num = 10;
            public static int AddNum(int p)
            {
                num += p;
                return num;
            }

            public static int MultNum(int q)
            {
                num *= q;
                return num;
            }
            public static int getNum()
            {
                return num;
            }

            static void MainDelegate(string[] args)
            {
                //create delegate instances
                NumberChanger nc1 = new NumberChanger(AddNum);
                NumberChanger nc2 = new NumberChanger(MultNum);

                nc1(25);
                nc2(35);
                Console.WriteLine("Addition of two number is {0}",getNum());
                Console.ReadLine();
            }
        }
    }
}

Constructor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    class Constructor1
    {
        public Constructor1()
        {
            Console.WriteLine("constructr that have the no parameter");

        }
        //public Constructor1(string st)
        //{
        //    Console.WriteLine("constructr that have the  parameter {0}",st);

        //}
        public Constructor1(string st1, string st2)
        {
            Console.WriteLine("constructr that have the  parameter {0}&{1}", st1,st2);

        }
    
    }
     class ChildClass : Constructor1
    {
        public ChildClass()
            : base()
        {
            Console.WriteLine("Chuild  Class constructor with n parameter ");
        }
        //public ChildClass(string stchild1)
        //    : base(stchild1)
        //{
        //    Console.WriteLine("Child class cnstructr that have one string parameter{0}", stchild1);

        //}
        public ChildClass(string stchild1,string stChild2)
            : base(stchild1,stChild2)
        {
            Console.WriteLine("Child class cnstructr that have one string parameter{0} & {1}", stchild1, stChild2);

        }
    }
    public class Program1
    {
        public static void Maincons(string[] args)
        {
            Console.WriteLine("--------------------------Cnstructor Chaining strted here---------------------------------------");
            ChildClass objConstructor = new ChildClass ();
            ChildClass objCh2 = new ChildClass("Parameter1", "Parameter2");
            Console.ReadLine();
        }
    }
}

ABSTTRACTION

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    public class Bike
    {
        public int mileage = 65;
        public string color = "Black";
        private string formula = "a*b";
        //Its public – so accessible outside class
        public int GetMileage()
        {
            return mileage;
        }

        //Its public – so accessible outside class
        public string GetColor()
        {
            return color;
        }

        //Its private – so not accessible outside class
        private string GetEngineMakeFormula()
        {
            return formula;
        }
    }
    public class hondaBike
    {
        public int mileage = 65;
        public string color = "Black";
        private string formula = "a*b";
        //Its public – so accessible outside class
        public int GetMileage()
        {
            return mileage;
        }

        //Its public – so accessible outside class
        public string GetColor()
        {
            return color;
        }

        //Its private – so not accessible outside class
        private string GetEngineMakeFormula()
        {
            return formula;
        }

        //Its public – so accessible outside class
        public string DisplayMakeFormula()
        {
            //"GetEngineMakeFormula()" is private but accessible and limited to this class only
            return GetEngineMakeFormula();
        }
    }

    public class Programabst
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("------------------------------------Encapsulation started here------------------------------------");
            Bike objBike = new Bike();
            Console.WriteLine("Bike mileage is : " + objBike.GetMileage()); //accessible outside "Bike"
            Console.WriteLine("Bike color is : " + objBike.GetColor()); //accessible outside "Bike"
            //we can't call this method as it is inaccessible outside "Bike"
            //objBike.GetEngineMakeFormula(); //commented because we can't access it


            Console.WriteLine("------------------------------------Encapsulation End here------------------------------------");



            Console.WriteLine("------------------------------------Abstraction Started here------------------------------------");
            hondaBike objhondaBike = new hondaBike();
            Console.WriteLine("Bike mileage is : " + objhondaBike.GetMileage()); //accessible outside "Bike"
            Console.WriteLine("Bike color is : " + objhondaBike.GetColor()); //accessible outside "Bike"
               //we can't call this method as it is inaccessible outside "Bike"
               //objBike.GetEngineMakeFormula(); //commented because we can't access it
            Console.WriteLine("Bike making frmula  is : " + objhondaBike.DisplayMakeFormula()); //accessible outside



            Console.WriteLine("------------------------------------Abstraction End here------------------------------------");
            Console.Read();
        }
    }
}

AbstractInterfaceBoth

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OopsConcept
{
    /// <summary>
    /// An Abstract class doesn't provide full abstraction but an interface does provide full abstraction; i.e. both a declaration and a definition is given in an abstract class but not so in an interface.
//Using Abstract we can not achieve multiple inheritance but using an Interface we can achieve multiple inheritance.
//We can not declare a member field in an Interface.
//We can not use any access modifier i.e. public , private , protected , internal etc. because within an interface by default everything is public.
//An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.
    /*
     * Abstraction:
Abstraction is "To represent the essential feature without representing the back ground details."

Abstraction lets you focus on what the object does instead of how it does it.

Abstraction provides you a generalized view of your classes or object by providing relevant information.

Abstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner.

Real world Example of Abstraction: -
Suppose you have an object Mobile Phone.

Suppose you have 3 mobile phones as following:-

Nokia 1400 (Features:- Calling, SMS)
Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera)
Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)

Abstract information (Necessary and Common Information) for the object "Mobile Phone" is make a call to any number and can send SMS."

so that, for mobile phone object you will have abstract class like following:-

     *
     ///  ENCAPSULATION START HERE
     *
     *
     *
     * Encapsulation:
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.

Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.

Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions.

    class Bag
    {
        book;
        pen;
        ReadBook();
    }


Encapsulation means hiding the internal details of an object, i.e. how an object does something.

Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.

Encapsulation is a technique used to protect the information in an object from the other object.

Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public.
So, when you access the property you can validate the data and set it.
S
    
    
    
     */
    /// </summary>
abstract class M1
   {
        public int add(int a, int b)
        {
            return (a + b);
        }
    }
    class M2 :M1
    {
        //public int mul(int a, int b)
        //{
        //    return a * b;
        //}
    }
    class test
    {
        static void Main56(string[] args)
        {
            M2 ob = new M2();
            int result = ob.add(10, 20);
            Console.WriteLine("the result is {0}", result);
            Console.ReadLine();
        }
    }
}


Sunday, 21 February 2016

nested gridediting in asp.net

code//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class NestedGrid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvDepartments.DataSource = GetData("select top 10 * from Departments");
            gvDepartments.DataBind();
        }
    }

    private static DataTable GetData(string query)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }

    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string DepartmentId = gvDepartments.DataKeys[e.Row.RowIndex].Value.ToString();
            GridView gvEmployees = e.Row.FindControl("gvEmployees") as GridView;
            gvEmployees.DataSource = GetData(string.Format("select top 3 Id,Name,Address,DepartmentId from Employees where DepartmentId='{0}'", DepartmentId));
            gvEmployees.DataBind();
        }
    }

    protected void gvEmployees_OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView gvEmployees = sender as GridView;
        GridViewRow row = gvEmployees.Rows[e.NewEditIndex];
        int DepartmentId = Convert.ToInt32((row.Cells[0].FindControl("lblDepartmentId") as Label).Text);
        gvEmployees.EditIndex = e.NewEditIndex;

        gvEmployees.DataSource = GetData(string.Format("select top 3 Id,Name,Address,DepartmentId from Employees where DepartmentId='{0}'", DepartmentId));
        gvEmployees.DataBind();

    }

    protected void gvEmployees_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gvEmployees = sender as GridView;
        int Id = Convert.ToInt32(gvEmployees.DataKeys[e.RowIndex].Value);
        this.Delete(Id);
        gvEmployees.EditIndex = -1;
        Response.Redirect("CS.aspx");
    }

    private void Delete(int id)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string sqlStatment = "DELETE FROM  Employees WHERE Id = @id";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }

    protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
    {
        GridView gvEmployees = sender as GridView;
        int id = Convert.ToInt32(((Label)gvEmployees.Rows[e.RowIndex].FindControl("lblId")).Text);
        string name = ((TextBox)gvEmployees.Rows[e.RowIndex].FindControl("txtName")).Text;
        string address = ((TextBox)gvEmployees.Rows[e.RowIndex].FindControl("txtAddress")).Text;
        int index = name.IndexOf(",");
        string finalName = name.Substring(index + 1);
        index = address.IndexOf(",");
        string finalAddress = address.Substring(index + 1);
        index = address.IndexOf(",");
        this.Update(id, finalName, finalAddress);
        gvEmployees.EditIndex = -1;
        gvDepartments.DataSource = GetData("select top 10 * from Departments");
        gvDepartments.DataBind();
    }

    private void Update(int id, string name, string address)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string sqlStatment = "UPDATE Employees SET Name = @Name,Address = @Address WHERE Id = @id";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@Id", id);
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Address", address);
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}




//design



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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        .Grid td
        {
            background-color: #A1DCF2;
            color: black;
            font-size: 10pt;
            line-height: 200%;
        }
        .Grid th
        {
            background-color: #3AC0F2;
            color: White;
            font-size: 10pt;
            line-height: 200%;
        }
        .ChildGrid td
        {
            background-color: #eee !important;
            color: black;
            font-size: 10pt;
            line-height: 200%;
        }
        .ChildGrid th
        {
            background-color: #6C6C6C !important;
            color: White;
            font-size: 10pt;
            line-height: 200%;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("[src*=plus]").live("click", function () {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "images/minus.png");
        });
        $("[src*=minus]").live("click", function () {
            $(this).attr("src", "images/plus.png");
            $(this).closest("tr").next().remove();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="gvDepartments" runat="server" AutoGenerateColumns="false" CssClass="Grid"
                DataKeyNames="Dept_Id" OnRowDataBound="OnRowDataBound">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <img alt="" style="cursor: pointer" src="images/plus.png" />
                            <asp:Panel ID="pnlEmployees" runat="server" Style="display: none">
                                <asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" DataKeyNames="Id"
                                    OnRowDeleting="gvEmployees_OnRowDeleting" OnRowUpdating="UpdateCustomer" OnRowEditing="gvEmployees_OnRowEditing"
                                    CssClass="ChildGrid">
                                    <Columns>
                                        <asp:TemplateField HeaderText="DepartmentId" Visible="false">
                                            <ItemTemplate>
                                                <asp:Label ID="lblDepartmentId" Text='<%# Eval("DepartmentId") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField HeaderText="Id">
                                            <ItemTemplate>
                                                <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server"></asp:Label>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Name">
                                            <ItemTemplate>
                                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name")%>'></asp:TextBox>
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Address">
                                            <ItemTemplate>
                                                <asp:Label ID="lblAddress" runat="server" Text='<%# Eval("Address")%>'></asp:Label>
                                            </ItemTemplate>
                                            <EditItemTemplate>
                                                <asp:TextBox ID="txtAddress" runat="server" Text='<%# Bind("Address")%>'></asp:TextBox>
                                            </EditItemTemplate>
                                        </asp:TemplateField>
                                        <asp:ButtonField CommandName="Edit" Text="Edit" />
                                        <asp:ButtonField CommandName="Delete" Text="Delete" />
                                        <asp:ButtonField CommandName="Update" Text="Update" />
                                    </Columns>
                                </asp:GridView>
                            </asp:Panel>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField ItemStyle-Width="150px" DataField="Dept_Id" HeaderText="Dept Id" />
                    <asp:BoundField ItemStyle-Width="150px" DataField="Dept_Name" HeaderText="Dept Name" />
                </Columns>
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>



//dadatabse



create database tempdb1
CREATE TABLE [dbo].[Departments](
    [Dept_Id] [int] IDENTITY(1,1) NOT NULL,
    [Dept_Name] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Departments] PRIMARY KEY CLUSTERED
(
    [Dept_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO



CREATE TABLE [dbo].[Employees](
    [Id] [int] NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Address] [varchar](100) NOT NULL,
    [DepartmentId] [int] NULL,
 CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

nested grid edit

http://www.aspforums.net/Threads/133072/Edit-Update-Delete-in-Nested-Child-GridView-in-ASPNet/

Friday, 19 February 2016

insert data with check exist or not

   if not exists (select AssessmentName from AssessmentDetails where ClientID=43  and ProgramName='Accenture (BPO)' and CourseName='Effective Business Writing' and AssessmentName='test' )
                        BEGIN
                            insert into AssessmentDetails (ClientId,ProgramName,CourseName,AssessmentName,MaximumScore,CreatedBy,Status) values (
                              43,'Accenture (BPO)','Effective Business Writing','test','688',578,'True')
                              select 1 as p
                                end
                              else
                                BEGIN
                                select 0 as p
                                end

Thursday, 18 February 2016

create curser

DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @path = 'C:\BJS\'

SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
       BACKUP DATABASE @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor

Monday, 8 February 2016

returnjson

var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var UserLoginID;
var QuestionTitle;
var QuestionDesc;
var ExamID;
var TagID;
var Examname;
var PageIndex = 1, pageSize = 10, pageCount = 5;
var pages;

$(document).ready(function () {
    $(".pagination").hide();
    GetRecentQues();
    GetAllTags();
    GetExamForSelection();
    getautocompletetag();
    getArtists(PageIndex);
    //$("#fileupload").hide();
    if (getUrlVars()["title"]) {
        document.getElementById("txtTitle").value = getUrlVars()["title"];
    }
    if (getUrlVars()["ques"]) {
        document.getElementById("txtDesc").value = getUrlVars()["ques"];
    }
});

function getArtists(index) {
    $(".pagination").show();
    GetAllQuestion(index);
}

function AddQuesMaster(examId) {
    if (document.getElementById("fileslist")) {
        var questionid = document.getElementById("fileslist").value;
    }
    var UserLoginID = 1;
    ExamID = document.getElementById("txtExams").value;
    QuestionTitle = document.getElementById("txtTitle").value;
    QuestionDesc = document.getElementById("txtDesc").value;
    TagID = document.getElementById("txtTag").value;
 //   console.log(TagID);
    var parms = '{"userId":"' + UserLoginID + '","examId":"' + ExamID + '","questionTitle":"' + QuestionTitle + '","questionDesc":"' + QuestionDesc + '","tagId":"' + TagID + '","questionId":"' + questionid + '"}';
    //console.log(abc);
    Type = "POST";
    Url = questionanswersservicepath + "/AddQuestionMaster";
    Data = parms;
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    // GetInsprofile();
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {
            $("#txtExams").tokenInput("clear");
            $("#txtTag").tokenInput("clear");
            document.getElementById("txtTitle").value = "";
            document.getElementById("txtDesc").value = "";
            alert('Question Submitted');
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}
function InsertQuesMaster(loginId, questionTitle, questionDesc) {
    var UserLoginID = loginId;
    ExamID = 0;
    QuestionTitle = questionTitle;
    QuestionDesc = questionDesc;
    TagID = 0;
    var parms = '{"userId":"' + UserLoginID + '","examId":"' + ExamID + '","questionTitle":"' + QuestionTitle + '","questionDesc":"' + QuestionDesc + '","tagId":"' + TagID + '","questionId":"' + questionid + '"}';

    //var parms = '{"userID":"' + UserLoginID + '","ExamID":"' + ExamID + '","QuestionTitle":"' + QuestionTitle + '","QuestionDesc":"' + QuestionDesc + '","TagID":"' + TagID + '","QuestionID":"' + questionid + '"}';
    //console.log(abc);
    Type = "POST";
    Url = questionanswersservicepath + "/AddQuestionMaster";
    Data = parms;
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    // GetInsprofile();
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {
            alert('Question Submitted');
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}
function GetInsprofile() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
            var dats = eval(msg.SelectInstituteAboutusDetailsResult);
            //  console.log(dats);
            $.each(dats, function (i, dat) {
                //console.log(dat.About);
                document.getElementById('About').innerHTML = dat.About;
                document.getElementById('Value').innerHTML = dat.Value;
                document.getElementById('Mission').innerHTML = dat.Mission;
                document.getElementById('centers').setAttribute("src", dat.ImgCenters);
                document.getElementById('winners').setAttribute("src", dat.ImgWinners);
                document.getElementById('learning').setAttribute("src", dat.ImgLearning);
            });
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}


function GetExam() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
            var dats = eval(msg.GetExamsForSelectResult);
            console.log(dats);
            $("#txtExams").tokenInput(dats, {
                theme: "facebook"
            });
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}

function getautocompletetag() {
    $.ajax({
        type: "POST", //GET or POST or PUT or DELETE verb
        url: questionanswersservicepath + "/GetTagsForSelect", // Location of the service
        data: '{}', //Data sent to server
        contentType: "application/json; charset=utf-8", // content type sent to server
        dataType: "json", //Expected data format from server
        processdata: false, //True or False  
        success: function (msg) {//On Successfull service call
            var dats = eval(msg.GetTagsForSelectResult);
            $("#txtTag").tokenInput(dats, {
                theme: "facebook"
            });
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}

function GetExamForSelection() {
    var Examname = document.getElementById("txtExams").value;
    // alert(Examname);
    var abc = '{"examName":"' + Examname + '"}';
    //console.log(abc);
    Type = "POST";
    Url = questionanswersservicepath + "/GetExamsForSelect";
    Data = abc;
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    GetExam();
}


function GetRecentQues() {
    Type = "POST";
    Data = '{}';
    Url = questionanswersservicepath + "/GetQuestions";
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    GetQues();
}


function GetQues() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
            // console.log(msg);
            var result = eval(msg.GetQuestionsResult);
        //    console.log(result);
            $.each(result, function (i, dat) {
                $('#output').append('<li><a>"' + dat.QuestionTitle + '"</a></li>');
            });
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}


function GetAllQuestion(index) {
    pageIndex = index;
    Type = "POST";
    Data = '{"pageIndex":"' + PageIndex + '","pageSize":"' + pageSize + '"}';
    Url = questionanswersservicepath + "/GetAllQuestions";
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    GetAllQues();
}


function GetAllQues() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
         //   console.log(msg);
            var result1 = eval(msg.GetAllQuestionsResult);
            //            console.log(JSON.stringify(msg));
            //            console.log(JSON.stringify(result1));
            //          
            //            console.log(result1);
            //$.each(result1, function (i, dat) {

            $('#outputall').html('');
            $('#paging').html('');
         
            for (var i = 0; i < result1.length - 1; i++) {
                $('#outputall').append(
                        '<div class="question-box">' +
                            '<div class="qus-user">' +
                                '<img src="' + result1[i].Image + '"></div>' +
                                    '<a href="QuestionAnswerDetails.aspx?quesid=qs-' + result1[i].questionid + '">' + result1[i].questionTitle + '</a></div>' +
                                        '<hr style="margin-bottom: 10px; margin-top: 10px;">');
                pages = result1[i + 1].NoOfPages;
            } if (PageIndex != 1) {
                $('#paging').append('<li><a href="#" onclick="previous();">Prev</a></li>');
            }
            $('#paging').append('<li><a href="#" onclick="pagecall(' + PageIndex + ');">' + PageIndex + '</a></li>');
            //                for (var j = PageIndex; j <= pages; j++) {
            //                  
            //                    $('#paging').append('<li><a href="#" onclick="pagecall(' + j + ');">' + j + '</a></li>');
            //                }
            $('#paging').append('<li><a> of </a></li>');
            $('#paging').append('<li><a>' + pages + '</a></li>');
            if (PageIndex != pages) {
                $('#paging').append('<li><a href="#" onclick="next();">Next</a></li>');
            }
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}

function previous() {
    if (PageIndex != 1) {
        PageIndex = PageIndex - 1;
    }
    GetAllQuestion(PageIndex);
}

function pagecall(index) {
    PageIndex = index;
    GetAllQuestion(index);
}

function next() {
    PageIndex = PageIndex + 1;
    //    if (pageSize = (pageIndex - 5)) {
    //        pageCount = pageIndex - 5;
    //    }
    GetAllQuestion(PageIndex);
}

function GetAllTags() {

    Type = "POST";
    Data = '{}';
    Url = questionanswersservicepath + "/GetTags";
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = false;
    GetTags();
}

function GetTags() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
         //   console.log(msg);
            var resultTag = eval(msg.GetTagsResult);

            $.each(resultTag, function (i, dat) {
                $('#outputTag').append('<li><a href="#">' + dat.Tag_Name + '</a></li>'
                );

            });
        },
        error: function ()
        { console.log('there is some error'); } // When Service call fails
    });
}

function attachfile() {
    $("#fileupload").show();
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

Saturday, 9 January 2016

disposal and finalyuse

Finalize:

1. Finalize() belongs to the Object class.
2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program
3. It is slower method and not suitable for instant disposing of the objects.
4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory.
5. Example:

class employee
{
//This is the destructor of emp class
~employee()
{

}
//This destructor is implicitly compiled to the Finalize method.
}

Dispose:

1. Dispose() belongs to the IDisposable interface
2. We have to manually write the code to implement it(User Code)
ex: if we have emp class we have to inherit it from the IDisposable interface
and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method.
3. Faster method for instant disposal of the objects.
4. It is deterministic function as Dispose() method is explicitly called by the User Code. 
5. Example:

user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method.

try
{

string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
sqlcon.Open(); // here connection is open


// some code here which will be execute
}
catch
{
// code will be execute when error occurred in try block
}
finally
{
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // detsroy the connection object
}