Serializing using protobuf-net and sending as postdata in http - http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}

You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

Related

How do I use response from an web api returning an image?

I have two web asp.net mvc based projects.
The first one has an image preview api, is implemented somewhat like this...
private async Task <HttpResponseMessage> GetImage(int id)
{
string filePath = "abstractedforsimplicity.png";
using(var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
{
byte[] buff = new byte[file.Length];
await file.ReadAsync(buff, 0, (int) file.Length);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(buff)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
}
this works, I am able to show a preview with the following url - domain/api/image/3
Now I am a different application where I want to again make use of the same preview. I do not want to expose this api directly, so will be making a proxy api which will be making the call internally.
public HttpResponseMessage GetImage(int id)
{
string tempalteUrl = string.Format("{0}/{1}", ConfigurationManager.AppSettings["rmgpubadmin:template-base-url"], id);
WebClient client = new WebClient();
byte[] bytes = client.DownloadData(tempalteUrl);
// not very sure what should i do here ??
return null;
}
I tried to converting the bytes to an object, but if fails with errors - System.Runtime.Serialization.SerializationException.
The input stream is not a valid binary format. The starting contents (in bytes) are: 89-50-4E-47-0D-0A-1A-0A-00-00-00-0D-49-48-44-52-00 ...
What should i be doing here?

How to consume post/put WCF RestFul Service

I am doing crud operation(Using Stored Procedure) in wcf restful service .I have done with creating services,but How do I consume that service in my plain ASP.net Application(without Javascript,Jquery,AJAX). As I am new in WCF rest service.Plz give me step by step operation.
string sURL = #"http://localhost:50353/urUriName/"+ txtfname.Text;
WebRequest webGETURL;
webGETURL = WebRequest.Create(sURL);
webGETURL.Method = "DELETE";
webGETURL.ContentType = #"Application/Json; charset=utf-8";
HttpWebResponse wr = webGETURL.GetResponse() as HttpWebResponse;
Encoding enc=Encoding.GetEncoding("utf-8");
// read response stream from response object
StreamReader loResponseStream = new StreamReader(wr.GetResponseStream(), enc);
// read string from stream data
string strResult = loResponseStream.ReadToEnd();
// close the stream object
loResponseStream.Close();
// close the response object
wr.Close();
// assign the final result to text box
Response.Write(strResult);

REST WEBAPI POST method with parameters not being called

I have built a REST API with a controller having a POST method with 4 parameters like this-
[HttpPost]
public void SaveSession([FromBody] string userId, [FromBody] DateTime issueDateTime, [FromBody] string browserType, [FromBody] string salt)
{
// Params need to be changed
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}
How should I POST data on the client side, I mean what should be the format of the data to be sent?
I tried this format-
"userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
Its not working if I try this, The web service method is not even being called
Could anyone tell me the correct format?
EDIT:
Here is how I am calling the API-
const string endPoint = #"http://localhost:85/session/Test";
var postData = "userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
var request = (HttpWebRequest) WebRequest.Create(EndPoint + parameters);
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse) request.GetResponse())
{
var xmlDoc = new XmlDocument();
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
xmlDoc.Load(responseStream);
}
return (xmlDoc);
}
Thanks!
I assume routing has been properly configured.
Said so.... DateTime parameter in the controller method has been named "issueDateTime" while within the request has been named "DateTime".
I got to know, what mistake I was doing. I was sending 4 parameters in a WebService method. We can only send one parameter while calling a web service method. If you want to send multiple data, just send it as an object. Like this -
[HttpPost]
public void SaveSession([FromBody] Values value)
{
var userId = values.userId,
var issueDateTime= values.issueDateTime,
var browserType= values.browserType,
var salt= values.salt,
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}

passing parameters to json web service using HttpWebRequest

I am having a problem in passing parameters to webservice which except POST data in JSON. I am using HttpWebRequest for this, following is the code i have tried so far, but everytime server returns any of these two errors:
Error 1:
{"command":null,"handle":null,"code":2003,"msg":"Required parameter missing","error":["Parameter 'login_handle' missing.","Parameter 'login_pass' missing."],"params":{"0":{"Key":"login_handle","Value":"test"},"1":{"Key":"login_pass","Value":"test"},"handle":"example.com"},"svTRID":null,"response":[]}
Error 2:
{"command":null,"handle":null,"code":2400,"msg":"Command failed","error":["Internal Server Error. resulted in the following error: array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":[],"svTRID":null,"response":[],"children":[{"command":"Internal Server Error.","handle":null,"code":2400,"msg":"Command failed","error":["array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":{"errno":2,"errstr":"array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object","errfile":"\/home\/ote\/httpapi\/v1\/index.php","errline":54},"svTRID":null,"response":[]}]}
Here is the code:
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
Dictionary<string, string> data = new Dictionary<string, string>();
data["login_handle"] = "test";
data["login_pass"] = "test";
System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
writer.Write(json);
writer.Close();
System.Net.WebResponse webResp = webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string s = sr.ReadToEnd().Trim();
}
catch (Exception ex)
{
string e = ex.Message;
}
If i use string data = "[login_handle:'username',login_pass:'password']"; instead of Dictionary<string, string> , i receive error number 2.
Never mind, i solved it myself, instead of using Dictionary type i used anonymous type like this var data = new { login_handle = "test", login_pass = "test" }; and it solved my problem.
What you should have done is create a DataContract class (we'll call JsonData) which has two DataMembers named login_handle and login_pass.
Then, in the DataContractJsonSerializer, pass typeof(JsonData) to the constructor.
This solution is the best because you cannot create complex types using an anonymous type. Also, by parenting your DataContracts you can easily create complex JSON.

POSTing XML with non-ASCII characters

I'm trying to patch RestSharp for it to be able to POST XMLs with non-ASCII characters as POST request body.
Here's how it gets written:
private void WriteRequestBody(HttpWebRequest webRequest) {
if (HasBody) {
webRequest.ContentLength = RequestBody.Length;
var requestStream = webRequest.GetRequestStream();
using (var writer = new StreamWriter(requestStream, Encoding.ASCII)) {
writer.Write(RequestBody);
}
}
}
RequestBody is a string and when server actually tries to parse the request, all non-ASCII characters turn into ???.
Now, I do the following:
var encoding = Encoding.UTF8;
webRequest.ContentLength = encoding.GetByteCount(RequestBody);
var requestStream = webRequest.GetRequestStream();
using (var writer = new StreamWriter(requestStream, encoding)) {
writer.Write(RequestBody);
}
But it throws IOException on Stream.Dispose() saying "Cannot close stream until all bytes are written."
How do I post this XML?
I haven't used RestSharp but looking explanation my guess is that the payload's ContentLength does not match the internal-string. XML uses UTF-8 escapes, so the payload could become larger. So on original string the representation could Content-Length could differ.
Maybe you calculate the Content-Length at a wrong place?

Resources