Wednesday, 1 July 2015

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#

DataReader

DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:

Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database

DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}


DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.

DataTable 
DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.
protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();
}


























Monday, 29 June 2015

Create WCF service and use it to retreive data from Dynamics CRM

Create WCF service and use it to retreive data from Dynamics CRM



1. Open Visual Studio and Select WCF service application.




2. add following code to the IService1.cs file 


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

namespace CrmWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        SampleTestEntity[] getAccountDetails();
     }

    [DataContract]
    public class SampleTestEntity
    {
        string new_sample_name;
        string new_gender;
        string new_contactnumber;

        [DataMember]
        public string sample_name
        {
            get { return new_sample_name; }
            set { new_sample_name = value; }
        }

        [DataMember]
        public string gender
        {
            get { return new_gender; }
            set { new_gender = value; }
        }

        [DataMember]
        public string contactnumber
        {
            get { return new_contactnumber; }
            set { new_contactnumber = value; }
        }
    }

}

3. Now open Service1.svc.cs and add following code
(Add necessary refernces from CRM sdk for accessing your CRM instance(eg., Microsoft.Crm.Sdk, etc.))::


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk.Query;

namespace CrmWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {


        OrganizationService _orgservice = new OrganizationService(CrmConnection.Parse("Url=https://YourSolution.crm5.dynamics.com; Username=userName@YourSolution.onmicrosoft.com; Password=Password.;"));



        public SampleTestEntity[] getAccountDetails()
        {
            string fetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='new_SampleTestEntity'>
                                    <attribute name='new_sample_name' />
                                    <attribute name='new_gender' />
                                    <attribute name='new_contactnumber' />
                                    <attribute name='new_birthdate' />
                                    <attribute name='new_address' />
                                    <attribute name='new_SampleTestEntityid'/>    
                                    <order attribute='fullname' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='new_sample_name' operator='eq' value='pallavi' />
                                      </condition>
                                    </filter>
                                  </entity>
                                </fetch>";

            EntityCollection result = _orgservice.RetrieveMultiple(new FetchExpression(fetchXML));
            int i = 0;
            int Rcount = result.Entities.Count;
            SampleTestEntity[] arrAccount = new SampleTestEntity[Rcount];
            foreach (var c in result.Entities)
            {
                arrAccount[i] = new SampleTestEntity();

                arrAccount[i].sample_name = c.Attributes["new_sample_name"].ToString();

                if (c.Attributes.Contains("new_gender"))
                    arrAccount[i].contactnumber = c.Attributes["new_gender"].ToString();

                i++;
            }
            return arrAccount;
        }

        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}

        //public CompositeType GetDataUsingDataContract(CompositeType composite)
        //{
        //    if (composite == null)
        //    {
        //        throw new ArgumentNullException("composite");
        //    }
        //    if (composite.BoolValue)
        //    {
        //        composite.StringValue += "Suffix";
        //    }
        //    return composite;
        //}
        
    }
}


Consume your WCF Service

5. Now your WCF Service is ready to use. For consuming this service, Open Visual Studio and Create new Web application



6. Put a gridview in your design window(.aspx page)

7. Goto References and Add reference of your crm Service dll. Goto Browse in Add Reference and select the path of your crm srvice dll in bin folder.

8. Goto to the code window and add namespace and add below code for binding data to gridview.::



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


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Service1Client obj = new Service1Client();
        SampleTestEntity acc = new SampleTestEntity();
        GridView1.DataSource = obj.getAccountDetails();
        GridView1.DataBind();
    }
}



































Tuesday, 23 June 2015

How to Create a Simple Web Service and Use it in ASP.Net


How to create a Web Service

Step 1
Go to Visual Studio then click on "File" -> "Website" -> "ASP.NET empty website template".
Then provide the website name (for example: WebServiceSample).


Step 2: Add a Web Service File

Go to Solution Explorer, then select the solution then click on "Add new item".

Choose the Web Service template.

Enter the name (for example: Calculation.cs) then click on "Add".


 



This will create the following two files:
  1. Calculation.asmx (the service file)
  2. Calculation.cs (the code file for the service; it will be in the "App_code" folder)

Open the file Calculation.cs and write the following code:

 using System;
 using
 System.Collections.Generic;
 using
 System.Linq;
 using
 System.Web;
 using
 System.Web.Services;
 ///
 <summary>
 ///
 used for Calculationcalculation
 ///
 </summary>
 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 // [System.Web.Script.Services.ScriptService]

 public
 class Calculation: System.Web.Services.WebService
 {
     public
Calculation()   {
         //Uncomment the following line if using designed components
         //InitializeComponent();
     }
     [WebMethod]
     public int Add(int x, int y)
     {
         return x + y;
     }
     [WebMethod]
     public int Sub(int x, int y)
     {
         return x - y;
     }
     [WebMethod]
     public int Mul(int x, int y)
     {
         return x * y;
     }
     [WebMethod]
     public int Div(int x, int y)
     {
         return x / y;
     }
 }

Step 3

To see whether the service is running correctly go to the Solution Explorer then open "Calculation.asmx" and run your application.

Now you will find all the method names in the browser.



To determine whether the functions are working, click on one of the functions (for example: "Add").

Now you will see two TextBoxes for checking. Enter the value for x and y and click on the "Invoke" button.

Now you will see the result in an open standard form (XML).


Now your service is ready for use.

Step 4: Creating the client application

Now create a website and design your form as in the following screen.




Source code  

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                        <asp:Label ID="Label1" runat="server" Text="Enter the First number "></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </td>
                </tr>

                <tr>
                    <td>
                        <asp:Label ID="Label2" runat="server" Text="Enter the First number"></asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    </td>
                    <td>
                        <asp:Label ID="Label3" runat="server" ></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="Add" OnClick="Button1_Click" />
                    </td>
                    
                    <td>
                        <asp:Button ID="Button2" runat="server" Text="Sub" OnClick="Button2_Click" />
                    </td>
                    
                    <td>
                        <asp:Button ID="Button3" runat="server" Text="Div" OnClick="Button3_Click" />
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </td>
                    
                    <td>
                        <asp:Button ID="Button4" runat="server" Text="Mul" OnClick="Button4_Click" />
                    </td>
                </tr>

            </table>


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

Step 5: Add a web reference to the Website

Go to Solution Explorer then select the solution then click on "AddWeb Reference" then within the URL type the service reference path.

(For example: http://localhost:65312/WebServiceSample/Airthmatic.asmx) then click on the "Go" button.

Now you will see your service methods. Change the web reference name from "localhost" to any other name as you like (for example: WebAirthmatic).

Click on the "Add Reference" button. It will create a Proxy at the client side.




Now go to the cs code and add a reference for the Service.

Example:  using WebAirthmatic;


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

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

    CalculationSoapClient obj = new CalculationSoapClient();
    int a, b, c;

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        a = Convert.ToInt32(TextBox1.Text);
        b = Convert.ToInt32(TextBox2.Text);

        c = obj.Add(a, b);
        Label3.Text = c.ToString();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        a = Convert.ToInt32(TextBox1.Text);
        b = Convert.ToInt32(TextBox2.Text);

        c = obj.Sub(a, b);
        Label3.Text = c.ToString();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        a = Convert.ToInt32(TextBox1.Text);
        b = Convert.ToInt32(TextBox2.Text);

        c = obj.Div(a, b);
        Label3.Text = c.ToString();
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        a = Convert.ToInt32(TextBox1.Text);
        b = Convert.ToInt32(TextBox2.Text);

        c = obj.Mul(a, b);
        Label3.Text = c.ToString();
    }
}