I wanna share…

Archive for the ‘C#.Net’ Category

Creating and consuming the Webservice

Creating  and consuming the Web service by using a Web Application

Download Link: Click Here

 These are the definitions of Webservice.

Definition 1:

A Web service is a software application, accessible on the Web through an URL that is accessed by clients using XML-based protocols, such as Simple Object Access Protocol (SOAP) sent over accepted Internet protocols, such as HTTP. Clients access a Web service application through its interfaces and bindings, which are defined using XML artifacts, such as a Web Service Definition Language (WSDL) file.

Definition 2:

Web services are typically application programming interfaces (API) or web APIs that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services.

 Definition 3:

A web service can be defined as a service available through the World Wide Web (Internet or Intranet) that makes use of the XML as message system and is not tied to any programming language, operating systems (OS).

Some people having a doubt about where this webservice concept will come into picture.

I will tell the best example. You want to buy a Kingfisher flight ticket in online. You can book it from Kingfisher website. Likewise you can book that ticket through makemytrip.com website also. Here makemytrip.com is using the webservice of Kingfisher.

Now I will explain about my Webservice.

Here I am explaining about Webservice concept (How to create a Webservice and how to consume that webservice using a web application) in an understandable way.

These are the steps to create a Webservice and publish it.

1.      Create a New website and create a virtual directory in IIS.

2.      Add asmx file.

3.      In .cs file write your functionality.

4.      Run the Asmx file.

These are the steps to consume a Webservice

1.      Create a New website and create a virtual directory in IIS

2.      Create an aspx file and add web reference.

3.      Invoke the properties of the webservice.

4.      Run the application.

I created a new website called webparts and create a virtual directory in IIS with that same name.

Now I created the asmx application. When we create the file .cs file also create with .asmx file. .cs will store in App_Code folder. In .cs file I wrote the web service functionality Addition, Subtract, Multiplication and Hello methods.

This is code of App_Code/ FirstWebService.cs file

[WebService(Namespace = “http://localhost/webparts”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class FirstWebService : System.Web.Services.WebService

{

public FirstWebService () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod]

public int Add(int a, int b)

{

return a + b;

}

[WebMethod]

public int Sub(int a, int b)

{

return a – b;

}

[WebMethod]

public int Multiplication(int a, int b)

{

return a * b;

}

[WebMethod]

public String Hello()

{

return “Welcome to the Web Service”;

}

}

Now Run the FirstWebService.asmx file.

Click on Service Description.


Click on methods like Add etc…


Finally in Visual Studio command prompt run these below commands.

WSDL http://local/webparts/FirstWebService.asmx?WSDL

csc /t: library FirstWebService.cs

When we run these commands, at the next second FirstWebService.cs and FirstWebService.dll files will create like this in your C or D drive.


Now I create the new website. In this website I created an aspx file.

Add the Web Reference like this.

1. Right click on the website and click on add Web Reference. This screen will comes.


Click on the Webservices in the local machine. It will show all the webservices which are exists in your system. Click on FirstWebservice.asmx and click Add Reference.

Web Reference is added to your site. (disco, disomap, wsdl files will create under App_Referances folder)

2. Add FirstWebService.cs and FirstWebService.dll to bin folder (which are created in C or D drive).

Webservconsumer.aspx file code behind code is:

Imports System

Imports System.Data

Imports System.Configuration

Imports System.Collections

Imports System.Web

Imports System.Web.Security

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.WebControls.WebParts

Imports System.Web.UI.HtmlControls

Imports System.Web.Services

Partial Class webservconsumer

Inherits System.Web.UI.Page

Public Sub runSrviceAdd_Click(ByVal sender As [Object], ByVal e As EventArgs)

Dim mySvc As New FirstWebService()

Label1.Text = mySvc.Hello()

Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString()

End Sub

Protected Sub runSrviceSub_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles runSrviceSub.Click

Dim mysvcsub As New FirstWebService()

Label1.Text = mysvcsub.Hello()

Label2.Text = mysvcsub.Sub(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString()

End Sub

Protected Sub runSrviceMulti_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles runSrviceMulti.Click

Dim mysvcMulti As New FirstWebService()

Label1.Text = mysvcMulti.Hello()

Label2.Text = mysvcMulti.Multiplication(Int32.Parse(txtNum1.Text), Int32.Parse(txtNum2.Text)).ToString()

End Sub

End Class

Run the Webservconsumer.aspx file. Output  screen will be like this.


Using MySql with C#.Net and GridView Paging

Using MySql with C#.Net and GridView Paging

DownLoad Link: Click Here

 In this Article I’m explaining about how to add the data to the database and how to show the data in Gridview in C#.Net with MySql with Paging. This is very useful article to who are using MySql Database with C#.Net first time.

Steps:

  1. Create the Web Application like “Gridviewincsharpmysql.aspx”.
  2. Copy the MySql.Data.dll from MySql website and Paste into the Bin Folder of your application.
  3. Create a table Emp_master.

Aspx page having three tables tblone, tbladd, and tblgv.

.aspx Code is available in Downloads Zip.

 In page_Load Event I checked the value of Seesion object with null value. If right i assigned  the value ‘1’ to the session object.

After that I checked postback method, if not postback till that movement I called the Select Method. In the Select method has two methods First(0), gvwithpaging(gview, qry())

 First(0) is to show the tables tblone, tbladd, and tblgv depends on the method parameter value.

gvwithpaging(gview, qry())is to bind the values to the gridview. In the gvwithpaging method having DatasetBinding(out ds, some).

At the time of Databinding gview_rowDataBound event is fired. When changing the page  gview_PageIndexChanging is fired.

When we try to refresh the page last entered data will again entered into the database. To overcome that we are changing the session object value from stage to stage. Finally PreRender Event is fired.

 In web.config file I added my applications settings like this:

You have to change the values where XXXXX are shown, with your Database connection values.

<appSettings>

<add key=”Mysql” value=”Data Source=XXXXX;User ID=XXXXXX; password=XXXXX; Database=XXXXX“></add>

</appSettings>

This is the Code-behind page code:

public partial class Gridviewincsharpmysql : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (Session[“RefreshCtr”] == null)

{

Session[“RefreshCtr”] = 1;

lblRefresh.Text = Session[“RefreshCtr”].ToString();

}

if (!IsPostBack)

{

            Select();

}

}

private void Page_PreRender(object sender, EventArgs e)

{

lblRefresh.Text = Session[“RefreshCtr”].ToString();

}

protected void Addnew(object sender, EventArgs e)

{

        first(1);

        Clearall();

}

protected void Button1_click(object sender, EventArgs e)

{

if (lblRefresh.Text == Session[“RefreshCtr”].ToString())

{

Session[“RefreshCtr”] = Session[“RefreshCtr”].ToString() + 1;

            ConnectionString();

            Select();

}

            first(0);

}

public void Select()

{

first(0);

        gvwithpaging(gview, qry());

}

private string qry()

{

string myquery = “”;

myquery = “SELECT Emp_Id, Emp_FName,  Emp_LName, Emp_Gender, Emp_P_City,      Emp_P_Country, Emp_P_PIN, Emp_Phone, Emp_Bank_Name, PAN_NO FROM                 test.emp_master”;

return myquery;

}

public void gvwithpaging(GridView gv, string some)

{

DataSet ds = null;

if (gv.PageIndex == 0)

{

int myindex = 0;

gv.PageIndex = myindex;

}

DatasetBinding(out ds, some);       

gv.DataSource = ds;

gv.DataBind();

}

public void DatasetBinding(out DataSet dset, string myqry)

{

MySqlConnection myconn = new                                                  MySqlConnection(ConfigurationManager.AppSettings[“Mysql”]);

myconn.Open();

MySqlCommand mycomm = new MySqlCommand();

mycomm.Connection = myconn;

mycomm.CommandType = CommandType.Text;

mycomm.CommandText = myqry;

MySqlDataAdapter myadapter = new MySqlDataAdapter(mycomm);

DataSet dts = new DataSet();

myadapter.Fill(dts);

dset = dts;

mycomm.Dispose();

myconn.Close();

}

public void gview_RowDatabound(object sender, GridViewRowEventArgs e)

{

int page = gview.PageIndex + 1;

int count = gview.PageCount;

}

public void first(int a)

{

if (a == 0)

{

tblgv.Visible = true;

tbladd.Visible = true;

tblone.Visible = false;

}

if (a == 1)

{

tblgv.Visible = false;

tbladd.Visible = false;

tblone.Visible = true;

}

}

protected void gview_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

gview.PageIndex = e.NewPageIndex;

gvwithpaging(gview, qry());

int pagenumber=gview.PageIndex+1;

Response.Write(“You are at page number ” +pagenumber);

}

public void ConnectionString()

{

int Emp_Id = Convert.ToInt32(TextBox1.Text);

string Emp_FName = TextBox4.Text;

string Emp_LName = TextBox5.Text;

string Emp_Gender = TextBox6.Text;

string Emp_P_City = TextBox7.Text;

string Emp_P_Country = TextBox8.Text;

string Emp_P_PIN = TextBox9.Text;

string Emp_Phone = TextBox10.Text;

string Emp_Bank_Name = TextBox11.Text;

string PAN_NO = TextBox12.Text;

MySqlConnection myconn = new MySqlConnection(ConfigurationManager.            AppSettings[“Mysql”]);

myconn.Open();

MySqlCommand mycomm = new MySqlCommand();

mycomm.Connection = myconn;

mycomm.CommandType = CommandType.Text;

string myqry = “insert into test.emp_master(Emp_Id, Emp_FName,               Emp_LName, Emp_Gender, Emp_P_City, Emp_P_Country,     Emp_P_PIN,                Emp_Phone, Emp_Bank_Name, PAN_NO)values(‘” + Emp_Id + “‘,'” + Emp_FName        + “‘,'” + Emp_LName + “‘,'” + Emp_Gender + “‘,'” + Emp_P_City + “‘,'” +       Emp_P_Country + “‘,'” + Emp_P_PIN + “‘,'” + Emp_Phone + “‘,'” +           Emp_Bank_Name + “‘,'” + PAN_NO + “‘)”;

mycomm.CommandText = myqry;

MySqlDataAdapter myadapter = new MySqlDataAdapter(mycomm);

DataSet ds = new DataSet();

myadapter.Fill(ds);

mycomm.Dispose();

myconn.Close();

}

private void Clearall()

{

TextBox1.Text = “”;

TextBox4.Text = “”;

TextBox5.Text = “”;

TextBox6.Text = “”;

TextBox7.Text = “”;

TextBox8.Text = “”;

TextBox9.Text = “”;

TextBox10.Text = “”;

TextBox11.Text = “”;

TextBox12.Text = “”;

}

}

When we run this we can see this.

Click AddNew Button

This table will appear,

You may face these Errors are:

1. Overload method Gridview_pageiindexchanging matches delegate.

Sol:

Create this event from design page. If we write the onclick property from source page of aspx file Pageindexchanging will not fired.