Using wcf service we can perform upload and download a File
[ServiceContract]
public interface IService1
{
[OperationContract]
ZipResponse
ZipUpload(ZipRequest requests);
}
ZipResposne and ZipRequests
are messagecontracts
[MessageContract]
public class ZipRequest
{
[MessageHeader(MustUnderstand=true)]
public string DataInformation;
[MessageBodyMember(Order
= 1)]
public
System.IO.Stream Data;
}
[MessageContract]
public class ZipResponse
{
[MessageHeader(MustUnderstand
= true)]
public string ResponsetoClient;
[MessageBodyMember(Order
= 1)]
public bool Response;
}
Service
Implementation:
public class Service1 : IService1
{
public ZipResponse ZipUpload(ZipRequest
request)
{
bool
isError = false;
string[]
FileDetails = request.DataInformation.Split('@');
string
name = FileDetails[0];
string
path = FileDetails[1];
string
code = FileDetails[2];
DateTime
uploadtime = DateTime.Now;
string uploadpath = ConfigurationSettings.AppSettings["FileUploadLocation"] + path;
//CHECK
WHETHER DIRECTORY IS EXIST OR NOT
if
(!Directory.Exists(uploadpath))
{
Directory.CreateDirectory(uploadpath);
}
string
uploadLocation = Path.Combine(uploadpath,
name);
//CREATE
THE UPLOADED FILE
FileStream
fs = null;
try
{
fs = File.Create(uploadLocation);
byte[]
buffer = new byte[65000];
int
read = 0;
while
((read = request.Data.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, read);
}
}
catch
(Exception ex)
{
#region log the
error
string
errorpath = ConfigurationSettings.AppSettings["ErrorPath"];
System.IO.StreamWriter sw;
sw = System.IO.File.AppendText(errorpath);
sw.WriteLine(DateTime.Now.ToString("dd-MM-yy
hh:mm:ss tt") + "
:===============================================================");
sw.WriteLine(ex.Message);
sw.WriteLine(ex.StackTrace);
sw.WriteLine("");
sw.Close();
#endregion
isError = true;
}
finally
{
if
(fs != null)
{
fs.Close();
fs.Dispose();
}
if
(request.Data != null)
{
request.Data.Close();
request.Data.Dispose();
}
if
(isError)
{
Exception
newEx = new Exception("Exception Thrown By Upload");
throw
newEx;
}
if
(!isError)
{
}
}
ZipResponse
response = new ZipResponse();
response.ResponsetoClient = "kasibabu";
response.Response = true;
return
response;
}
public List<string> GetValues(int
x)
{
List<string> list = new
List<string>();
list.Add("abcd");
list.Add("efgh");
return
list;
}
}
App.confile:
<appSettings>
<add
key="ErrorPath" value="C:\DSMLog\ErrorLog" />
<add
key="FileUploadLocation" value="E:\todays\"/>
</appSettings>
<system.serviceModel>
<services>
<service
name="RealtimeWCFService.Service1" behaviorConfiguration="RealtimeWCFService.Service1Behavior">
<host>
<baseAddresses>
<add
baseAddress = "http://localhost:8731/Design_Time_Addresses/RealtimeWCFService/Service1/" />
</baseAddresses>
</host>
<!-- Service
Endpoints -->
<!-- Unless fully
qualified, address is relative to base address supplied above -->
<endpoint
address ="" binding="basicHttpBinding" contract="RealtimeWCFService.IService1">
<!--
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>
<!-- Metadata
Endpoints -->
<!-- The Metadata
Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint
does not use a secure binding and should be secured or removed before
deployment -->
<endpoint
address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior
name="RealtimeWCFService.Service1Behavior">
<!-- 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>
AT
client side
At Client:
namespace DSMClients
{
public partial class Form1 : Form
{
bool
isMatched = true;
SqlConnection
DBConnection = new SqlConnection();
ServiceReference1.Service1Client proxy = new
ServiceReference1.Service1Client();
public
Form1()
{
InitializeComponent();
vancodelbltxt.Text = ConfigurationSettings.AppSettings["vancode"];
DBConnection.ConnectionString
= ConfigurationSettings.AppSettings["DBConnection"];
}
private
void btnUpload_Click(object
sender, EventArgs e)
{
FileUploadMethod();
}
private
void FileUploadMethod()
{
if
(isMatched)
{
bool
uploadresponse = false,updated = false,dataupload = false;
string[]
FileInfo = GetFileInfo();
try
{
if
(FileInfo[0] != null && FileInfo[1] != null)
{
dataupload = true;
string filename = FileInfo[0];
string filepath = FileInfo[1];
string DataInformationrmation;
DataInformationrmation
= filename;
DataInformationrmation
= DataInformationrmation + "@" +
filepath.Replace(ConfigurationSettings.AppSettings["uploadpath"], "").Trim();
DataInformationrmation
= DataInformationrmation + "@" +
vancodelbltxt.Text;
string DataPath = Path.Combine(filepath,
filename);
var Data = new FileStream(DataPath, FileMode.Open);
string responseFrom = proxy.ZipUpload(DataInformationrmation,
Data,out uploadresponse);
if (uploadresponse)
{
updated =
UpdateFileStatus(filename, filepath, "Data");
MessageBox.Show("uploaded
succefully");
}
}
else
{
dataupload = false;
}
}
catch
(Exception ex)
{
//writelog.ErrorLog(ex);
global::System.Windows.Forms.MessageBox.Show("Error
Occured");
//
MakeAllVisible();
}
}
else
{
MessageBox.Show(" VAN NO Doesn't Matched. Please check it");
}
}
private
string[] GetFileInfo()
{
SqlCommand
getFileInfo = new SqlCommand();
getFileInfo.Connection =
DBConnection;
getFileInfo.CommandTimeout = 600;
getFileInfo.CommandType = CommandType.StoredProcedure;
getFileInfo.CommandText = "getFileInfo";
string[]
FileInfo = { null, null
};
try
{
if
(DBConnection.State == ConnectionState.Closed)
{
DBConnection.Open();
}
SqlDataReader
reader = getFileInfo.ExecuteReader();
while
(reader.Read())
{
if
(reader.HasRows == true)
{
FileInfo[0] =
reader[0].ToString();
FileInfo[1] =
reader[1].ToString();
}
}
reader.Close();
}
catch
(Exception ex)
{
//
ErrorDisplay("Error Occured. See Error in C:\\DSMLog\\ErrorLog");
//writelog.ErrorLog(ex);
// MakeAllVisible();
MessageBox.Show(ex.Message.ToString());
}
finally
{
if
(DBConnection.State == ConnectionState.Open)
{
DBConnection.Close();
}
}
return
FileInfo;
}
private
bool UpdateFileStatus(string
name, string path, string
filetpe)
{
bool
isUpdated;
SqlCommand
updateFileStatusCmd = new SqlCommand();
updateFileStatusCmd.Connection =
DBConnection;
updateFileStatusCmd.CommandTimeout
= 600;
updateFileStatusCmd.CommandType = CommandType.StoredProcedure;
updateFileStatusCmd.CommandText = "update_uploadedFile";
/**
PARAMETERS DECLARATION */
SqlParameter
filename = updateFileStatusCmd.Parameters.Add("@filename",
SqlDbType.VarChar, 500);
SqlParameter
filelocation = updateFileStatusCmd.Parameters.Add("@filelocation",
SqlDbType.VarChar, -1);
SqlParameter
filetype = updateFileStatusCmd.Parameters.Add("@filetype",
SqlDbType.VarChar, 100);
try
{
/**
PARAMETERS DIRECTION */
filename.Direction = ParameterDirection.Input;
filelocation.Direction = ParameterDirection.Input;
filetype.Direction = ParameterDirection.Input;
/**
ASSIGNING PARAMETERS VALUES */
filename.Value = name;
filelocation.Value = path;
filetype.Value = filetpe;
if
(DBConnection.State == ConnectionState.Closed)
{
DBConnection.Open();
}
updateFileStatusCmd.ExecuteNonQuery();
isUpdated = true;
}
catch
(Exception ex)
{
isUpdated = false;
//
ErrorDisplay("Error Occured. See Error in C:\\DSMLog\\ErrorLog");
//
writelog.ErrorLog(ex);
// MakeAllVisible();
}
finally
{
if
(DBConnection.State == ConnectionState.Open)
{
DBConnection.Close();
}
}
return
isUpdated;
}
private
void button1_Click(object
sender, EventArgs e)
{
ServiceReference1.Service1Client proxy = new
ServiceReference1.Service1Client();
string[]
str=proxy.GetValues(10);
MessageBox.Show(str[0].ToString());
MessageBox.Show(str[1].ToString());
}
}
}
proxy generation at design time:
then ZipRequest is
DataBase:
select * from FileStatus
UploadFileName varchar(100) Unchecked
FileCreated bit Unchecked
CreatedOn datetime
Unchecked
FileTransferStatus bit Unchecked
TransferedOn datetime Checked
FileLocation varchar(MAX) Checked
Data#01100#16-10-12Zip 1 2012-10-16 18:08:14.757 1 2012-10-16
18:08:16.210 C:\DataToUpload\16-10-12
Data#01100#16-10-12Zip 1 2012-10-16 18:11:34.993 1 2012-10-16
18:11:35.460 C:\DataToUpload\16-10-12\Increment-1
Data#01100#17-10-12Zip 1 2012-10-17 12:05:38.137 1 2012-10-17
12:05:41.097 C:\DataToUpload\17-10-12
Data#01100#17-10-12Zip 1 2012-10-17 12:48:40.080 1 2012-10-17
12:48:40.407 C:\DataToUpload\17-10-12\Increment-1
14:53:30.860 C:\DataToUpload\17-10-12\Increment-15
getFileInfo : stored procedure which takes the zip file for tranfer client—server.
where FileTransferStatus =0
like
UploadFileName Data#01100#16-10-12Zip
FileTransferStatus 0
Then transfer to Server: FileUploadlocation.
client config:
client config:
<appSettings>
<add
key="vancode" value="024002" />
<add
key="serviedays" value="1,2,3,4,5,6,8,9,10,11,12,13,15,16,17,18,19,20,22,23,24,25,26,27" />
<add
key="DBConnection" value="Password=zolt123$;Persist
Security Info=True;User ID=sa;Initial Catalog=Vhop_Updated;Data
Source=mystyemsname" />
<add
key="uploadpath" value="C:\DataToUpload" />
<add
key="TempLocation" value="C:\TempForXMLS" />
<add
key="TransactionPath" value="C:\DataDownloaded\Transactions" />
<add
key="UnzipPath" value="C:\DataDownloaded\UnzipFiles" />
<add
key="MasterPath" value="C:\DataDownloaded\Masters" />
<add
key="ErrorLog" value="C:\DSMLog\ErrorLog" />
<add
key="Log" value="C:\DSMLog\Log" />
<add
key="ScriptPath" value="C:\Scripts\" />
<add
key="FullDataPath" value="C:\DataDownloaded\FullData" />
<add
key="FullBackup" value="E:\FullDataBackups" />
<add
key="imagepath" value="E:\ImagesPath" />
<add
key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
No comments:
Post a Comment