Click here to Skip to main content
12,448,720 members (52,905 online)
Click here to Skip to main content
Add your own
alternative version

Stats

662.7K views
8.9K downloads
131 bookmarked
Posted

Understanding the Basics of Web Service in ASP.NET

, 10 Jun 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Introduction

This article aims at understanding the need for a web service, the benefits of having a web service and how we can create a basic web service and consume it.

Background

Connectivity between applications is very important. Connectivity in any case is very important for that matter but it specially is very important between applications. Connecting web application used to be a big challenge before the advent of technologies like SOAP (Simple Object Access Protocol). The reason it was so difficult was, there were so many technologies people were working in. The applications were hosted on different types of servers, etc. But these things should not be a barrier to facilitate the communication between applications. The only requirement was to have some standards to follow and standard ways of doing things so that the applications become capable of communicating with other applications irrespective of the technologies used.

SOAP and Web Services

SOAP and XML created the solution for the problem that developers were facing before. SOAP is a standard XML based protocol that communicated over HTTP. We can think of SOAP as message format for sending messaged between applications using XML. It is independent of technology, platform and is extensible too.

We have SOAP and XML to give us connectivity between applications. Does it mean that I have to write XML and SOAP specific things myself to facilitate this communications? I could do that but that will be very time consuming and sometimes error prone too.

Where does Web Services come in picture? Well, Web services is the mechanism that ASP.NET framework provides to make it easy for us to write code to facilitate connectivity between applications. As ASP.NET developer, If I need an application that will be used by many other applications then I can simply decide to write a web service for it and ASP.NET framework will take care of doing the low level SOAP and XML work for us.

The other side of the coin is, if our ASP.NET application wants to use a web service, i.e., an application that is providing me SOAP based interface for communication. So what we are going to do now is write a small Web service to see how we can have our application communication-ready for other applications and secondly, we will try to consume a webservice to understand how we can use other applications from our application.

Web service article image

Creating a Web Service

Let us write a simple module that will provide basic arithmetic operations to other applications. The user of our application will have to provide us 2 numbers and we will perform the requested operation like Addition, Subtraction and Multiplication.

So, the first thing we need to do is to create our web service. We can do this by creating a website of type ASP.NET Web service. This will give us a skeleton to write our web service code in.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
}

The attribute WebService tells that this class contains the code for web service. The namespace is what is used to identify the web service. The WebMethod attribute specifies the methods which our web service is providing.

Let us now go ahead and write code to have our functions in this webservice.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    public Service ()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public int Add(int x, int y)
    {
        return x+y;
    }

    [WebMethod]
    public int Subtract(int x, int y)
    {
        return x - y;
    }

    [WebMethod]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

We have a very basic web service implemented which can let the user have some basic arithmetic operations. Now to create the WebService binary, we will have to use the following command on Visual Studio Command Prompt.

>CSC /t:library /out:ArithmeticServiceImpl.dll App_code\Service.cs

This will create a DLL file for our web service. This DLL file can be used by any client by using the SOAP protocol. If we need to test our web service for how it works over the SOAP protocol, we can view the service.asmx file in the browser and see what functions our web service is exposing.

Web service article image

We can even test these methods here and see the XML file that contains the service description.

Consuming a WebService

There are three ways we can consume a WebService:

  1. Using HTTP-POST method.
  2. Using XMLHttp that will use SOAP to call our the service
  3. Using WSDL generated proxy class

The HTTP-Post method can be used by calling .asmx file directly from client. We can directly use the method name and the parameter names will be taken from our input fields on form.

<html>
    <body>
        <form action="http://localhost/.../Service.asmx/Multiply"  method="POST">
                <input name="x"></input>
                <input name="y"></input>

                <input type="submit" value="Enter"> </input>
        </form>
    </body>
</html>

When this form get submitted, the web service's method will be called. The second method where we can use the XMLHttp over SOAP to access the webservice is used when we want to use the web service using full capability of SOAP.

The third way of using the web service is by generating a Proxy class for the web service and then using that proxy class. This method is, to me, more type safe and less error prone as once we have the proxy class generated, it can take care of SOAP messages, serialization and ensure that all the problems can be handled at compile time instead of runtime.

To use this service, we need to do "Add Web reference" and add the webservice reference. Alternatively I can also use WSDL.exe, a command line tool, to generate the proxy classes and use them. "Add web Reference" is also using the same WSDL.exe to generate the proxy classes.

Web service article image

Now let us write some code to use the proxy class to perform the operations, the proxy class will then communicate to the web service using SOAP and get back the results to us.

protected void Button1_Click(object sender, EventArgs e)
{
    if (txtX.Text != string.Empty
        && txtY.Text != string.Empty)
    {
        try
        {
            int x = Convert.ToInt32(txtX.Text);
            int y = Convert.ToInt32(txtY.Text);

            ArithmeticService.Service service = new ArithmeticService.Service();

            Label1.Text = "Sum: " + service.Add(x, y).ToString();
            Label2.Text = "Difference: " + service.Subtract(x, y).ToString();
            Label3.Text = "Multiplication: " + service.Multiply(x, y).ToString();
        }
        catch(Exception)
        {
            throw;
        }
    }
}

Let us run the website to see the results

Web service article image

Points of Interest

We saw how to create a web service in ASP.NET and how we can consume a web service in ASP.NET. One interesting area that we did not see here is how we can use web service from AJAX. ASP.NET also provides a mechanism using scriptManager that will generate the JavaScript proxy for a webservice and we can use it to call the webservice methods. Also, if we want to customize the security of our web service, we can do that too using custom SOAP headers.

History

  • 27 Feb 2012: Understanding the basics of Web Service in ASP.NET

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionThanks for sharing nice article Pin
khaliqhamid2-May-14 19:00
memberkhaliqhamid2-May-14 19:00 
GeneralMessage Automatically Removed Pin
30-Apr-14 21:16
memberRavi Kumar30-Apr-14 21:16 
Questionbasic grid edit delete update Pin
mganesan198724-Apr-14 18:01
membermganesan198724-Apr-14 18:01 
QuestionMy vote of 5 Pin
Gena H11-Apr-14 22:14
memberGena H11-Apr-14 22:14 
SuggestionMessage Automatically Removed Pin
31-Mar-14 19:01
memberAyesha Sharma31-Mar-14 19:01 
Questionأحسنت Pin
Ayham Ȝllan10-Mar-14 22:44
memberAyham Ȝllan10-Mar-14 22:44 
AnswerRe: أحسنت Pin
Rahul Rajat Singh10-Mar-14 22:47
mvpRahul Rajat Singh10-Mar-14 22:47 
Questionc#.asp.net,sql,css,jquery important links Pin
mganesan19872-Jan-14 4:26
membermganesan19872-Jan-14 4:26 
asp.net:
http://www.dotnetfox.com/articles/how-to-add-edit-delete-update-records-in-grid-view-Asp-Net-1003.aspx

http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/

http://www.aspsnippets.com/Articles/DataBinding-DropDownList-Label-and-Textbox-Controls-in-ASP.Net.aspx

http://www.cramerz.com/aspdotnet

http://www.slideshare.net/mannysiddiqui/Advanced-ASPNET-Concepts-and-Constructs

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

http://www.aspsnippets.com/Articles/How-to-bind-GridView-with-DataReader-in-ASPNet-using-C-and-VBNet.aspx

http://www.aspdotnet-suresh.com/2012/10/aspnet-difference-between-datareader.html

http://www.microsoft.com/web/post/adding-video-to-your-website-using-the-new-html5-video-tag

http://www.homewebsitebuilder.com/admin/site/niche

http://www.tutorialspoint.com/asp.net/asp.net_multi_views.htm

http://www.aspdotnet-suresh.com/2011/02/how-to-inserteditupdate-and-delete-data.html

http://www.aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspx

http://www.aspdotnet-suresh.com/2011/12/how-to-create-simple-login-form-using.html


c#.net:

http://www.c-sharpcorner.com/1/75/asp-net-controls.aspx

http://www.c-sharpcorner.com/UploadFile/sapnabeniwal/a-glimpse-to-image-slideshow-using-jquery/

http://www.c-sharpcorner.com/UserRegistration/UserRegistration.aspx?check=r&ReturnURL=/uploadfile/sapnabeniwal/a-glimpse-to-image-slideshow-using-jquery/

http://samples.gaiaware.net/Combinations/WebApps/Chess/

http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=183

http://www.tutorialspoint.com/csharp/csharp_overview.htm

http://www.c-sharpcorner.com/UploadFile/b8d90a/send-sms-using-C-Sharp-net/

http://forums.asp.net/t/1883175.aspx/1

http://social.msdn.microsoft.com/Search/en-US?query=sms%20senting%20method%20asp.net&emptyWatermark=true&ac=6

file related
http://go.microsoft.com/FwLink/p/?LinkID=303856
http://go.microsoft.com/FwLink/p/?LinkID=303859
http://go.microsoft.com/FwLink/p/?LinkID=303863
http://go.microsoft.com/FwLink/p/?LinkID=303861

http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDsQFjAA&url=http%3A%2F%2Fsourceforge.net%2Fdirectory%2Fbusiness-enterprise%2Fenterprise%2Fmedhealth%2F&ei=qGvmUoPWJcWNrgfUtYHIDQ&usg=AFQjCNE1mbxdpBcX7qYaBVokbUtxpOxO3g&cad=rja


http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=5&ved=0CFQQFjAE&url=http%3A%2F%2Fmastersinhealthinformatics.com%2F2009%2F25-open-source-software-projects-that-are-changing-healthcare%2F&ei=qGvmUoPWJcWNrgfUtYHIDQ&usg=AFQjCNEFLVbn2_l2eTlmgD4P8_O1iAkGCA&cad=rja

http://www.1000projects.org/sr1p/dn17p/he-in-ma.zip


http://www.1000projects.org/sr1p/dn17p/he-in-ma.zip


http://www.ondd.org/the-top-100-open-source-software-tools-for-medical-professionals/


sql

http://programmers.stackexchange.com/questions/181651/are-these-sql-concepts-for-beginners-intermediate-or-advanced-developers

http://www.gplivna.eu/papers/sql_join_types.htm

http://developers.cartodb.com/tutorials/joining_data.html

webservice:http://www.aspdotnet-suresh.com/2011/05/aspnet-web-service-or-creating-and.html

http://www.aeiucm.com/index.php/erp-system/payroll-system

http://www.finetechcode.com/upload-and-free-download-php-source-code-php-projects/

http://visuallightbox.com/visuallightbox-mac-setup.zip?affiliateid=WPG731GH

http://www.kannel.org/download.shtml#devel

http://www.developershome.com/sms/sms_tutorial.asp?page=smsGateway

http://www.clickatell.com/

http://www.ozekisms.com/index.php?owpn=230


wpf&wcf:

http://tnvbalaji.com/articles/wcf-tutorials/

http://www.codeproject.com/Tips/468354/WCF-Example-for-Inserting-Deleting-and-Displaying

http://www.codeproject.com/Articles/99330/WPF-Step-by-Step-Getting-Started-with-WPF-and-Expr

http://www.aspdotnet-suresh.com/2012/10/c-difference-between-aspnet-webservice.html

jquery url:

http://jqueryui.com/effect/

http://www.slidesjs.com/

http://bxslider.com/examples

http://www.htmlgoodies.com/tutorials/forms/article.php/3895776/HTML-Forms-jQuery-Basics---Getting-Started.htm

http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/

http://msdn.microsoft.com/en-us/library/bb386416%28v=vs.100%29.aspx

http://msdn.microsoft.com/en-us/library/x8k61whf%28v=vs.100%29.aspx

http://gregfranko.com/jquery.selectBoxIt.js/#Examples

http://www.cssbasics.com/css-classes/


menu

http://jqueryui.com/menu/#default and apycom.com

Design

http://www.subcide.com/articles/creating-a-css-layout-from-scratch/

wizard

ttp://www.codeproject.com/Articles/15804/ASP-NET-2-0-Wizard-Control

calender holiday

http://www.c-sharpcorner.com/uploadfile/puranindia/calendar-control-in-Asp-Net/

tutorial

http://www.java2s.com/Tutorial/CSharp/CatalogCSharp.htm

ajax asp.net

http://www.programcall.com/7/aspnet/binding-dropdownlist-with-dataset-values-in-aspnet.aspx

http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/

storedprocedure

http://www.mssqltips.com/sqlservertutorial/164/using-try-catch-in-sql-server-stored-procedures/

nth max salary

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

hosting

http://www.dotnetfunda.com/articles/article1247-how-to-host-aspnet-application-on-the-web-server-iis.aspx


js slider

http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/#prettyPhoto

solutions

http://www.dotnetspider.com/resources/Category518-ASP.NET-GridView.aspx

Excel
>http://www.codeproject.com/Articles/16210/Excel-Reader

>http://www.smartxls.com/download.htm\

mobile find location:
http://msdn.microsoft.com/en-us/magazine/hh852592.aspx

js:
http://bxslider.com/examples/auto-show-start-stop-controls

jscript validation

http://webcheatsheet.com/javascript/form_validation.php

http://www.w3resource.com/javascript/form/javascript-sample-registration-form-validation.php

http://www.tizag.com/javascriptT/javascriptform.php

sql:
http://www.1keydata.com/sql/inline-view.html

http://www.tutorialspoint.com/sql/sql-rdbms-concepts.htm

http://programmers.stackexchange.com/questions/181651/are-these-sql-concepts-for-beginners-intermediate-or-advanced-developers
image slide show using jquery

http://www.c-sharpcorner.com/UserRegistration/UserRegistration.aspx?check=r&ReturnURL=/uploadfile/sapnabeniwal/a-glimpse-to-image-slideshow

http://www.aspdotnet-suresh.com/2011/04/ajax-accordion-control-example-or-how.html


http://www.w3resource.com/javascript/form/javascript-field-level-form-validation.php

http://www.mywebsite123.com/


http://www.aspdotnet-suresh.com/2013/04/8-jquery-popup-window-plugin-examples.html

jqueryslidertemplates

http://wowslider.com/rq/own-template-beautiful-jquery-slider-1e.html

http://wowslider.com/best-jquery-slider-crystal-linear-demo.html

http://cube3x.com/2013/08/30-free-jquery-slider-plugins/


http://www.aspdotnet-suresh.com/2011/02/how-to-inserteditupdate-and-delete-data.html

Xcode for iphones apps
1.https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

2.http://www.appcoda.com/improve-detail-view-controller-storyboard-segue/

basic web service in codeproject

ado.net :

*dataset
*datatable
*datarow
*datacolumn
***********
*sqldataadapter
*sqldatareader
*sqlcommand
************
*executereader
*executenonquery
*executescalar
**********************
http://www.dotnetspider.com/projects/category2.aspx

http://wowslider.com/download/wowslider-win-setup.zip?utm_source=free_downl_win&utm_medium=email&utm_campaign=wow_downl_link

http://www.freshdesignweb.com/jquery-login-registration-contact-form.html

http://demos.devexpress.com/MVCxGridViewDemos/DataBinding/DataBinding

http://w3layouts.com/healthy-mobile-website-template

http://www.webcodeexpert.com/2013/08/create-registration-form-and-send.html#.UyGOqD-Sxr0 conformation email

http://www.aspdotnet-suresh.com/2012/10/aspnet-difference-between-datareader.html




http://visuallightbox.com/visuallightbox-mac-setup.zip?affiliateid=WPG731GH

http://www.c-sharpcorner.com/UploadFile/sapnabeniwal/a-glimpse-to-image-slideshow-using-jquery/

http://www.c-sharpcorner.com/UserRegistration/UserRegistration.aspx?check=r&ReturnURL=/uploadfile/sapnabeniwal/a-glimpse-to-image-slideshow-using-jquery/


http://www.microsoft.com/web/post/adding-video-to-your-website-using-the-new-html5-video-tag



http://www.homewebsitebuilder.com/admin/site/niche


http://www.filesmix.com/item/live-demo/3127 LOGIN TEMPLATE


http://www.templatemo.com/

http://streetsmash.com/admin-templates/

http://bootsnipp.com/?page=4

Dynamic cloud widgets animation
http://www.dotnettips4u.com/2013/03/registering-in-web-site.html
http://www.goat1000.com/tagcanvas.php
http://www.portnine.com/bootstrap-themes

c#.net add webmethod important:
http://www.mikesdotnetting.com/Article/104/Many-ways-to-communicate-with-your-database-using-jQuery-AJAX-and-ASP.NET
http://www.citehr.com/318322-payroll-excel-sheet.html


----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;

[Serializable]
public class BAL
{
SqlConnection con;
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();

public Dictionary DParameter { get; set; }
string Result = string.Empty;
public BAL() { DParameter = new Dictionary(); }
#region Clear Member Function
public void Clear_DropDownList(ControlCollection ControlCollections)
{
List allControls = new List();
GetControlList(ControlCollections, allControls);
foreach (var childControl in allControls) { childControl.SelectedIndex = -1; }
}
public void Clear_TextBox(ControlCollection ControlCollections)
{
List allControls1 = new List();
GetControlList(ControlCollections, allControls1);
foreach (var childControl in allControls1) { childControl.Text = ""; }
}
public void Clear_RadioButtonList(ControlCollection ControlCollections)
{
List allControls2 = new List();
//GetControlList(Page.Controls, allControls2);
GetControlList(ControlCollections, allControls2);
foreach (var childControl in allControls2) { childControl.SelectedIndex = -1; }
}
public void Clear_CheckBoxList(ControlCollection ControlCollections)
{
List allControls3 = new List();
GetControlList(ControlCollections, allControls3);
foreach (var childControl in allControls3) { childControl.SelectedIndex = -1; }
}
private void GetControlList(ControlCollection controlCollection, List resultCollection) where T : Control
{
foreach (Control control in controlCollection)
{
//if (control.GetType() == typeof(T))
if (control is T) // This is cleaner
resultCollection.Add((T)control);

if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
#endregion

#region SQLCommand Member Function
public string CAIUDT_Data(string ConnectionName, string Query, CommandType CommandTypes = CommandType.Text, Boolean IsParam = false)
{
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandText = Query;
cmd.CommandType = CommandTypes;
if (IsParam)
{
foreach (KeyValuePair kvp in DParameter)
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
if (con.State == ConnectionState.Closed) con.Open();
Result = Convert.ToString(cmd.ExecuteNonQuery());
//if (Result == "1") Result = Result + " row affected";
//else Result = Result + " row(s) affected";
}
}
catch (Exception Ex) { Result = Ex.Message; }
finally
{
cmd.Dispose();
if (con.State == ConnectionState.Open) con.Close();
}
return Result;
}
#endregion

#region SQLDataAdapter Member Function
public string SingleData(string ConnectionName, string Query, CommandType CommandTypes = CommandType.Text, Boolean IsParam = false)
{
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandText = Query;
cmd.CommandType = CommandTypes;
if (IsParam)
{
foreach (KeyValuePair kvp in DParameter)
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
if (con.State == ConnectionState.Closed) con.Open();
Result = Convert.ToString(cmd.ExecuteScalar());
}
}
catch (Exception Ex)
{
Result = Ex.Message;
}
finally
{
cmd.Dispose();
sda.Dispose();
}
return Result;
}
public DataTable SelectMethod(string ConnectionName, string Query, CommandType CommandTypes = CommandType.Text, Boolean IsParam = false)
{
DataTable dts = new DataTable();
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
cmd.Parameters.Clear();
dts.Clear();
cmd.Connection = con;
cmd.CommandText = Query;
cmd.CommandType = CommandTypes;
if (IsParam)
{
foreach (KeyValuePair kvp in DParameter)
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
if (con.State == ConnectionState.Closed) con.Open();
sda = new SqlDataAdapter(cmd);
sda.Fill(dts);
}
}
catch (Exception Ex) { dts = null; }
finally
{
cmd.Dispose();
sda.Dispose();
}
return dts;
}
public void FillData(System.Web.UI.WebControls.WebControl ctrl, DataTable dt, Boolean IsSelectValue = false, string DataTextField = null, string DataValueField = null, string SelectText = "-select-")
{
try
{
if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddls = (DropDownList)ctrl;
ddls.DataSource = dt;
ddls.DataTextField = DataTextField;
ddls.DataValueField = DataValueField;
ddls.DataBind();
if (IsSelectValue) { ddls.Items.Insert(0, SelectText); }
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.RadioButtonList))
{
RadioButtonList ddls = (RadioButtonList)ctrl;
ddls.DataSource = dt;
ddls.DataTextField = DataTextField;
ddls.DataValueField = DataValueField;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.CheckBoxList))
{
CheckBoxList ddls = (CheckBoxList)ctrl;
ddls.DataSource = dt;
ddls.DataTextField = DataTextField;
ddls.DataValueField = DataValueField;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.ListBox))
{
ListBox ddls = (ListBox)ctrl;
ddls.DataSource = dt;
ddls.DataTextField = DataTextField;
ddls.DataValueField = DataValueField;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.FormView))
{
FormView ddls = (FormView)ctrl;
ddls.DataSource = dt;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DetailsView))
{
DetailsView ddls = (DetailsView)ctrl;
ddls.DataSource = dt;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.GridView))
{
GridView ddls = (GridView)ctrl;
ddls.DataSource = dt;
ddls.DataBind();
}
else if (ctrl.GetType() == typeof(System.Web.UI.WebControls.ListView))
{
ListView ddls = (ListView)ctrl;
ddls.DataSource = dt;
ddls.DataBind();
}
}
catch (Exception Ex) { }
}
#endregion

#region Other Members
public static string Numbers2Words(string inputNumber)
{
int inputNo = Convert.ToInt32(inputNumber);
if (inputNo == 0) { return "Zero"; }
int[] numbers = new int[4];
int first = 0, u, h, t;
StringBuilder sb = new StringBuilder();
if (inputNo < 0) { sb.Append("Minus "); inputNo = -inputNo; }
string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
string[] words3 = { "Thousand ", "Lakhs ", "Crore " };
numbers[0] = inputNo % 1000;
numbers[1] = inputNo / 1000;
numbers[2] = inputNo / 100000;
numbers[1] = numbers[1] - 100 * numbers[2];
numbers[3] = inputNo / 10000000;
numbers[2] = numbers[2] - 100 * numbers[3];
for (int i = 3; i > 0; i--) { if (numbers[i] != 0) { first = i; break; } }
for (int i = first; i >= 0; i--)
{
if (numbers[i] == 0) continue;
u = numbers[i] % 10;
t = numbers[i] / 10;
h = numbers[i] / 100;
t = t - 10 * h;
if (h > 0) sb.Append(words0[h] + "Hundred ");
if (u > 0 || t > 0)
{
if (h > 0 || i == 0) sb.Append("and ");
if (t == 0) { sb.Append(words0[u]); }
else if (t == 1) { sb.Append(words1[u]); }
else { sb.Append(words2[t - 2] + words0[u]); }
}
if (i != 0) sb.Append(words3[i - 1]);
}
return sb.ToString().TrimEnd();
}
public DateTime Server_DateTime(string ConnectionName)
{
DateTime dt = new DateTime();
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
if (con.State == ConnectionState.Closed) con.Open();
cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DATEADD(MI,tz_diff,GETDATE())[tz_diff] from tbl_TimeZone";
dt = Convert.ToDateTime(cmd.ExecuteScalar());
}
}
catch (Exception Ex)
{
dt = Convert.ToDateTime("1900-01-01");
}
finally
{
cmd.Dispose();
if (con.State == ConnectionState.Open) con.Close();
}
return dt;
}
public DateTime ServerDateTime(string ConnectionName)
{
DateTime dt = new DateTime();
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
if (con.State == ConnectionState.Closed) con.Open();
cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select GETDATE()[TimeZone]";
dt = Convert.ToDateTime(cmd.ExecuteScalar());
}
}
catch (Exception Ex)
{
dt = Convert.ToDateTime("1900-01-01");
}
finally
{
cmd.Dispose();
if (con.State == ConnectionState.Open) con.Close();
}
return dt;
}
public string Current_Ident(string ConnectionName, string TableName)
{
try
{
using (con = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionName].ConnectionString))
{
if (con.State == ConnectionState.Closed) con.Open();
cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select IDENT_CURRENT('" + TableName + "')";
Result = Convert.ToString(cmd.ExecuteScalar());
}
}
catch (Exception Ex)
{
Result = Ex.Message;
}
finally
{
cmd.Dispose();
if (con.State == ConnectionState.Open) con.Close();
}
return Result;
}
public void Grid2Excel(DataTable dt, System.Web.UI.WebControls.WebControl ctrl)
{
GridView grdvw = (GridView)ctrl;
string attachment = "attachment; filename=report.xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
grdvw.AllowPaging = false;
grdvw.ShowHeader = true;
grdvw.DataSource = dt;
grdvw.DataBind();
grdvw.HeaderRow.Style.Add("background-color", "#fe3dec");
grdvw.HeaderRow.Style.Add("border", "1px solid #000");
grdvw.DataBind();
foreach (GridViewRow gvr in grdvw.Rows)
{
foreach (TableCell tc in gvr.Cells)
{
tc.Style.Add("border", "1px solid #000");
}
}
for (int i = 0; i < grdvw.HeaderRow.Cells.Count; i++)
{
grdvw.HeaderRow.Cells[i].Style.Add("color", "#df5015");
grdvw.HeaderRow.Cells[i].Style.Add("border", "1px solid #000");
}
grdvw.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(grdvw);
frm.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
public string getJSON(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List> rows = new List>();
Dictionary row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary();
foreach (DataColumn col in dt.Columns)
row.Add(col.ColumnName, dr[col]);
rows.Add(row);
}
return serializer.Serialize(rows);
}
public string Encryption(string PlainText, string Key)
{
try
{
byte[] CypherText;
string NewKey = string.Empty;
foreach (char ch in Key.ToCharArray()) { NewKey = ch + NewKey; }
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8Encoding.UTF8.GetBytes(NewKey));
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.Key = TDESKey;
TDES.Mode = CipherMode.ECB;
TDES.Padding = PaddingMode.PKCS7;
byte[] ASCIICode = UTF8Encoding.UTF8.GetBytes(PlainText);
try
{
ICryptoTransform Encryptor = TDES.CreateEncryptor();
CypherText = Encryptor.TransformFinalBlock(ASCIICode, 0, ASCIICode.Length);
Result = Convert.ToBase64String(CypherText);
}
finally
{
TDES.Clear();
HashProvider.Clear();
}
}
catch (Exception Ex) { Result = null; }
return Result;
}
public string Decryption(string Text, string Key)
{
byte[] Results;
string NewKey = string.Empty;
foreach (char ch in Key.ToCharArray()) { NewKey = ch + NewKey; }
MD5CryptoServiceProvider Hash = new MD5CryptoServiceProvider();
byte[] TDESKey = Hash.ComputeHash(UTF8Encoding.UTF8.GetBytes(NewKey));
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.Key = TDESKey;
TDES.Mode = CipherMode.ECB;
TDES.Padding = PaddingMode.PKCS7;
byte[] ASCIICode = Convert.FromBase64String(Text);
try
{
ICryptoTransform Decryptor = TDES.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(ASCIICode, 0, ASCIICode.Length);
}
finally
{
TDES.Clear();
Hash.Clear();
}
return UTF8Encoding.UTF8.GetString(Results);
}
#endregion
}
-------------
http://www.c-sharpcorner.com/Blogs/12509/difference-between-datareader-dataset-dataadapter-and-data.aspx[^]

modified 4-Oct-14 6:43am.

Questionmabahong indiano Pin
jerome dela cruz23-Sep-13 21:14
memberjerome dela cruz23-Sep-13 21:14 
AnswerRe: mabahong indiano Pin
Rahul Rajat Singh5-Dec-13 20:13
mvpRahul Rajat Singh5-Dec-13 20:13 
QuestionDanish Habib Pin
danishuet23-Aug-13 2:26
memberdanishuet23-Aug-13 2:26 
GeneralMy vote of 5 Pin
ketan italiya13-Aug-13 20:23
professionalketan italiya13-Aug-13 20:23 
GeneralMy vote of 5 Pin
prema_r28-Jul-13 0:38
memberprema_r28-Jul-13 0:38 
QuestionThanks Rahul Pin
Member 994161423-Jul-13 11:13
memberMember 994161423-Jul-13 11:13 
GeneralMy vote of 5 Pin
Qadri Jillani3-Jul-13 19:16
memberQadri Jillani3-Jul-13 19:16 
Questionweb services Pin
Qadri Jillani3-Jul-13 19:14
memberQadri Jillani3-Jul-13 19:14 
GeneralMy vote of 3 Pin
GreatOak27-Jun-13 2:01
memberGreatOak27-Jun-13 2:01 
Generalvery good and understanding article Pin
AmrutaKanvinde20-Jun-13 14:41
memberAmrutaKanvinde20-Jun-13 14:41 
GeneralVery Nice Article Pin
Lalit PB31-May-13 0:42
member Lalit PB31-May-13 0:42 
GeneralVery nice article Pin
rasul gani11-Apr-13 21:29
memberrasul gani11-Apr-13 21:29 
GeneralRe: Very nice article Pin
vijaykaliyaperumal23-May-13 3:46
groupvijaykaliyaperumal23-May-13 3:46 
GeneralMy vote of 5 Pin
ajis23262-Apr-13 23:36
memberajis23262-Apr-13 23:36 
GeneralMy vote of 5 Pin
sagmali25-Mar-13 4:25
membersagmali25-Mar-13 4:25 
GeneralMy vote of 5 Pin
Kr.Prakash19-Mar-13 23:43
memberKr.Prakash19-Mar-13 23:43 
GeneralMy vote of 5 Pin
Nikhil_S10-Mar-13 19:52
memberNikhil_S10-Mar-13 19:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160811.3 | Last Updated 11 Jun 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid