Showing posts with label wcf. Show all posts
Showing posts with label wcf. Show all posts

Wednesday, September 25, 2013

transport layer security

// transport layer security -client side

ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
s.ClientCredentials.UserName.UserName = "windows";
s.ClientCredentials.UserName.Password = "omomsandeepkaran";
Response.Write(s.GetData()); 

// web config

<system.serviceModel>

<bindings>
    <wsHttpBinding>
       <binding name ="narang">
        <security mode ="Transport">
          <transport clientCredentialType ="Basic">

          </transport>
       </security>
      </binding>
     </wsHttpBinding>
</bindings>

<services>

<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" bindingConfiguration ="narang" contract="IService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically.
-->
<identity>
   <dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

==========================
//Transport layer security 
<wsHttpBinding>
<binding name ="narang">
<security mode ="Transport">
<transport clientCredentialType ="Basic">

</transport>
</security>
</binding>
</wsHttpBinding>
// Attach with EndPoint
<endpoint address="" binding="wsHttpBinding" bindingConfiguration ="narang" contract="IService">

step-2

Go to IIS --create certificate

step-3
Add HTTPS and assign ceritificate name

step-4 netsh http show sslcert
netsh http delete sslcert ipport=0..0.0.0:8080

netsh http add sslcert ipport=0.0.0.0:8080 certhash=2b626efa63a083bbf868d2b8dfc2bcab263d9857 appid={4B04E6AD-E432-40EB-9A11-9081F5DDEC88}

Monday, September 23, 2013

Exception Handling in WCF using Fault Contract

//Create Services Contract (Interface)
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService   //name of interface
{

[OperationContract]        // Name of Method
[FaultContract(typeof(MyReason))]
string GetData(int value);

}

[DataContract]

public class MyReason
{
[DataMember]
private string Reason;
public string MyCause { get; set; }
}

//class to implement 
Services Contract 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient; 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.

public class Service : IService
{
  SqlConnection con;
  string ret;
  public string GetData(int r)
   {
     try
      {
         con = new SqlConnection("initial catalog=Tblname;data source=Dbname;integrated security=yes");
SqlCommand cmd = new SqlCommand("select name from student where seat_no=" + r + "", con);
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
bool b = rd.Read();
if (b == false)
{
ret = null;
}
else
{
ret = rd["name"].ToString();
}

}

catch (Exception e1)
{
MyReason m = new MyReason();
m.MyCause = "he has internal pain in stomach";
throw new FaultException<MyReason>(m);
}
finally
{
con.Close();

}

return ret;
}
}

//Call 
That Services Client Side
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;    //First Client Add ServiceModel NameSpace

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

}
protected void Button1_Click(object sender, EventArgs e)
{
try
 {
   int s1 = Convert.ToInt32(TextBox1.Text);
ServiceReference1.ServiceClient s=new 
ServiceReference1.ServiceClient();
string y = s.GetData(s1);
if (y == null)
{
Label1.Text = "Rec not found";
}
else
{
  Label1.Text = y;
}
}
catch (FaultException<ServiceReference1.MyReason> m)
{

Label1.Text = m.Detail.MyCause; //
Services Error Here
}
}
}
//

Sunday, June 16, 2013

WCF+LINQ(Integration)

WCF+LINQ(Integration)
//BL.CS

using System;
using System.Data.Linq.Mapping;
using System.Runtime.Serialization;

[DataContract]
[Table(Name="student")]
public class BL
{
[DataMember]
[Column(Name="seat_no",IsPrimaryKey=true)]
public int sno {get;set;}

[DataMember]
[Column(Name="name")]
public string sn { get; set; }
}
//DAL.CS

using System;
using System.Data.Linq;
using System.Collections.Generic;
using System.Linq;
public class DAL
{
Table<BL> b2 = null;

public List<BL> Show_Data()
{
List<BL> st = new List<BL>(); //For manipulation
// For insert,update,delete
using (DataContext dt = new DataContext("initial catalog=cac;integrated security=yes;data source=WINDOWS-PC\\SQLEXPRESS"))
{
st = dt.GetTable<BL>().ToList();
}
return st;

}

public int save(BL b)
{
using (DataContext dt = new DataContext("initial catalog=cac;integrated security=yes;data source=WINDOWS-PC\\SQLEXPRESS"))
{
b2 = dt.GetTable<BL>(); //Call By rererence
b2.InsertOnSubmit(b);
dt.SubmitChanges();
return 1;

}

}
}

//Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Runtime.InteropServices;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
public List<BL> Get_Student()
{

DAL d = new DAL();
return d.Show_Data();
}

public int Save_data(BL b)
{
DAL d2 = new DAL();
d2.save(b);
return 1;

}
}
/IService

//using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
[OperationContract]
List<BL> Get_Student();

[OperationContract]
int Save_data(BL b);
}

//AT CLIENT SIDE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

}
protected void Button2_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient s = new ServiceReference1.ServiceClient();
GridView1.DataSource = s.Get_Student();
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
int r = Convert.ToInt32(TextBox1.Text);
string n = TextBox2.Text;

ServiceReference1.BL a = new ServiceReference1.BL();
a.sno = r;
a.sn = n;

ServiceReference1.ServiceClient s2 = new ServiceReference1.ServiceClient();
int f=s2.Save_data(a);
if (f == 1)
{
GridView1.DataSource = s2.Get_Student();
GridView1.DataBind();
}
}
}

Wednesday, April 17, 2013

Why Use WCF


Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types.

Its forthcoming microsoft technology for service-oriented applications, is designed to address these requirements. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it.
Lets me share my project live example scenario to understand WCF working in practical computing world.
To get a sense WHEN to use WCF let me engage you in a problems that WCF addresses, suppose that a car rental firm decides to create a new application for reserving cars. Since this application will run on Windows, the firm chooses to build it on version 2.0 of the .NET Framework. The architects of this rental car reservation application know that the business logic it implements will need to be accessible by other software running both inside and outside their company. Accordingly, its decided to build it in a service-oriented style, with the application’s logic exposed to other software through a well-defined set of services. To implement these services, and thus communicate with other software, the new application will use WCF.
Below is architecture of proposed system. 


Over its lifetime, the rental car reservation application will likely be accessed by a range of other applications. When it’s designed, however,its thought  of the rental car reservation application know that its business logic will be accessed, as shown in the figure above, by three other kinds of software

1) A call center client application running on Windows desktops that will be used by employees in the organization’s call center. Created specifically for the new reservations system, this application will also be built using the .NET Framework and WCF. (In some sense, this application isn’t truly distinct from the new rental car reservation application, since its only purpose is to act as a client for the new system. Still, from a service-oriented perspective, it’s just another client for the reservation system’s business logic.)

2) An existing reservation application built on a J2EE server running on a non-Windows system. Due to a recent merger with another car rental firm, this existing system must be able to access the new application’s logic to provide customers of the merged firms with a unified experience. Partner applications running on a variety of platforms, each located within a company that has a business arrangement with the car rental firm. Partners might include travel agencies, airlines and others that have a business requirement to make car rental reservations.

The diverse communication requirements for the new rental car reservation application aren’t simple. For interactions with the call center client application, for instance, performance is paramount, while interoperability is straightforward, since both are built on the .NET Framework.
For communication with the existing J2EE-based reservation application and with the diverse partner applications, however, interoperability becomes the highest goal. The security requirements are also quite different, varying across local Windows-based applications, a J2EE-based application running on another operating system, and a variety of partner applications coming in across the Internet.
Even transactional requirements might vary, with only the internal applications being allowed to make transactional requests.
So the question is how can we in given  diverse business and technical requirements be met without exposing the creators of the new application to unmanageable complexity? The answer to this question is WCF. Designed for exactly this kind of diverse but realistic scenario, WCF will be the default technology for Windows applications that expose and access services.So here i will introduce to  an introduction to WCF, examining what it provides and showing how it’s used. Throughout this introduction, the scenario just described will serve as an example. The goal is to make clear what WCF is, show what problems it solves, and illustrate how it solves those problems.
Addressing the Problem: WHAT WCF Provides:
The foundation for new Windows-based applications is the .NET Framework. Accordingly, WCF is implemented primarily as a set of classes on top of the .NET Framework’s Common Language Runtime (CLR). Because it extends their familiar environment, WCF allows developers who create object-oriented applications using the .NET Framework today to also build service-oriented applications in a familiar way.


he figure above shows a simple view of a WCF client and service. The two interact via SOAP, WCF’s native protocol, so even though the figure shows both parties built on WCF, this certainly is not required.  WCF addresses a range of problems for communicating applications.
1) Unification of existing .NET Framework communication technologies
2) Support for cross-vendor interoperability, including reliability, security, and transactions.
Let us try to understand each benefit of WCF one by one below;
A) Unification of Microsoft’s Distributed Computing Technologies.
Think about the team of developers implementing the rental car reservation application described earlier. In the absence of WCF, this team would need to choose the right distributed technology from the multiple choices offered by the .NET Framework. Yet given the diverse requirements of this application, no single technology would fit the bill. Instead, the application would probably use multiple existing .NET technologies. For example:

1) ASMX, also called ASP.NET Web Services, would be an option for communicating with the J2EE-based existing reservation application and with the partner applications across the Internet. Given that basic Web services are supported today on most platforms, this would likely be the most direct way to achieve cross-vendor interoperability.

2) .NET Remoting is a natural choice for communication with the call center application, since both are built on the .NET Framework. Remoting is designed expressly for .NET-to-.NET communication, so it would offer the best performance for this situation.

3) Enterprise Services (the successor to COM+) might be used by the rental car reservation application for things such as managing object lifetimes and defining distributed transactions. These functions could be useful in communicating with any of the other applications in this scenario, but Enterprise Services supports only a limited set of communication protocols.

4) Web Services Enhancements (WSE) could be used along with ASMX to communicate with the J2EE-based reservation application and with the partner applications. Because it implements more recently defined Web services agreements, known collectively as the WS-* specifications, WSE can allow better security and more, as long as all applications involved support compatible versions of these new specifications.

5) Microsoft Message Queuing (MSMQ) could be used to communicate with Windows-based partner applications that weren’t always available. The persistent queuing that MSMQ provides is typically the best solution for intermittently connected applications.
If it were built on today’s .NET Framework, the rental car reservation application would need to use more than one of these communication technologies, and maybe even all five, to meet its requirements. Although this is technically possible, the resulting application would be complex to implement and challenging to maintain. A better solution is needed.

With WCF, this solution is at hand. As the figure above shows it also compliments WHY to use it. WCF can be used for all the situations described above. Accordingly, the rental car reservation application can use this single technology for all its application-to-application communication. Here’s how WCF addresses each of these requirements:
1) Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.

2) To allow optimal performance when both parties in a communication are built on WCF, the wire encoding used in this case is an optimized binary version of SOAP. Messages still conform to the data structure of a SOAP message, referred to as its Infoset, but their encoding uses a binary representation of that Infoset rather than the standard angle-brackets-and-text format of XML. Using this option would make sense for communicating with the call center client application, since it’s also built on WCF, and performance is a paramount concern.

3) Managing object lifetimes, defining distributed transactions, and other aspects of Enterprise Services are now provided by WCF. They are available to any WCF-based application, which means that the rental car reservation application can use them with any of the other applications it communicates with.

4) Because it supports a large set of the WS-* specifications, WCF helps provide reliability, security, and transactions when communicating with any platform that also supports these specifications.

5) WCF’s option for queued messaging, built on MSMQ, allows applications to use persistent queuing without needing to use another set of application programming interfaces.
The result of this unification is greater functionality and significantly reduced complexity. Because WCF allows an application to address all the communication requirements listed earlier, it can easily support scenarios that were difficult (or even impossible) with the collection of technologies that preceded it. While Microsoft will still support these earlier technologies, most new applications that would previously have used any of them will instead be built on WCF.
B) Interoperability with Other Web Services Platforms.
Enterprises today typically have systems and applications that were purchased from a range of vendors. In the rental car application, for instance, communication is required with various other software applications written in various languages and running on various operating systems. This kind of diversity is the reality in most organizations, and it will remain so for the foreseeable future.
Because WCF’s fundamental communication mechanism is SOAP, WCF-based applications can communicate with other software running in a variety of contexts. As shown in the figure below, an application built on WCF can interact with all of the following:

1) WCF-based applications running in a different process on the same Windows machine

2) WCF-based applications running on another Windows machine

3) Applications built on other technologies, such as J2EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems, such as Sun Solaris, IBM z/OS, or Linux.


To allow more than just basic communication, WCF implements Web services technologies defined by the WS-* specifications. All of these specifications were originally defined by Microsoft, IBM, and other vendors working together. As in the figure below, these specifications address several areas, including basic messaging, security, reliability, transactions, and working with a service’s metadata



WCF supports all the specifications shown in this figure. Grouped by function, those specs are:

1) Messaging: SOAP is the foundation protocol for Web services, defining a basic envelope containing a header and a body. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. The Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages based on the XML-binary Optimized Packaging (XOP) specification.

2) Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to directly request descriptive information about a service, such as its WSDL and its policies, via SOAP.

3) Security: WS-Security, WS-Trust and WS-SecureConversation all define additions to SOAP messages for providing authentication, data integrity, data privacy and other security features.

4) Reliability: WS-ReliableMessaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more SOAP intermediaries must be traversed.

5) Transactions: Built on WS-Coordination, WS-AtomicTransaction allows using two-phase commit transactions with SOAP-based exchanges
The rental car reservation application would likely use several of these more advanced technologies. For example, WS-Addressing is essential whenever SOAP is running over a protocol other than HTTP, which might be the case for communication with the .NET
Going back to our problem with designing framework-based call center client application, below we see how these specifications addressed the concerns;
WCF relies on WS-Policy and WS-MetadataExchange to discover whether the system it’s communicating with is also using WCF and for other things.
Reliable communication is essential for most situations, so it’s likely that WS-ReliableMessaging would be used to interact with many of the other applications in this scenario.
Similarly, WS-Security and the related specifications might also be used for communication with one or more of the applications, since all would require some kind of security.
For the applications that are allowed to use transactions with the rental car reservation system, WS-AtomicTransaction would be essential. Finally, MTOM could be used whenever an optimized wire format made sense, and both sides of the communication supported this option.

The key point is that WCF implements interoperable Web services, complete with cross-platform security, reliability, transactions, and more. To avoid paying an unnecessary performance penalty, WCF-to-WCF communication is optimized, but all other communication uses standard Web services protocols on the wire.

Wednesday, February 27, 2013

How to Send Large Amount Of Data in WCF(Streaming),Upload/Download Files Over HTTP



I have tried to transfer large files over HTTP to/from WCF, but I have faced problems in that I was not able to upload files more than 45 KB in size, I have tried many configuration setting combinations and finally succeeded in transferring large files (I have tested up to 1GB on IE6).

To transfer large files using “WCF service + HTTP”, we can use the following types of bindings:
1.  wsHttpBinding
2.  basicHttpBinding   

        In wsHttpBinding, we can set the transfermode attribute as Buffered, but there is a disadvantage in using this approach for large files, because it needs to put the entire file in memory before uploading/downloading, A large buffer is required on both the web client and the WCF service host. However, this approach is very useful for transferring small files, securely.
In basicHTTPBinding we can use the transfermode as Streamed so that the file can be transferred in the form of chunks. We have to ensure additional security mechanisms for transferring chunks. The security mechanisms are not explained in this posting.

Create WCF Contract with Use Of Interface:-
Create a new “WCF Service” project. Create a new service with the name TransferService. Now we will see an interface file “ITransferService” and a class file TransferService.csITransferService should have two methods, one for upload and one for download.

WCF Service Sample Interface Code:
[ServiceContract]
public interface ITransferService
{
    [OperationContract]
    RemoteFileInfo DownloadFile(DownloadRequest request);

    [OperationContract]
     void UploadFile(RemoteFileInfo request);
}
[MessageContract]
public class DownloadRequest
{
    [MessageBodyMember]
    public string FileName;
}

[MessageContract]
public class RemoteFileInfo : IDisposable
{
    [MessageHeader(MustUnderstand = true)]
    public string FileName;

    [MessageHeader(MustUnderstand = true)]
    public long Length;

    [MessageBodyMember(Order = 1)]
    public System.IO.Stream FileByteStream;

    public void Dispose()
    {
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }  
}

WCF Service Sample Interface Implementation Code:-
public RemoteFileInfo DownloadFile(DownloadRequest request)
{
    RemoteFileInfo result = new RemoteFileInfo();
    try
    {
   string filePath = System.IO.Path.Combine(@"c:\Uploadfiles", request.FileName);
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

        // check if exists
        if (!fileInfo.Exists)
    throw new System.IO.FileNotFoundException("File not found",request.FileName);
        // open stream
        System.IO.FileStream stream = new System.IO.FileStream(filePath,
                  System.IO.FileMode.Open, System.IO.FileAccess.Read);
            // return result
            result.FileName = request.FileName;
            result.Length = fileInfo.Length;
            result.FileByteStream = stream;
        }
        catch (Exception ex)
        {
        }
        return result;
    }
    public void UploadFile(RemoteFileInfo request)
    {
        FileStream targetStream = null;
        Stream sourceStream =  request.FileByteStream;
        string uploadFolder = @"C:\upload\";
        string filePath = Path.Combine(uploadFolder, request.FileName);
        using (targetStream = new FileStream(filePath, FileMode.Create,
                              FileAccess.Write, FileShare.None))
        {
            //read from the input stream in 65000 byte chunks
            const int bufferLen = 65000;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
            {
                // save to output stream
                targetStream.Write(buffer, 0, count);
            }
            targetStream.Close();
            sourceStream.Close();
        }
    }

Changing in Web.Config File in Wcf (Server Side):-

The following settings are most important for transferring large data:

·         ReaderQuotas: We have to set the maximum sizes (this depends on our specific requirement). Here I have set to the maximum values where we can transfer data up to 2GB, as per MSDN/www documentation.   <binding name="TransferService"
maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed" > <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>

 A word about my experiences here: I have used the above settings alone and received the error “400 bad request” from the WCF service on the browser.This error may occur due to many reasons: the reasons might be configuration mismatch between the web server and the WCF service, or an exception raised in the WCF service etc.

BindingConfiguration: This attribute is not available by default in the endpoint section. When I added this attribute, the “400 bad request” exception disappeared and the upload and download executed well.

<endpoint address="" binding="basicHttpBinding"
          bindingConfiguration="TransferService"
          contract ="ITransferService">
</endpoint>
Along with the above settings, HttpRuntime settings should also be placed in the web.config file as below:
<httpRuntime maxRequestLength="2097151" //Maxvalue
     useFullyQualifiedRedirectUrl="true" executionTimeout="14400"   />  //can be configured as per the requirement.

Create Web Site Or Client or Calling To Services :-

Create a new “web site” project. Place a link button and a file upload control on the web page. Create one more button to upload the file. Add the reference of the WCF service in “Service References” with a suitable name, currently FileTransferServiceReference.

The following changes need to be done in web.config after adding the service reference: 

<binding name="BasicHttpBinding_ITransferService" closeTimeout="04:01:00" openTimeout="04:01:00" receiveTimeout="04:10:00" sendTimeout="04:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed" useDefaultWebProxy="true">

<readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />

<security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" />

<message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding>

Increase the values for the readerQuotas attribute and also increase the timeout settings.  

The code-behind of the page is the following:

protected void LinkButton1_Click(object sender, EventArgs e)
 {
     try
       {
 FileTransferServiceReference.ITransferService clientDownload = new TransferServiceClient(); 
 FileTransferServiceReference.DownloadRequest requestData = new DownloadRequest(); 
 FileTransferServiceReference.RemoteFileInfo fileInfo = new RemoteFileInfo(); requestData.FileName = "codebase.zip";
 fileInfo = clientDownload.DownloadFile(requestData);
 Response.BufferOutput = false; // to prevent buffering 
 byte[] buffer = new byte[6500]; 
 int bytesRead = 0;
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.ClearHeaders();
 HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + requestData.FileName);
 bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length); 
 while (bytesRead > 0)
   { 
 // Verify that the client is connected. 
      if (Response.IsClientConnected)
        {
       Response.OutputStream.Write(buffer, 0, bytesRead); // Flush the data to the HTML output. 
       Response.Flush(); 
       buffer = new byte[6500]; 
       bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);
       } 
      else    {        bytesRead = -1;       }

    }
 }
   catch (Exception ex) 
      { // Trap the error, if any.
         System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
      }
    finally
      { 
       Response.Flush(); 
       Response.Close();
       Response.End();  
       System.Web.HttpContext.Current.Response.Close();
       }
   } 
 protected void Button1_Click(object sender, EventArgs e)
  {
   if (FileUpload1.HasFile) 
   {
System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileUpload1.PostedFile.FileName); FileTransferServiceReference.ITransferService clientUpload = new FileTransferServiceReference.TransferServiceClient(); FileTransferServiceReference.RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();           
using (System.IO.FileStream stream = new System.IO.FileStream (FileUpload1.PostedFile.FileName,                        System.IO.FileMode.Open, System.IO.FileAccess.Read))
  {   
     uploadRequestInfo.FileName = FileUpload1.FileName;
     uploadRequestInfo.Length = fileInfo.Length;
     uploadRequestInfo.FileByteStream = stream;
    clientUpload.UploadFile(uploadRequestInfo);
   //clientUpload.UploadFile(stream);
    }
  } 
}
Now build both the IDE projects and execute the web server project. This still works only for less than 50KB! If you select a large file to be uploaded, you will see a blank webpage.
Now, you need to add one more attribute, MaxRequestLength, in the httpRuntime section in thesystem.web configuration file section, as below:

<httpRuntime maxRequestLength="2097150"/>

That is it! Now one can download and upload large files (I have tested up to ~1GB) from an IE6 browser over HTTP to a WCF service. 

Ref:  http://www.codeproject.com