Upload Documents To Server From Windows Application Using WCF
Requirement : A WCF Service in a web application ,windows application
First take a web application and add a WCF Web service .
Name of the service is UploadPdf.svc
Property Class is RemoteFileInfo.cs
Now write the following code into the inter face IUploadPdf.cs:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
public interface IUploadPdf
{
[OperationContract()]
Int16 UploadFile(RemoteFileInfo request);
}
{
[OperationContract()]
Int16 UploadFile(RemoteFileInfo request);
}
Now Implemented Class Name UploadPdf.cs code details :("Pdf_Documents" this folder should be on the application path)
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Web.Hosting;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UploadPdf" in code, svc and config file together.
public class UploadPdf : IUploadPdf
{
short IUploadPdf.UploadFile(RemoteFileInfo request)
{
try
{
String filename = "";
String filePath = "";
filename = request.FileName;
filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Pdf_Documents");
File.WriteAllBytes(filePath + "\\" + request.FileName, request.FileByteStream);
if (File.Exists(filePath + "\\" + request.FileName))
{
return 1;
}
else
{
return 0;
}
}
catch (Exception )
{
throw new NotImplementedException();
}
}
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Web.Hosting;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UploadPdf" in code, svc and config file together.
public class UploadPdf : IUploadPdf
{
short IUploadPdf.UploadFile(RemoteFileInfo request)
{
try
{
String filename = "";
String filePath = "";
filename = request.FileName;
filePath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Pdf_Documents");
File.WriteAllBytes(filePath + "\\" + request.FileName, request.FileByteStream);
if (File.Exists(filePath + "\\" + request.FileName))
{
return 1;
}
else
{
return 0;
}
}
catch (Exception )
{
throw new NotImplementedException();
}
}
Now the property class RemoteFileInfo.cs code is as follows :
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Web;
/// <summary>
/// Summary description for RemoteFileInfo
/// </summary>
public class RemoteFileInfo
{
[MessageHeader(MustUnderstand = true)]
public string FileName;
[MessageHeader(MustUnderstand = true)]
public long Length;
[MessageBodyMember(Order = 1)]
public byte[] FileByteStream;
}
Web,config file should be :
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings >
<basicHttpBinding>
<binding name="BasicHttpBinding_Upload" closeTimeout="00:10:00"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services >
<service name="UploadPdf" >
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Upload"
contract="IUploadPdf"/>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Now Create a windows application and add WCF service to this project and on page load write the following code place a pdf file on debug folder :
SRUP is the Service Reference name
Imports System.IO
Public Class Form1
Dim objup As New SRUP.UploadPdfClient()
Dim objfile As New SRUP.RemoteFileInfo()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim fileList As IList = New ArrayList()
Dim fileEntries As String() = Directory.GetFileSystemEntries("D:\MergePdf")
Dim extntion As String
Dim fileNm As String
For Each fileNm In fileEntries
objfile.FileName = Path.GetFileName(fileNm)
extntion = Path.GetExtension(fileNm)
If extntion = ".pdf" Then
objfile.FileByteStream = GetBytesFromUrl(fileNm)
objup.UploadFile(objfile)
End If
Next
End Sub
Public Shared Function GetBytesFromUrl(ImageFilePath As String) As Byte()
Dim _tempByte As Byte() = Nothing
If String.IsNullOrEmpty(ImageFilePath) = True Then
Throw New ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath")
Return Nothing
End If
Try
Dim _fileInfo As New System.IO.FileInfo(ImageFilePath)
Dim _NumBytes As Long = _fileInfo.Length
Dim _FStream As New System.IO.FileStream(ImageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim _BinaryReader As New System.IO.BinaryReader(_FStream)
_tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes))
_fileInfo = Nothing
_NumBytes = 0
_FStream.Close()
_FStream.Dispose()
_BinaryReader.Close()
Return _tempByte
Catch ex As Exception
'#########
Throw ex
'#########
Return Nothing
End Try
End Function
Now app.config file would be like that :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IUploadPdf" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="Service hosted address"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IUploadPdf"
contract="SRUP.IUploadPdf" name="BasicHttpBinding_IUploadPdf" />
</client>
</system.serviceModel>
</configuration>
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Web;
/// <summary>
/// Summary description for RemoteFileInfo
/// </summary>
public class RemoteFileInfo
{
[MessageHeader(MustUnderstand = true)]
public string FileName;
[MessageHeader(MustUnderstand = true)]
public long Length;
[MessageBodyMember(Order = 1)]
public byte[] FileByteStream;
}
Web,config file should be :
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings >
<basicHttpBinding>
<binding name="BasicHttpBinding_Upload" closeTimeout="00:10:00"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services >
<service name="UploadPdf" >
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Upload"
contract="IUploadPdf"/>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Now Create a windows application and add WCF service to this project and on page load write the following code place a pdf file on debug folder :
SRUP is the Service Reference name
Imports System.IO
Public Class Form1
Dim objup As New SRUP.UploadPdfClient()
Dim objfile As New SRUP.RemoteFileInfo()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim fileList As IList = New ArrayList()
Dim fileEntries As String() = Directory.GetFileSystemEntries("D:\MergePdf")
Dim extntion As String
Dim fileNm As String
For Each fileNm In fileEntries
objfile.FileName = Path.GetFileName(fileNm)
extntion = Path.GetExtension(fileNm)
If extntion = ".pdf" Then
objfile.FileByteStream = GetBytesFromUrl(fileNm)
objup.UploadFile(objfile)
End If
Next
End Sub
Public Shared Function GetBytesFromUrl(ImageFilePath As String) As Byte()
Dim _tempByte As Byte() = Nothing
If String.IsNullOrEmpty(ImageFilePath) = True Then
Throw New ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath")
Return Nothing
End If
Try
Dim _fileInfo As New System.IO.FileInfo(ImageFilePath)
Dim _NumBytes As Long = _fileInfo.Length
Dim _FStream As New System.IO.FileStream(ImageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)
Dim _BinaryReader As New System.IO.BinaryReader(_FStream)
_tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes))
_fileInfo = Nothing
_NumBytes = 0
_FStream.Close()
_FStream.Dispose()
_BinaryReader.Close()
Return _tempByte
Catch ex As Exception
'#########
Throw ex
'#########
Return Nothing
End Try
End Function
Now app.config file would be like that :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IUploadPdf" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="Service hosted address"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IUploadPdf"
contract="SRUP.IUploadPdf" name="BasicHttpBinding_IUploadPdf" />
</client>
</system.serviceModel>
</configuration>