I have a rest service.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Add(News entity);
Here the imp :
public bool Add(News entity)
{
try
{
_ctx.News.Add(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
I post data to my service but i need the result of my operation that here is bool .how can i get the result in my code ?
News student = new News
{
Id = Guid.NewGuid(),
Subject = "wfwf",
ViewerCounter = 1, // removed the "" (string)
MainContent = "fsdsd", // renamed from "Content"
SubmitDateTime = DateTime.Now,
ModifiedDateTime = DateTime.Now,
PublisherName = "sdaadasd",
PictureAddress = "adfafsd",
TypeOfNews = "adsadaad"
};
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(News));
serializerToUplaod.WriteObject(ms, student);
Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/AddNews", "POST", ms.ToArray());
Just use this:
byte[] a= Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/AddNews", "POST", ms.ToArray());
string result = System.Text.Encoding.UTF8.GetString(a);
Related
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);
}
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);
}
I am bit new in rest service
I have service as below
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate="AuthenticateJSON/?username=username&password=password")]
public Response.Authenicate Authenticate(string username,string password)
{
var returnObject = new Authenicate();
try
{
returnObject.Response = "True";
}
catch (Exception exceptionObject)
{
returnObject.IsError = true;
returnObject.ErrorMessage = exceptionObject.Message;
}
return returnObject;
}
And I consume Service by below code
string input = #"{'himanshu','password'}";
var newUser = new User();
newUser.username = "username";
newUser.password = "username";
var input = new JavaScriptSerializer().Serialize(newUser);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:20620/Services/User/OperationActiveDirectory.svc/AuthenticateJSON/?username=username&password=password");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";//POST/GET
string responseText = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(input);//any parameter
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
but i am facing below error while execution
Could some one suggest me what i am doing wrong here
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";
}
}
}
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)
{
}