How to Send and receive excel data using web service - c#

How to Send and receive excel data using web service
I have created a web application to send excel file data to a web service.
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:58959/RESTServiceImpl.svc/PostFile");
request.ContentType = "application/vnd.ms-excel";
request.Headers.Add("filename", "fooBar.xls");
request.Method = WebRequestMethods.Http.Post;
byte[] fileData = System.IO.File.ReadAllBytes("C:\\Users\\Public\\Documents\\Forecast Pro TRAC\\Input\\Book1.xls");
request.ContentLength = fileData.Length;
using (System.IO.BinaryWriter postStream = new System.IO.BinaryWriter(request.GetRequestStream()))
{
postStream.Write(fileData);
postStream.Flush();
postStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK);
string responseMessage = string.Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseMessage = sr.ReadToEnd();
}
System.Diagnostics.Debug.WriteLine(responseMessage);
}
Now I need to receive that excel data from WCF application. So I have done something like below code. I am getting total bytes that I am sending. What are exact things I need to do in both end to send and receive excel data.
[ServiceContract]
public interface IRESTServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "PostFile")]
string PostFile();
}
public class RESTServiceImpl : IRESTServiceImpl
{
public string PostFile()
{
var httpRequest = HttpContext.Current.Request;
var bites = httpRequest.TotalBytes;
return httpRequest.FilePath;
}
}
I am very new in web service and this is my first application. So please please help me.
Thanks in advance.

I have solved the solution and here is the working code
public class RestServiceImpl : IRestServiceImpl
{
public string PostFileRest(Stream fileContents)
{
var httpRequest = HttpContext.Current.Request;
var filePath = "C:\\file.xls"; //excel filePath for local
var bites = httpRequest.TotalBytes;
//Convert stream to byte array
byte[] reqBytes = readRequest(fileContents, bites);
byte[] decodedReqBytes = HttpUtility.UrlDecodeToBytes(reqBytes);
string json = System.Text.Encoding.UTF8.GetString(reqBytes);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
MemoryStream stream = new MemoryStream(reqBytes);
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();
return json ;
}
#region Convert Stream to byte array
private byte[] readRequest(Stream fileContents, int bites)
{
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
int BUFFER_SIZE = bites;
int iRead = 0;
int idx = 0;
Int64 iSize = 0;
memStream.SetLength(BUFFER_SIZE);
while (true)
{
byte[] reqBuffer = new byte[BUFFER_SIZE];
try
{
iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE);
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
if (iRead == 0)
{
break;
}
iSize += iRead;
memStream.SetLength(iSize);
memStream.Write(reqBuffer, 0, iRead);
idx += iRead;
}
byte[] content = memStream.ToArray();
memStream.Close();
return content;
}
#endregion
}
The Interface-
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "PostFileRest")]
string PostFileRest(Stream fileContents);
}

Related

WCF Service not save image from Ionic App

I'm working on an application and upload images Ionic my WCF Service, the problem is that when the image comes from my WCF code not saved correctly. Save it as an image invalid.
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "upload2/{fileName}")]
string Upload2(string fileName, Stream fileStream);
public string Upload2(string fileName, Stream fileStream)
{
try
{
FileStream fileToupload = new FileStream(WebConfigurationManager.AppSettings["FilePath"] + fileName, FileMode.Create);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
return "succ";
}
catch (Exception ex)
{
return ex.Message + " - " + ex.InnerException;
}
}
Code controller AngularJs,
$scope.subirFoto = function() {
var options = new FileUploadOptions();
options.fileKey = "post";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.68.1.182:8085/IServiceTopStore.svc/upload2/"+options.fileName), win, fail, options);
}
Solve it follows if someone needs
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "UploadImage/{fileName}")]
string UploadImage(string fileName);
public string UploadImage(string fileName)
{
try
{
HttpPostedFile file = HttpContext.Current.Request.Files["post"];
if (file == null)
return null;
string targetFilePath = WebConfigurationManager.AppSettings["FilePath"] + fileName;
file.SaveAs(targetFilePath);
return "succ " + file.FileName.ToString(); ;
}
catch (Exception ex)
{
return ex.Message + " - " + ex.InnerException;
}
}
Ionic :
$scope.subirFoto = function() {
var options = new FileUploadOptions();
options.fileKey = "post";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.1.1.1:8085/IServiceTopStore.svc/upload2/"+options.fileName), win, fail, options);
}

WCF bad request 400 - wpf client

I created WCF service and WPF client to send to service some stream. GET method works fine in my client but i have problem with POST method. Here is the code:
IRestService:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "SaveFromStreamJson2")]
void SaveFromStreamJson2(Stream stream);
RestService.svc
public void SaveFromStreamJson2(Stream stream)
{
if (stream != null)
{
StreamReader stReader = new StreamReader(stream);
string text = stReader.ReadToEnd();
}
}
WCF client:
private void button2_Click(object sender, RoutedEventArgs e)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:57424/RestService.svc/SaveFromStreamJson2");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," + "\"password\":\"bla\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}

Failure Loading XML from String Returned by WCF Service

I have a WCF project that returns a DataSet in XML format. This is in my service contract:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "RunSavedReportByID", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DataSet RunSavedReportByID(int savedReportID);
I have another project that consumes this service, and I'm trying to get the DataSet back. I call my service like so:
strResults = objUtility.GetData("RunSavedReportByID", JsonConvert.SerializeObject(new { savedReportID = savedReportID }));
GetData looks like this:
public string GetData(string method, string data)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(externalServiceUrl + method);
ASCIIEncoding encoding = new ASCIIEncoding();
var postData = encoding.GetBytes(data);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, data.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
return reader.ReadToEnd().Trim();
}
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
return null;
}
The string that I get is weird. It looks like this when I save it to a text file:
"\"<DataSet><xs:schema id=\\\"NewDataSet\\\" xmlns:xs=\\\"http:\\/\\/www.w3.org\\/2001\\/XMLSchema\\\" xmlns:msdata=\\\"urn:schemas-microsoft-com:xml-msdata\\\"><xs:element name=\\\"NewDataSet\\\" msdata:IsDataSet=\\\"true\\\" msdata:UseCurrentLocale=\\\"true\\\"><xs:complexType><xs:choice minOccurs=\\\"0\\\" maxOccurs=\\\"unbounded\\\"><xs:element name=\\\"Table\\\"><xs:complexType><xs:sequence><xs:element name=\\\"InvoiceNo\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"GuestID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ConsumerID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ContactTitleName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"LastName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"FirstName\\\" type=\\\"xs:string\\\" ... blah blah blah ... \\/NewDataSet><\\/diffgr:diffgram><\\/DataSet>\""
Not surprisingly, after I create and XmlDocument and call LoadXml, I get
Data at the root level is invalid. Line 1, position 1.
If I strip out the first and last quotation marks and unescape the string like so
strResults = Regex.Unescape(strResults);
strResults = strResults.Remove(0, 1);
strResults = strResults.Remove(strResults.Length - 1, 1);
then the XML loads fine, so the XML itself is legit.
So after all this exposition, my questions are
1) Why does the string I get back look so weird? What's up with all the extra quotation marks and backslashes?
2) Is there a better way of getting rid of the bad stuff before loading the XML?

How to read HttpHeaders at WebService send by HttpClient

I am trying to create a webservice. I am successfully able to send HttpClient Request to web service and getting response too.
What I want ?
I am sending some HttpHeaders with the POST request like userAgent, or any CustomHeader. That Header I want to read in webservice method. I don't know how to get Header list ?
I created webservice in C#.
public class Service1 :IService1{
public string putData(Stream data)
{
string response = string.Empty;
try
{
HttpContext ctx = HttpContext.Current;
string headerValue = ctx.Request.Headers["tej"];
StreamReader reader = new StreamReader(data);
string xmlString = reader.ReadToEnd();
StringReader sr = new StringReader(xmlString);
MySqlCommand cmd = new MySqlCommand();
DataSet ds = new DataSet();
ds.ReadXml(sr);
//my logic here....
return "Passed";
}
catch (Exception ex)
{
return "Failed";
}
}
}
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "putdata")]
string putData(Stream sDatabase);
}
Please try following using WebOperationContext.Current.IncomingRequest object.
public class Service1 :IService1
{
public string putData(Stream data)
{
try
{
//reading headers
IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;
foreach (string headerName in headers.AllKeys)
{
Console.WriteLine(headerName + ": " + headers[headerName]);
}
//---- rest of the code
}
catch (Exception ex)
{
return "Failed";
}
}
}

How to pass parameter value using HttpPost and NameValuePair in android when accessing rest web service?

I made a rest web service with the service contract as shown below
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "postdataa?id={id}"
)]
string PostData(string id);
Implementation of the method PostData
public string PostData(string id)
{
return "You posted " + id;
}
Code in Android to post data in web service
HttpClient httpclient = new DefaultHttpClient();
HttpHost target = new HttpHost("192.168.1.4",4567);
HttpPost httppost = new HttpPost("/RestService.svc/postdataa?");
String result=null;
HttpEntity entity = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(target, httppost);
entity = response.getEntity();
//get xml result in string
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
The problem is that the xml result shows and the value of the parameter is missing:
<PostDataResponse xmlns="http://tempuri.org/"><PostDataResult>You posted </PostDataResult></PostDataResponse>
I do not know what went wrong.
Since you are using REST service, give this a try:
private static char[] GetData(String servicePath) throws Exception
{
InputStream stream = null;
String serviceURI = SERVICE_URI;//this is your URI to the service
char[] buffer = null;
try
{
if (servicePath != "")
serviceURI = serviceURI + servicePath;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(serviceURI);
request.setHeader("Accept", "application/xml");
request.setHeader("Content-type", "application/xml");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null)
{
// Read response data into buffer
buffer = new char[(int)responseEntity.getContentLength()];
stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
}
}
catch (Exception e)
{
Log.i("Survey Application", e.getMessage());
throw e;
}
return buffer;
}
Invoke this method using
try
{
char[] buffer = GetData("postdataa/" + id);
if (buffer != null)
//Build your XML object
}
catch (Exception e)
{
}

Categories