Archive for the ‘.NET’ Category

Web programming: How to read cookie created by ASP.NET using JavaScript

Wednesday, February 4th, 2009

All of you heard about “Cookies”. This is a way that web site remember some information about you in *.txt file located on your machine.

Here is how we create cookie in C#, this is code behibnd of aspx page.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create a new HttpCookie named "MyLastVisit".
        HttpCookie myHttpCookie = new HttpCookie("MyLastVisit", DateTime.Now.ToString());

        // By default, the HttpOnly property is set to false
        // unless specified otherwise in configuration.

        //rename Cookie
        myHttpCookie.Name = "MyHttpCookie";
        Response.AppendCookie(myHttpCookie);

        // Show the name of the cookie.
        Response.Write(myHttpCookie.Name);

        // Create an HttpOnly cookie.
        HttpCookie myHttpOnlyCookie = new HttpCookie("MyLastVisit", DateTime.Now.ToString());

        // Setting the HttpOnly value to true, makes
        // this cookie accessible only to ASP.NET.

        myHttpOnlyCookie.HttpOnly = true;
        //rename Cookie
        myHttpOnlyCookie.Name = "MyHttpOnlyCookie";
        Response.AppendCookie(myHttpOnlyCookie);

        // Show the name of the HttpOnly cookie.
        Response.Write(myHttpOnlyCookie.Name);
    }
}

and this is java script code which reads cookie:





<script>

    // This code returns the cookie name.
    alert("Getting HTTP Cookie");
    alert(getCookie("MyHttpCookie"));

    // Because the cookie is set to HttpOnly,
    // this returns null.
    alert("Getting HTTP Only Cookie");
    alert(getCookie("MyHttpOnlyCookie"));

</script> 



Top 3 security mistakes which .NET developers make

Tuesday, January 20th, 2009

When you start programming, you can find beginners mistakes in misspelling, missing “;”, … But leter you’ll find there exists logical errors too. Your code has no errors or warnings, but application behavior is different. It is so called logical errors. This post is about some security mistakes which .net developer makes.

1-st Mistake: SQL Injection
SQL injection is passing SQL code into an application. These potential attack strings are parts of SQL query that can be executed on the database server if the Web application uses the string when forming a SQL statement without first parsing out certain characters.

For example, problems can arise when a developer does not protect against potentially malicious input such as a ” ‘ “, which could close the SQL string and give the user unintended system and application access. The simple and most common SQL query which developer use during login process looks like:

SELECT userID, fname, lname from users WHERE username = $username and password = $password

An example of SQL injection would be for the user to enter the following strings for the username and password:

‘ OR ‘1′ = ‘1

The SQL statement passed to the database now reads like this:

SELECT CustomerID FROM Customers WHERE EmailAddress = '' OR '1' = '1'
AND Password = '' OR '1' = '1'
SELECT userID, fname, lname from users WHERE username = '' OR '1' = '1' and password = '' OR '1' = '1'

Since the WHERE clause of the SQL statement will be satisfied by the always-true condition ‘1′ = ‘1′, the SQL statement will login you successfully.
Here is another example of a more destructive SQL injection. You may have text field for entering email address for newsletter. And what if someone put this for e-mail address.

'; DELETE FROM Customers;

The SQL now reads:

SELECT CustomerID FROM Customers WHERE EmailAddress = ”; DELETE FROM Customers;

If you really have table named Customers, all data will be erased.

2-nd Mistake : Cross-Site Scripting
Each user input must be validated. Especially if you show entered data to page in next screen.
Taking user input and returning it to the user without proper encoding causes cross-site scripting. Cross-site scripting occurs when dynamically generated Web pages display input that is not properly validated. This is also knows as XSS or CSS scripting. For cross-site scripting demonstartion, enter the following text into any form field whose value will be displayed on the page after it is posted back (for example, it can be a search filed):

<script>alert(’Some Message’)</script>

If, when the page posts back, you see a pop-up message box with the message “Some Message”, then that page is vulnerable to cross-site scripting.

How to solve it in .NET? By passing all user input through the Server.HTMLEncode() function, the cross-site scripting hole is automatically fixed.

3-hd Mistake: Enabling Debug Options in the Web.Config File
The section of the Web.Config file tells a .NET application how to deal with errors. An application should never show an end user a detailed error message. Instead, it should show a “friendly” message that says the site is having technical difficulties, and not give any technical details.

Attackers can get some valuable information from error messages. That means you have to enable detailed error messages. This is one of possible settings for tag in Web.config file.

    

HOW TO: Generate Thumbnails on the Fly using ASP.NET while uploading video file

Thursday, January 15th, 2009

In this tutorial our focus is on creating dynamic thumbnails with the help of .NET framework. Here is the scenario: We have simple aspx page with FileUpload and Button control. We will use FMPEG library, so you can have it installed before you start this example.
Here is the code of aspx page:

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








and code for web.config file:




  
    
    
  

	
	
		
		
    
	

as you can see, we save location of fmpeg and thumb path in web.config.

and here is the code which will uplaod video and save it’s thumb:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string thumbpath, thumbname, inputfile;
        string thumbargs;        

        thumbpath = ConfigurationManager.AppSettings.GetValues("thumbpath")[0];

        inputfile = thumbpath + fileUpload.FileName; 

        fileUpload.PostedFile.SaveAs( inputfile);

        thumbname = thumbpath + fileUpload.PostedFile.FileName.Substring(0, fileUpload.PostedFile.FileName.LastIndexOf(".")) + ".jpg";
        thumbargs = "-i " + inputfile + " -f image2 -ss 1 -vframes 1 -s 150x150 " + thumbname; 

        Process thumbproc = new Process();
        thumbproc = new Process();
        thumbproc.StartInfo.FileName = thumbpath = ConfigurationManager.AppSettings.GetValues("ffmpegPath")[0];
        thumbproc.StartInfo.Arguments = thumbargs;
        thumbproc.StartInfo.UseShellExecute = false;
        thumbproc.StartInfo.CreateNoWindow = false;
        thumbproc.StartInfo.RedirectStandardOutput = false;
        try
        {
            thumbproc.Start();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        thumbproc.WaitForExit();
        thumbproc.Close();
    }
}

Configuration files and ConnectionStrings

Monday, January 5th, 2009

One of the first things I’ve learned as .NET developer was using of App.config or Web.config files. Almost every application in which development I took a part had some database. Here is the brief sample how to connect to SQL Server from C#:

			string connString = @"Server=(LOCAL);Database=Northwind;User ID=sa;Password=;";
			string sqlString =  "SELECT * FROM PRODUCTS";
			DataSet ds = new DataSet();
			SqlConnection conn = new SqlConnection(connString);
			conn.Open();
			SqlDataAdapter da = new SqlDataAdapter(sqlString, conn);

			da.Fill(ds);
			dgrProducts.DataSource = ds;
			dgrProducts.DataBind();
			conn.Close();

This code will open connection to database, read table and fill data set. Then we bind data from data set to dataGrid or GridView (control named dgrProducts).
But it is not a good practice to keep connection string hard coded. Place it into configuration file.

< ?xml version="1.0" encoding="utf-8" ?>

	
	
		
	

and here is how you can read value from configuration file. It is a good practice to create new project, type of Class Library for that.

using System;
using System.Configuration;

namespace ConnectionString
{
	public class Configuration
	{
		public static string ReadConnectionString
		{
			get
			{
				return ConfigurationSettings.AppSettings.Get("ConnectionString");
			}
		}
	}
}

this sample runs on .NET 1.1 framework
For 3.0 .NET we use:

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace ConnectionString
{
    public class Configuration
    {
        protected static string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["ConnectionString"].
                    ToString();
            }
        }
    }
}

As you can see we use System.Configuration reference.

Policy Injection Application Block

Monday, December 29th, 2008

Here is how Microsoft describes it: “The Policy Injection Application Block provides a mechanism for automatically applying policies to object instances; this helps developers to better manage crosscutting concerns and maximize separation of concerns and encapsulation of behavior. Developers define the set of policies for the target classes and their members through configuration of the Policy Injection Application Block or by applying attributes to individual members of the target class.

The matching rules for each policy encompass a range of capabilities for selecting classes and members, including the name of the assembly, the namespace, the type, the member name, the member signature, attributes that are applied to the member, and more.

I’ll show you one small demo apllication which demonstrates how it works:
Create empty solution and add Class Library project called: BusinessObject. put those 2 files there: CellPhone.cs and ICellPhone.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessObject
{
    public interface ICellPhone
    {
        void SendSMS(String toPhoneMumber, String mesgSubject, String text);
        void Ring();
        void Dial(String toPhoneNumber);
        void Answer();
        void HangUp();
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessObject
{
    public class CellPhone : ICellPhone
    {
        private String phoneNumber;

        public CellPhone(String number)
        {
            phoneNumber = number;
        }

        public void SendSMS(String toPhoneMumber, String mesgSubject, String text)
        {
            Console.WriteLine("I am sending SMS to "
                + toPhoneMumber
                + ", with subject "
                + mesgSubject
                + " and text "
                + text
                );
        }
        public void Ring()
        {
            Console.WriteLine("Ringing ...");
        }

        public void Dial(String toPhoneNumber)
        {
            Console.WriteLine("I am dialing " + toPhoneNumber);
        }

        public void Answer()
        {
            Console.WriteLine("Yes plese!");
        }

        public void HangUp()
        {
            Console.WriteLine("Have a nice day.");
        }

    }
}

As you can see we have very simple class CellPhone which implements ICellPhone interface. Then, create and new project to your solution. It can be Console Application. I’ll call it client.
Add BusinessObject reference to your client project. Also you have to add some .NET references in order to use Policy Injection.
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection
Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers

Now take a look of code for Program.cs

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.Logging;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            BusinessObject.CellPhone cellPhone = PolicyInjection.Create("222333");
            cellPhone.Dial("123123");
            cellPhone.Ring();
            cellPhone.Answer();
        }
    }
}

This line is interesting:
BusinessObject.CellPhone cellPhone = PolicyInjection.Create(”222333″);
I don’t use BusinessObject.CellPhone cellPhone = new BusinessObject.CellPhone(”222333″); as you can see. If you want to use Policy Injection, this is how you create your objects. And very important rule: your object must implement some interface or must inherits class: “MarshalByRefObject“. Now you can try to “Build” and start (F5) your application, but for now there is no some differences. It works as it should be.
We have to do 2 more things. Add new project type of class library and to add App.config file to our client application.
First, add new project, type of class library, called: “CustomPIABHandler”.
Rename Class1.cs to LogCallHandler.cs and add some references to project as it is shown on the pictire below:





Now select custom handler. Click on property for Custom Handler and click type. From new PopUp window click on button “Load Assembly” and select LogCallHandler. You should navigate to your bin folder of your CustomPiabHanlder project and select CustomPIABHandler.dll.

And at last, add value for namespace matching rule. Click on Namespace Matching Rule and select it’s Property. Click on collection and add value: BusinessObject. And for the end add Reference of CustomPIABHandler to Client project.

to be continued

Enterprise Library Logging Application Block

Wednesday, December 24th, 2008

Our today discussion is about logging in .NET apps. In this demonstration I will use Visual Studio 2005 and Enterprise Library 3.1 - May 2007.

The Microsoft Enterprise Library is a set of tools and programming libraries for the Microsoft .NET Framework. Enterprise Library Logging Application Block provides you tool for perform logging into your application easily.
All you need is this using directive:

using Microsoft.Practices.EnterpriseLibrary.Logging;

and reference to: “Microsoft.Practices.EnterpriseLibrary.Logging“.
And when you want to log some method, you do it like this:

            LogEntry log = new LogEntry();
            log.Priority = 1;
            log.Message = "Executing";
            log.Categories.Add("General");
            log.Title = "Executing method name";
            Logger.Write(log);

that is all you need to put into your code. Take a look this line: “log.Categories.Add(”General”);”.
At this moment developer doesn’t know how application perform the logging. Does it use some txt file, database or something else. That is why we use App.config file to specify things like that. For editing App.config I suggest to do this edit tool: right click on App.config and select “Edit Enterpise Library Confoguration” .

When we want to use logging, 1-st we have to add “Category”. Take a look at picture!

I will call my Category “General”. Category gets name by Default, so you use “Property” window to change it’s name. After that add trace reference to your category.

For trace reference we need trace listener! So let’s add some trace listener, like this:


I selected “Flat File Trace Listener“. Choose Property for your trace listener. I select Filename to be: C:\trace.log.

After that select “Trace Reference Listener” and in it’s property window connect it to FlatFileTraceListener. Like this:



And that would be all. Now start your application and take a look at file: C:\trace.log.

We can go one step further and create our Logging class. Here is how can we do that.

Create new project in your solution, and call it Logger, type of project: Class Library, language C#. You have to add reference to you project for: “Microsoft.Practices.EnterpriseLibrary.Logging“.
and here is your class:

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace Logger
{
    public static class MyLogger
    {
        public static void Logg(String message, String category, Int32 priority, String title)
        {
            LogEntry log = new LogEntry();
            log.Priority = priority;
            log.Message = message;
            log.Categories.Add(category);
            log.Title = title;
            Logger.Write(log);
        }
    }
}

and here is how you call it from some of your method. First add reference to Logger project.

Logger.MyLogger.Logg("Exucuting method name", "General", 1, "before method start");

Business objects and WCF

Wednesday, December 24th, 2008

Let’s go further with WCF. In this post I will discuss about using business objects and WCF. For the beginning create blank solution named “SampleWCFWithBusinessObjetcs”, and put 4 projects there:
1. project type Class Library, language C#: “BusinessObjetcs
2. project type Windows Application, language C#: “Client
3. project type Console Application, language C#: “Host” and
4. project type Class Library, language C#: “Service

Project named “BusinessObjetcs” we will use to create business entites, project “Host” will host our WCF,
project “Service” will be wcf and project “Client” will be windows application for testing - our client.

Let’s start with “BusinessObjects”, create new class there called Person. Here is the code:

using System;
using System.Collections.Generic;
using System.Text;

namespace BusinessObjetcs
{
    public class Person
    {
        private Int32  m_Id;
        private String m_Name;
        private DateTime m_BirthDate;

        public Person(Int32 id, String name, DateTime birthDate)
        {
            m_Id = id;
            m_Name = name;
            m_BirthDate = birthDate;
        }

        public Int32 Id
        {
            get { return m_Id; }
            set { m_Id = value; }
        }
        public String Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }
        public DateTime BirthDate
        {
            get { return m_BirthDate; }
            set { m_BirthDate = value; }
        }
    }
}

Then let’s focus to our “Service” project. I will create an interface and one class which implements that interface: IPerson and Person. As you can imagine IPerson is an itnerface and Person is a class. Before you start, add 2 references to “Service” project. The first one is System.ServiceModel and the other is reference to project “BusinessObjects“. After that create class and interface. Here is the code:


using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using BusinessObjetcs;

namespace Service
{
[ServiceContract]
public interface IPersonService
{
[OperationContract]
Person GetPersonByID(Int32 id);

[OperationContract]
void UpdatePerson(Person person);
}
}

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using BusinessObjetcs;
using System.Collections;

namespace Service
{
    public class PersonService : IPersonService
    {
        private Dictionary m_People = new Dictionary();

        public PersonService()
        {
            m_People.Add(1, new Person(1, "Peter Petrovic", new DateTime(1977, 04, 5)));
            m_People.Add(2, new Person(2, "John Johnson", new DateTime(1987, 14, 6)));
            m_People.Add(3, new Person(3, "Mihajlo Lalic", new DateTime(1967, 24, 7)));
        }

        public Person GetPersonByID(Int32 id)
        {
            Person result = null;
            if(m_People.ContainsKey(id))
            {
                result = (Person)m_People[id];
            }
            return result;
        }

        public void UpdatePerson(Person person)
        {
            if(m_People.ContainsKey(person.Id) )
            {
                m_People[person.Id] = person;
            }
        }

    }
}

At this time you should try to build solution and if everything is OK, let’s go to create host for our wcf service.

In host project add reference to “System.ServiceModel” and to “Service” project. In “Host” project you’l find Program.cs

update this file to:

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using Service;

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {

            Type t;
            t = typeof(Service.PersonService);
            using (ServiceHost host = new ServiceHost(t))
            {
                host.Open();
                Console.WriteLine("Service started...");
                Console.ReadLine();
                host.Close();
            }
        }
    }
}

So if you run Host application our service will be started, but not so fast. We are missing one thing. end points!
Create App.config file for “Host” project and copy paste this.



  
    
      
        
          
        
      
    
    
      
        
      
    
  

Ok, I hope that is all for now, and I hope it’s works. Set your “Host” project to be startup project and press “F5″.

If you have some problems it is OK. You probably get message about: “Type ‘BusinessObjetcs.Person’ cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.”



Add an Using statement for System.Runtime.Serialization to the top of the source code file for the Person class and add Reference to System.Runtime.Serialization. Then add the DataContract attribute to the Person class declaration and the DataMember attribute to each of the properties. After that your “Person”class looks like this one:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace BusinessObjetcs
{
    [DataContract]
    public class Person
    {
        private Int32  m_Id;
        private String m_Name;
        private DateTime m_BirthDate;

        public Person(Int32 id, String name, DateTime birthDate)
        {
            m_Id = id;
            m_Name = name;
            m_BirthDate = birthDate;
        }

        [DataMember]
        public Int32 Id
        {
            get { return m_Id; }
            set { m_Id = value; }
        }

        [DataMember]
        public String Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }
        [DataMember]
        public DateTime BirthDate
        {
            get { return m_BirthDate; }
            set { m_BirthDate = value; }
        }
    }
}

Ok, now rebuild all and press “F5″. Wait for a while and then try to get “http://localhost:8081/PersonService”. Here is preview:


So, if everything works for now, let’s add Service Reference to “Client” project. I called it “PersonServiceProxy”. After adding service reference, Visual Studio created new file for you: “PersonServiceProxy.cs“. It is useful to take a look. There you can find some classes and interfaces:

Ok, now let’s finish our demo. Put some controls to your form.


and add some lines of code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadListBox();
        }

        private void LoadListBox()
        {
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {

                lstPeople.DisplayMember = "Name";
                lstPeople.ValueMember = "Id";
                lstPeople.DataSource = ws.GetPeople();
            }

        }

        private void lstPeople_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {
                PersonServiceProxy.Person _person = ws.GetPersonByID(Convert.ToInt32(lstPeople.SelectedValue));
                txtBirthDate.Text = _person.BirthDate.ToString();
                txtName.Text = _person.Name;
                txtID.Text = _person.Id.ToString();
            }

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            PersonServiceProxy.Person _person = new Client.PersonServiceProxy.Person();
            _person.BirthDate = Convert.ToDateTime(txtBirthDate.Text);
            _person.Name = txtName.Text;
            _person.Id = Convert.ToInt32(txtID.Text);
            using (PersonServiceProxy.PersonServiceClient ws = new PersonServiceProxy.PersonServiceClient())
            {
                ws.UpdatePerson(_person);
                LoadListBox();
            }
        }
    }
}



Now you have to set your solution to have multiple startup projects:
“Host” and “Client”.
When you hit “F5″ here is what you got.


try to play a litle bit with this!

Testing your web service with SOAP UI

Tuesday, December 16th, 2008

It is really fun! I hope you’ll find this interesting. The subject of this post is how to test your web service or some wcf service. You only need WSDL and SoapUI. Foe this demonstration we’ll use this service created in Windows Communication Foundation (WCF). If you start your Service you, you will see something like this in your web browser. In my case URL address is: http://localhost:3363/WebServiceHost/Service.svc

“You have created a service.

To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:

svcutil.exe http://localhost:3363/WebServiceHost/Service.svc?wsdl”

I need only this wsdl so I’ll click on this link: “http://localhost:3363/WebServiceHost/Service.svc?wsdl”.
That is the first step, remember location of your wsdl. Then start SoaupUI applcation, and under projects click “New WSDL project”.

Enter your project name, and enter URL of your WSDL and press OK.
Here is preview:

Now we will test method “FunctionAdd”. Click on Request 1 under the FunctionAdd and populate xml request.
Here is XML request:


And here is response



That is all. I find this tool “SoapUI” very interesting at all.

ASP.NET web service

Tuesday, December 9th, 2008

Creating web service in ASP.NET using Visual studio 2005 is very easy. Follow this steps:
Open Visual Studio and click New Web Site, and select ASP.NET web service.

After a second your project is created. You will find file named: “Service.cs” in your App_Code folder.
There is already default web methid implemented “Hello World”. Here is how it looks like:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[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";
    }
}

we will change this method “HelloWorld” with an other method “IntigerAddition”. So copy/paste this code into Service.cs file.

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[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 Int32 IntigerAddition(int a, int b)
    {
        return a + b;
    }
}

It is always useful to try to build your code. If everything is fine, let’s see how it works.
Right click on Service.asmx file in solution explorer and select “View in browser”. The same is if you try to click on “F5″. If there is no web.config file, you’ll be asked to put it into solution.
when web page is opened, you will see listed all services you have. For now it is only “Integer Addition” and if you click on it, you will see SOAP 1.1 and SOAP 1.2 request and response. Also you can test your web service method there if you want.


Now, get us back to solution explorer and create one web page to test this web service.
In Solution Explorer right click on solution and select Add new web site. This is image preview how to do this:

ASP.NET Web service - ASMX

ASP.NET Web service - ASMX




I’ll call this new web site project: “DemoClientForWebService”.
In your new web site project, ther is a file Default.aspx. Open it and add 2 text boxes, one Button and one more text box. Like this:

Now, we need to add web reference in our web site from web service project. Right click on web site project and select Add Web Reference.
Right click on web project and select “Add web reference”.



Then you need to specify web reference. Select “Web service in this solution”.


Then select your reference and click on button “Add reference”.



Now let’s use this reference and connect our application to web service.
Here is the code for Default.aspx page. This is code behind, file: Deafult.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using localhost; //this is how we called our web service

public partial class _Default : System.Web.UI.Page
{
    localhost.Service myWeb;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            myWeb = new Service();
        }
    }
    protected void bntGo_Click(object sender, EventArgs e)
    {
        txtResult.Text = myWeb.IntigerAddition(
                Convert.ToInt32(txtAdd1.Text),
                Convert.ToInt32(txtAdd2.Text)
                ).ToString();
    }
}

And now, let’s do some testing :)
But first be carefull. You must start your web service first.
It must be running when you try to call it from your web apps.

Windows Communication Foundation (WCF)

Sunday, November 30th, 2008

Windows Communication Foundation (WCF) (code-named “Indigo”) is a set of .NET technologies for building and running connected systems. It is a new breed of communications infrastructure built around the Web services architecture. Windows Communication Foundation, or just WCF, is a programming framework used to build applications that inter-communicate. Here is one sample which demonstrates WCF.

First create a blank solution in Visual Studio .NET 2005. I’ll call it “WSFSample”.

Then add New Project to your solution, language C#, type of project Class Library.
Let’s call this project “ServiceLibrary”. When you do this, Visual Studio cretes new file in your project. By default it is named: Class1.cs. Let’s rename it to MathService.cs. If you renamed the file name, you can see that the class name was renamed too. Add a reference to System.ServiceModel. After that let’s put some code to our class MathService. This is how our class looks like when you put few lines of code there.

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace ServiceLibrary
{
    [ServiceContract]
    public class MathService
    {
        [OperationContract]
        public Int32 AddFunction(Int32 a, Int32 b)
        {
            return a + b;
        }

        [OperationContract]
        public Int32 SquareFunction(Int32 a)
        {
            return a * a;
        }
    }
}

Now we will create Service Hosts. Add new project to your solution. Right click on solution and then select: Solution -> Add New Web Site->WCF Service.
Select WCF service template. For language select C#. Take care where is location of your WCF service because by default it is in your Document and Settings folder. I prefer to hold all project files in the root of my solution file.
I’ll call my WCF service project: “WebServiceHost”.


If you take a look at your new project, you will find a file named “Service.svc”.




add this line to file:

<% @ServiceHost Language=VB Service="ServiceLibrary.MathService" %>

As you can see there is a file named “Service.cs” under App_Code folder. Because we will not use it, you can delete it. Now, please rebuid your application and set WCF service to be Startup Project. Before we test it we need to ad some end points to Web.config and we need to add refernce to the project “ServiceLibrary”. Add this lines to Web.config




  
    
      
        
          
        
      
    
    
      
        
      
    
  

  
    
  


and add Reference in your wcf service project to “ServiceLibrary” project and press “F5″ please. You must have something like this on your screen.



Now we can create some client to consume this web service. Once again we add new project to our solution. This time it will be Windows application, language C# off course. I’ll call it “WindowsClient”.We will add 3 text boxes and one button control to our windows form. As you can imagine 2 text boxes will be for integers “a” and “b” and third text box will be result. Also we need to add “Service Reference” (not web reference as we did with *.asmx) to our wcf service. To do this right click on Windows project we’ve just created and click on “Add Service Reference”.But before that we must know URL of our WCF. We can just start with F5 our application and copy paste address from address bar of Service.svc. In my case it is: http://localhost:1157/WebServiceHost/Service.svc and this address I’ll put for “Service Reference”. Now click to add Service Reference, after you enter Service URI: http://localhost:1157/WebServiceHost/Service.svc
, your service reference name is “localhost” by default. I’ll rename it to “WCFMathService”. If you want your application to be ready for test you must check your app.config file. But Visual Studio set up all for your. Just for remember, you must specify end points element in your App.config too. Here is how it looks like:



    
        
            
                
                    
                    

                        
                    
                
            
        
        
            
        
    

.
Also you must add “System.ServiceModel” reference into your Windows client application.

Here is the code of our form which will call WCF Service when we press button on the form.
Just before I show tou you my code to say how I called controls on form:
button is called: bntCallWebService

2 text boxes txtA and txtB

The third textbox is called” txtResult

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bntCallWebService_Click(object sender, EventArgs e)
        {
            using( WCFMathService.MathServiceClient ws = new WCFMathService.MathServiceClient())
            {
                txtResult.Text = ws.AddFunction(Convert.ToInt32(txtA.Text), Convert.ToInt32(txtB.Text)).ToString();
            }
        }
    }
}


Before I finish I want to tell you to pay attention to this class: WCFMathService


And before we test this we must be carefull because our application will not work if WCF is not started. One way to do this is following: you must specify multiple startup projects: like this:



Just for case rebuild your solution and press “F5″.
Here is what I got!




heappy programming :)

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in