Proxy > Gmail Facebook Yahoo!

A simple application of Web Services in .net

Web services are used to give websites program functionality via internet. Web services can
accept messes and can return replies.


A simple example to demonstrate, how to design and use that web services in our website.
Web service has “.asmx” extension.
To designing web service select New Project and in the New Project dialog box select
“ASP.NET Web Service Application”
Now once the ASP.NET Web Service Application page opened we will do some coding part.

Code (WebService1.asmx.cs)

//before writing any method in web service we have to write “[WebMethod]”
//within square brakets”[ ]”.

//creating method Add which will accept two arguments.
        public int Add(int a, int b)
//returning value
            return a + b;

Now, we need to compile the application and add the compiled application 
to IIS in  order to get its web refrence, as we have to add its 
web refrence where we have to use it.

Example to demonstrate how to use Web service in our website

Designing website

Web Site design code(Default.aspx)

<form id="form1" runat="server">
    <asp:TextBox ID="TextBox2" runat="server"
    <asp:TextBox ID="TextBox1" runat="server"
    <asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click"
        Text="Add" />
    <asp:Label ID="Label2" runat="server" Text="TextBox2"
    <asp:Label ID="Label1" runat="server" Text="TextBox1"

Code for adding two numbers in text boxes using the web service

Before writing the code we need to add the web reference of the web service. To add web
reference of the web service right click in “Solution Explorer” and select “Add Web Reference”,
   add web reference dialog box will appear. There add the web reference of the service in my
case it is http://localhost:51481/Service1.asmx.

Code for website

//code for add button click
protected void btnAdd_Click(object sender, EventArgs e)
//creating object of service created earlier.
        localhost.Service1 ws = new localhost.Service1();
//using Add method of web service and displaying the result in the page.
  Response.Write((ws.Add(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text))).ToString());

Screen shot of web page

[Read More...]

Top ten Techies who changed the world

Steve Jobs, Apple – Maverick entrepreneur and co-founder of Apple, Steve Jobs is the current grandmaster of technology. Business savvy and a risk taker, Jobs is the visionary who redefined technology with world changing products like the Personal Computer, iPod, iPhone and iPad.

Mark Zuckerberg, Facebook – Whizkid Zuckerberg almost single handedly transformed the Internet from a place people went to get information to a place they went to meet each other. Facebook gave the virtual world a patina of humanity, the real world a new medium of interpersonal relationships, and made Zuckerberg not only this generation's phenomenon, but also the second youngest billionaire in the world. Interesting fact: The youngest billionaire is Dustin Moskovitz – co-founder of Facebook and 8 days younger than Zuckerberg, his Harvard roommate

Bill Gates, Microsoft – The Microsoft founder has passed the legion of supergeeks into the pantheon of technological demi-gods. The richest man in the world from 1995 to 2007 is currently the second richest. He holds 8 percent of Microsoft stock and now functions as the non-executive chairman of the company. Over the years, Gates and wife Melinda have made philanthropy their primary concern and recently pledged to give away at least half their fortune to charity with time.

Linus Torvalds, Linux – This Finnish engineer is virtually unknown outside the inner circles of technology, yet he is among the most influential figures in software development. A believer in open source software, Torvalds initiated thedevelopment of the Linux Kernel. He now acts as the coordinator of the project. The Linux operating system runs the 10 fastest supercomputers in the world and a diverse range of hardware including the smallest of devices. A modified version of the Linux kernel powers the ubiqitous Android OS

Larry Page and Sergey Brin, Google – Co-founders of internet behemoth Google, Larry Page and Sergey Brin ran Google from a rented garage in 1998. Twelve years later, Google has left it's Silicon Valley startup past way behind to become the world's largest media corporation.

Evan Williams, Twitter & Blogger – Virtually unknown in the real world, this college drop-out created two key communication technologies that shaped the Internet – Blogger and Twitter. He no longer works at Twitter but he's left an indelible handprint on the cyberworld.

Shigeru Miyamoto, Nintendo – Even if you've never played a video game, chances are you've heard of Super Mario Bros. Shigeru Miyamoto is the Japanese game designer behind popular Nintendo titles like Legend of Zelda, Donkey Kong, Star Fox, and the grand old man of gaming, Mario.

Jeffrey Bezos, Amazon – In 1994, this Princeton graduate started from his garage in Seattle and changed the face of online retail forever. He began with selling books online but soon diversified into, well, almost everything. Amazon made him a billionaire as well as Time magazine's person of the year in 1999.

Tim Berners-Lee, the World Wide Web – 20 years ago British physicist and computer scientist Berners-Lee invented the World Wide Web, the first web browser and the first web server. This man is the reason we can access webpages and surf the Internet using browsers today. (Photo: AP)

Akio Morita, Sony – Former naval officer Akio Morita left his family business of sake, miso and soy sauce to co-found Sony Corporation in 1946. Most of Sony's path-breaking products like magnetic tapes, tape recorders, pocket-sized radios, the Walkman and the Discman were developed under his leadership. (Photo: AP)

11th Man: Woz – The other Steve who founded Apple with Steve Jobs was Steve Wozniak. Affectionately called Woz, he has been credited with developing the Apple I and Apple II computers in the 1970s. He no longer works full time with Apple, but is still a shareholder and employee of the company.

[Read More...]

A beginner’s guide for consuming a WCF service in JavaScript using ASP.NET AJAX

Development Platform


  1. Visual Studio 2008 SP1
  2. .NET Framework 3.5 SP1
  4. IIS 7 or VS Integrated Web Server [WCF and SVS file configured]
  5. Windows Vista


WCF (Windows Communication Foundation) added a lot of new capabilities to the Microsoft application development platform, particularly in how applications communicate with each other. In this article, we are going to see how WCF can be used directly from a client-side JavaScript code. It is a very cool future provided by ASP.NET AJAX. In this article, we are not going to cover every theory about WCF internals, rather we only remain focused on how to use a service directly from JavaScript. So, no behind-the-scenes stuff on how ASP.NET or the .NET runtime manages this feature.
To demonstrate the ideas and facts, we are going create a demo solution with two projects. So, with no time waste, create a blank solution and save it. Now, add a Class Library project to the solution. Name the class library ServiceLibrary. Now, add a Web Application project to the solution and name it WEBUI. We are going to see two approaches to add a WCF Service that can be consumed from JavaScript.
  1. Using Ajax-Enable WCF Service item template
  2. Using Service Interface defined in a class library

Using an AJAX-Enabled WCF Service Item Template

Here, we will see a very straightforward way to use a WCF Service in JavaScript. Right click on the Web Application project and select Add New Item. Select AJAX-Enabled WCF Service Item Template, and name it “HelloWorldService.svc” and click OK. The wizard will add a HelloWorldService.svc file to the solution as expected. This file will have a code-behind file as well. If you open HelloWorldService.svc in an XML file editor, you will see a markup like this:
<%@ ServiceHost Language="C#" Debug="true" 
  Service="WebUI.HelloWorldService" CodeBehind="HelloWorldService.svc.cs" %>
If you open the code-behind file, you will see code like this:
namespace WebUI
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = 
    public class HelloWorldService
        public void DoWork()
Visual Studio 2008 automatically adds the necessary configurations for you in the web.config file, so no need to configure any thing in the web.config. Now, go ahead and add a HelloWorld() method which returns a string “HelloWorld”, and add a [OperationContract] attribute to the method. We will explain what the attributes are later in this article. Now, add a page to the Web Application project and name it “HelloWorldTest.aspx”. Drag and drop a Script Manager item from the Visual Studio tool box. Inside the ScriptManager tag, add a service reference to the service. An example code is given below:
<asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:ServiceReference Path="~/HelloWorldService.svc" />
Now, add a button and a textbox to the page, and on the button click event, use a JavaScript function to call the Service. When you write the service call function, the Visual Studio 2008 HTML Editor will provide intellisense to write the necessary function call. The full HTML code is give below:
<form id="form1" runat="server">
    <script language="javascript" type="text/javascript">
        function GetValueFromServer() {
            HelloWorldService.HelloWorld(onSuccess, onFailure);

        function onSuccess(result) {
            document.getElementById('txtValueContainer').value = result;

        function onFailure(result) {
    <asp:ScriptManager ID="ScriptManager1" runat="server">
            <asp:ServiceReference Path="~/HelloWorldService.svc" />
    <input id="btnServiceCaller" type="button" value="Get Value" 
           onclick="GetValueFromServer()"; />
    <input id="txtValueContainer" type="text" value="" />
Note that when calling the service, we have passed two methods: one for the callback and the other for the error callback. If we need to pass any parameters to the function, the parameters will go first and then the callback. So, if we have a function named getvalue which takes two string parameters as arguments, we are going to call the function as [NameSpaceName].[ServiceName].getvalue(“value one”,”value two”,on_success,on_error);, whereon_sucess and on_error are the callback and the error callback, respectively.

Using a Service Interface Defined in the Class Library

So, we have looked at how to use an AJAX-enabled WCF Service using an item template. Now, we are going to see a more traditional WCF Service implementation, and we are also going to see how we can expose this service for ASP.NET AJAX. When we created the Class Library project, by default, it is not added with the service model and the runtime serialization support which is necessary to run WCF. So, we have to add the necessary service references. Go ahead and right click on the Class Library project and select Add Reference, and then select these references:
  • System.Runtime.Serialization
  • System.ServiceModel
In this phase, we are going to use a TODO Management example to demonstrate the whole idea. Add a Service based database, and then create a TODO table with IDDescription, and Status fields. Now, add a LINQ to SQL class file from the item template. Drag and drop the TODO table from database to the LINQ to SQL Class File Designer. Now, click on the designer surface and from the property window, change the serialization mode to Unidirectional. Now, our designer generated LINQ to SQL classes are ready to be used for WCF. If you want to use custom user defined types, you must set the [DataContract] class attribute to your class and you must add the [DataMember] property attribute to each property of the class you want to expose to WCF.
Now, we are going to add a service interface like this:
namespace ServiceLibrary
    [ServiceContract(Namespace = "ServiceLibrary")]
    interface IToDoService
        ToDo GetToDo(long ID);
        ToDo AddToDo(ToDo toDo);
        bool DeleteToDo(ToDo todo);
        ToDo UpdateToDo(ToDo todo);
        List<ToDo> GetAllToDo();
Note that we have mentioned a namespace inside the ServiceContract interface attribute. This is very important. We are going to use this name as the service name inside the JavaScript code to access the services. Now, we are going to add the implementation to this service interface; the code is given below. Please note that in the code, I have used the [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] class attribute; this is a must requirement for exposing the service as an ASP.NET AJAX enabled WCF Service.
namespace ServiceLibrary
    [AspNetCompatibilityRequirements(RequirementsMode = 
    public class ToDoService : IToDoService
        #region IToDoService Members
        public ToDo GetToDo(long ID)
            DataClasses1DataContext context = new DataClasses1DataContext();
            var toDos = from p in context.ToDos
                        where p.ID == ID
                        select p;
            List<ToDo> listTodos =  toDos.ToList();
            if (listTodos != null && listTodos.Count > 0)
                return listTodos[0];
                return null;

Configure a Web Application to Use the TODO Service

Now that we have defined all the necessary stuff to run our TODO application, it is time to expose the Service to the client as an ASP.NET AJAX enabled WCF Service. For this, we are going to add an AJAX-enabled WCF Service.svc file. And, we will get rid of the code-behind file. Or, we can add an XML file or a text file and then rename it to ToDoService.svc. Open it with an XML editor and add a directive like shown below:
<%@ ServiceHost Language="C#" Debug="true" Service="ServiceLibrary.ToDoService" %>
Now, we are going to put the necessary configuration to run this service in web.config. The code is given below:
    <behavior name="AspNetAjaxBehavior">
     <enableWebScript />
    <behavior name="WebUI.HelloWorldServiceAspNetAjaxBehavior">
     <enableWebScript />
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
   <service name="ServiceLibrary.ToDoService">
    <endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding"
     contract="ServiceLibrary.IToDoService" />
   <service name="WebUI.HelloWorldService">
    <endpoint address="" behaviorConfiguration="WebUI.HelloWorldServiceAspNetAjaxBehavior"
     binding="webHttpBinding" contract="WebUI.HelloWorldService" />
Now, right click on the file and select View in Browser to see the service up and running well. A few things must be mentioned before moving to the next phase. You must add a serviceHostingEnvironment and setaspNetCompatibilityEnabled="true" to be able to use a WCF Service in ASP.NET with its features like HTTP Context, Session etc.

Using the Service in JavaScript

Now, use the service just like the HelloWorldService we previously used. Below, I have given example code to make things clear. The ScriptManager markup is also shown. Note that we have added a clientServiceHelper.jsfile. We have put all the client to WCF communication JavaScript functions in that file.
<asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:ScriptReference Path="~/Script/ClientServiceHeler.js" />
        <asp:ServiceReference Path="~/ToDoService.svc" />
We have used an ASP.NET AJAX client-side object oriented model to write the JavaScript client-code which is part of clientServiceHelper.js.
    ServiceClients.ToDoClient = function() {

ServiceClients.ToDoClient.prototype = {

    AddToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.AddToDo(todo, callback, errorCallBack);

    DeleteToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.DeleteToDo(todo, callback, errorCallBack);

    UpdateToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.UpdateToDo(todo, callback, errorCallBack);

    GetAllToDo: function(callback, errorCallBack) {
        ServiceLibrary.IToDoService.GetAllToDo(callback, errorCallBack);

    dispose: function() {

ServiceClients.ToDoClient.registerClass('ServiceClients.ToDoClient', null, Sys.IDisposable)

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


In this article, we have seen how we can use an AJAX-enabled WCF Service Item Template. Then, we saw how we can use a service interface based WCF Service. We also saw how to configure the web.config to use the Services. Last of all, we saw how we to add a service reference in ScriptManager. A few things must be mentioned before ending this article. We can also add a service reference in the C# code. A simple code example is given below:.
ScriptManager manager = ScriptManager.GetCurrent(Page);
ServiceReference reference = new ServiceReference("ToDoService.svc");
[Read More...]

Writing a 'Hello World' program using wpf+wcf+wf step by step


In my development,I use WF to do business logic ,and use wpf to do UI ,and use WCF to do communication.
Yesterday, I saw one post:what is the WCF,WPF,WF anybody can u give me the brief ? ,So I want to write an article to express my point of view.
A "hello world" program has become the traditional first program that many people learn. So I decide to write this 'Hello World' program with wcf+wpf+wf to express it .

About the Code

This example is very simple, just use the WPF, WCF, WF three new technologies. This example has three project:
WPFProject:A WPF Application ,It is used to implement the UI
WFProject:WF4 can be used to customize the business logic, this case I just use it to call the WCFservice
WCFProject:A Console Application,It is used to otain data: ‘hello world’
The WPFProject start WFProject's workflow, WFProject call WCFProject 's WCF Service. Then WCFProject return 'Hello World' to the WFProject, Last WFProject retun 'Hello World' to the WPFProject's UI. Implementation of the order as shown below:
Figure 1

Implementation steps

Create a new WpfApplication, a newConsoleApplication, a workflow of ActivityLibrary, a total of three projects, named respectively: WPFProject, WCFProject, WFProject,as show below:
Figure 2
1、Because it is a console application, so I need to add System.ServiceModel.dll reference
Figure 3

2、Add an interface IService1 for Contract
public interface IService1 
string GetData(); 
3、Add a class Service1 to implement IService1:
    public class Service1 : IService1
        public string GetData()
            return string.Format("Hello World");
4、 Deploy App.config with Address and Binding for wcf service:
<service name="WCFProject.Service1" behaviorConfiguration="metadata"> <host>
<add baseAddress="http://localhost:8001/Service1"/>
<endpoint binding="basicHttpBinding" contract="WCFProject.IService1"/> </service>
<behavior name="metadata">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
5、Add the following code in the Program.cs to start wcf service :
            using (ServiceHost host = new ServiceHost(typeof(Service1)))
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press  to terminate service.");
If you are not familiar with WF, see this
1、Drag and Drop a SendAndReceiveReply to Activity1,as show below.
Figure 4
2、Send:I use this Send Acitivy to call the WCF service.Please note.
a)、OperateName: GetData .(WCF Method)
b)、 EndPoint : EndPoint
c)、Binding : basichttpBingding.(WCF Binding)
d)、EndPointAddress:New Uri ("http://localhost:8001/Service1") (WCF Address)
e)、ServiceContractName :IService1.(WCF Contract)
3、ReceivReplyForSend: I use this ReceivReplyForSend Acitivy to obtain the return value of the WCF service
a)、Add an output parameter:returnValue.
Figure 5
b)、Content as show below:
Figure 6
4、The entire workflow as show below:
Figure 7
In this Demo, this proect is very easy , the relationship between WPF and WF is the reference dll. WPFProject reference WFProject.dll.So
1、Reference WFProject.dll、System.Activities.dll in the WPFProject
Figure 8
Figure 9
2、In MainWindow Form drag a button, change the Content: "Invoke Workflow", in the click event add the following code:
           IDictionary<string, object> results = WorkflowInvoker.Invoke(new Activity1());
Start WCFProject, as shown below:
Figure 10
Start WPFProject. Click Invoke Workflow, the results below:
Figure 12

Points of Interest

This article use the most simple Hello World program teach you to use three kinds of the latest technology. I think this is a good way to development
WPF:UI presents(In client)
WF:Business logic (In server or In client )
WCF:Data communication (In server)
This is my first article on codeproject, my first language is not English.I hope you give me some advice to improve

[Read More...]

Send mail to your Friends.  

Expert Feed

Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar