Wednesday, September 15, 2010

Use of Delegate and Lambda Expression

Use of Delegate and Lambda Expression


There are remarkable changes in the C# from the 1.0 Version. C# 2.0 and C# 3.0 has introduced lots of new thing they way we handle the things. Here I would like to discuss about the use of Delegates and Lambda Expression’s. Lambda Expressions has been introduced in C# 3.0 (2008).

What is Delegate?


"A delegate is a reference type that represents a method with a specific signature and return type."

Delegates allow you to pass a function to another function. As a concept, it's similar to functions as first-class types in functionally languages. A typical delegate usage is as a callback for asynchronous method calls.
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Call a Function directly - No Delegate

In most cases, when we call a function, we specify the function to be called directly. If the class MyClass has a function named Process, we'd normally call it like this (SimpleDelegateSample.cs):
namespace NoDelegate
{
    public class MyClass
    {
        public void Invoke() {
            Console.WriteLine("Invoke () begin");
            Console.WriteLine("Invoke () end");
        }
    }

    public class Test
    {
        static void Main(string[] args) {
            MyClass myClass = new MyClass();
            myClass.Invoke();
        }
    }
}

That works well in most situations. Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.

Call a Function - Delegate


namespace BasicDelegate
{
    // Declaration
    public delegate void SimpleDelegate();

    class TestDelegate
    {
        public static void MyFunc() {
            Console.WriteLine("I was called by delegate ...");
        }

        public static void Main() {
            // Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

            // Invocation
            simpleDelegate();
        }
    }
}

A delegate can be initialized with inline code, called an "anonymous method." This    method takes a string as an input parameter.
namespace ConsoleApplication1
{
    class Program
    {
        delegate void Print(string s);
        static void Main(string[] args) {

            Print p = delegate(string s) { Console.WriteLine("We are printing" + s); };
            p("Hello");

            Console.Read();
        }
    }
}

What is Lambda Expression?


A lambda expression simply defines an anonymous function. A function is something that takes one or more parameters (just as a method does)
In C# 3, the "=>" syntax is used to write a lambda expression. You place the parameters to the left of the arrow and the expression to compute to the right. The lambda expression can be assigned to delegate as shown below

namespace ConsoleApplication1
{
    class Program
    {
        delegate void Print(string s);
        static void Main(string[] args) {

            Print p = delegate(string s) { Console.WriteLine("We are printing" + s); };
            p("Hello");


            Console.WriteLine("Lambda Expression ");
            Print p1 = (x) => { Console.WriteLine("We are printing using Lambda " + x); };
                p1("Wow, it's Cool");
            Console.Read();
        }
    }
}

Below is the Sample Code which shows use of delegate and lambda expression. I have take here the Type List so that I can show the different way of using “anonymous function”

Product.cs


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

namespace ConsoleApplication
{
    class Product
    {
        public string Name { get; private set; }
        public decimal Price { get; private set; }

        public Product(string name, decimal price)
        {
            Name = name;
            Price = price;
        }

        public Product() { }
        public static List<Product> GetProductInformation()
        {
            List<Product> prod = new List<Product>();
            prod.Add(new Product("Soap", 11));
            prod.Add(new Product("Toothpaste", 10));
            prod.Add(new Product("Brush", 12));
            prod.Add(new Product("Shampoo", 10));

            return prod;
        }

        public override string ToString()
        {
            return string.Format("{0}: {1}", Name, Price);
        }

    }
}

Implemented the IComparer Interface to sort the product.

CompareProduct.cs


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

namespace ConsoleApplication
{
    class CompareProduct: IComparer<Product>
    {

        #region IComparer Members

        public int Compare(Product x, Product y) {
            return x.Name.CompareTo(y.Name);
        }

        #endregion
    }
}

Main Program

Program.cs


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

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

            Console.WriteLine("Product .......");
            foreach (Product pro in Product.GetProductInformation())
            {
                Console.WriteLine(pro.ToString());

            }

            Console.WriteLine(" Using IComparer Interface to Compare");
            List<Product> product = Product.GetProductInformation();
            product.Sort(new CompareProduct());
            Console.WriteLine();
            Console.WriteLine("Sorting 1.......");
            foreach (Product pro in product)
            {
                Console.WriteLine(pro.ToString());

            }
           
            List<Product> product1 = Product.GetProductInformation();
            Console.WriteLine();
            Console.WriteLine("Sorting 2.......");
            foreach (Product pro in product1.OrderBy(p => p.Name))
            {
                Console.WriteLine(pro.ToString());

            }
            List<Product> product2 = Product.GetProductInformation();
            product2.Sort((first, second) => first.Name.CompareTo(second.Name));
            Console.WriteLine();
            Console.WriteLine("Sorting 3.......");
            foreach (Product pro in product2)
            {
                Console.WriteLine(pro.ToString());

            }
            Predicate<Product> criteria = delegate(Product p)
            {
                return p.Price == 10;
            };

            List<Product> product3 = Product.GetProductInformation();
           List<Product> matches = product3.FindAll(criteria);
            Console.WriteLine("Finding with price 10.......");

            Action<Product> print = delegate(Product p)
            {
                Console.WriteLine(p);
            };
            matches.ForEach(print);

            Console.WriteLine("Lamda expression with Printing & Finding with price > 10.......");
            List<Product> products = Product.GetProductInformation();
            foreach (Product product4 in products.Where(p => p.Price > 10))
            {
                Console.WriteLine(product4);
            }

            Console.WriteLine("Delegate to Printing & Finding with price == 10.......");
            List<Product> finalProduct = Product.GetProductInformation();
            finalProduct.FindAll((delegate(Product p) { return p.Price == 10; })).ForEach((delegate(Product p) { Console.WriteLine(p); }));
            Console.Read();
        }
    }
}




Wednesday, June 2, 2010

How to consume/use the Web Service from Application


How to consume/use the Web Service from Application
I have come across the situation where I have the Web Service wrote during the VB 6.0 using the Soap Toolkit from the COM component, I want to consume the Web Service from the .Net Application (C# or ASP.net). There are few ways to consume the Web Service either wrote from .Net version or any other application.
Here I would like to share how to consume the Web Service in .Net application. As most of us know what is Web Service so I will not go deep into that.
I have generated the WSDL (Web Service Descriptor Language) from the COM (+) component using the SOAP Toolkit. SOAP will generate the .WSDL, .WSMX and .asp file which we can use to access the Web Service.
Step 1:
1.       Create the C# application (windows)  
2.       Add the Web Reference and Include the WSDL file under the Web Reference folder.
3.       Give the name to that Web Reference i.e. CallWS
4.       Set the Web Reference URL to something like
Now you have the Web reference added to your application. You can now access the Web Service and exposed API’s of that Web Service.
Open the form and add the button. On Button click event will access the Web Service and Its Function.
To access the Web Service we have to create the Instance from the Web Reference name.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

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

        private void btnShow_Click(object sender, EventArgs e)
        {
            CallWS.EyrAPIEnterprise call = new CallWS.EyrAPIEnterprise();

            call.Url = "http://server/virtualdirectory/services/APIEnterprise.asp";
            //If you are using the Default Credential then set this property to true.
            //call.UseDefaultCredentials = true;
            //If you are using Windows (NTLM) authetication then set the below property.
            call.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            string systemID = string.Empty;
           
            XmlDocument doc = new XmlDocument();

            string xmlString = ((System.Xml.XmlNode[])call.GetSystems())[0].OuterXml;
            doc.LoadXml(xmlString);

            textBox1.Text = xmlString;

            //You can get the value from the XML output using the XPath

        }
    }
}

How to consume the ASP.net Web Service
Now in .net we can have the Web Service written in ASP.net (.asmx) and use that in ASP.net or C# (windows) application.
First we will create the Web Service using ASP.net. You can create using the VS IDE or Simple in any text editor.
A Web Service Example
In the following example we will use ASP.NET to create a simple Web Service that converts the temperature from Fahrenheit to Celsius, and vice versa:
public class WebService : System.Web.Services.WebService {

    public WebService () {

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

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

    [WebMethod]
    public int FahrenheitToCelsius(int far)
    {
        return ((((far) - 32) / 9) * 5);
    }

    [WebMethod]
    public int CelsiusToFahrenheit(int cel)
    {
        return ((((cel) * 9) / 5) + 32);
    }
   
}
This document is saved as an .asmx file. This is the ASP.NET file extension for XML Web Services.
So when you open the Web Service from the browser using the following
You will see the below list of the methods which we made as the Web Method. This the web methods exposed by the Web Service. Now for to test, you can click on any method for e.g. CelciusToFarheneit, it will show you the next part where you can input the number and click on the Invoke button.
The Web service will then take that Input and convert the value from celcius to Far as show below in the next pic.


















How to Call the Web Service from ASP.net Application
To access the Web Service and exposed function, I am going to use the same approach as I did first time when accessing SOAP Web service. There are few other ways also but just to keep in sync I am using the same one.
You have to follow the Step 1 of the first section, and the following code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

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

        private void btnShow_Click(object sender, EventArgs e)
        {
            localhost.WebService call = new localhost.WebService();

            call.Url = "http://localhost:4834/WebSite1/WebService.asmx";
            call.UseDefaultCredentials = true;
            int far = call.CelsiusToFahrenheit(30);
            int cel = call.FahrenheitToCelsius(86);
            StringBuilder result = new StringBuilder();
            result.Append("30 Celcius = " + far + " Fahrenheit");
            result.AppendLine();
            result.Append("86 Fahrenheit = " + cel + " Celcius");
            textBox1.Text = result.ToString();

        }
    }
}





Sunday, March 21, 2010

How to Upload and Download the Files in ASP.net

How to Upload and Download the Files in ASP.net

There are number of times the user wants to upload some file and want the way to download the files from the server. ASP.net provides the FileUpload control to upload the file to the web server. It provides the easy way to upload the file to the server; the coder has not to write whole logic to read the files and writes to the web server.

Here I will mention how to use the File Upload control and upload the files to the server. I have added one more button to download the file from the server. Response Object provides the AddHeader method where you can mention the different type of Header passed to the client.

Here I have use the content-disposition and attachment attribute, where you can specify the file name which you want to pass to the client. On client web browser will prompt the user to download the file.

Client Side Code: Default.aspx

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

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>title>

head>

<body>

<form id="form1" runat="server">

<div>

<table border="1" cellspacing="0" cellpadding="0" id="tbl">

<tbody>

<tr>

<td>

<asp:FileUpload ID="FileUpload1" runat="server" BorderStyle="Solid" ForeColor="Black"

Width="329px" BackColor="White" />

td>

tr>

tbody>

table>

<table border="1" cellspacing="0" cellpadding="0" id="tblButton">

<tbody>

<tr>

<td>

<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" />

td>

<td>

<asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />

td>

tr>

tbody>

table>

div>

form>

body>

html>

Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

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

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btnUpload_Click(object sender, EventArgs e)

{

String filePath = FileUpload1.FileName;

String strFileName = "";

if (FileUpload1.PostedFile != null)

{

HttpPostedFile file = FileUpload1.PostedFile;

//Get the size of the file so you can read the file

int contentLen = file.ContentLength;

if (contentLen > 0)

{

strFileName = Path.GetFileName(filePath);

file.SaveAs(Server.MapPath(strFileName));

}

}

}

protected void btnDownload_Click(object sender, EventArgs e)

{

string fileName = "Amazon.txt";

string filePath = Server.MapPath(fileName);

Response.Clear();

Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);

Response.ContentType = "application/octet-stream";

Response.WriteFile(filePath);

Response.Flush();

Response.End();

}

}

Hope this will guide how to upload and download the files from the web server.