Windows Phone 8 send File HttpClient FileBody - file-upload

Hello I'm just searching for more than 2 days...
My problem: I want to send a Post Request to a Server and send a File (FileBody) with this post.
I've found many examples for this with the WebClient class. But I am a newbee to C# and Windows Phone development and so i did not get it to work. Because the only method i see is "UploadStringAsync" but the method mentioned everywhere in the internet "UploadFile" is not available in my object.
string postdata = string.Format("cmd={0}&", "show");
postdata += string.Format("latitude={0}&", HttpUtility.UrlEncode("-1"));
...
WebClient wc = new WebClient();
wc.UploadStringAsync(new Uri("http://mydomain/myphp.php", UriKind.Absolute), "POST", postdata);
The problem is i have to send a FileBody as mentioned here: http://www.codescales.com/category/howto/
But i cant reference this project to my windows phone project.
I am very confused right now and hope anyone can help me with this.

You can use RestSharp, (Nuget it)
Contains several options to upload files:
public IRestRequest AddFile(string name, string path);
public IRestRequest AddFile(string name, Action<System.IO.Stream> writer, string fileName);
public IRestRequest AddFile(string name, byte[] bytes, string fileName);
public IRestRequest AddFile(string name, Action<System.IO.Stream> writer, string fileName, string contentType);
public IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType);

Related

Rewriting API from .Net Framework to .netcore ,Getting 'System.NotSupportedException' in attempt to get file stream

I am Migrating one of projects to .NET CORE MVC ,
Previous code had API to Upload document, re-written same
Rewritten Above Code to below code , used "using
Microsoft.AspNetCore.Mvc.WebApiCompatShim" to get HttpRequestMessage
[Older Code: Working Fine in .NET FRAMEWORK]
public HttpResponseMessage UploadFile(string filetype)//old code
{
Stream file = Request.Content.ReadAsStreamAsync().Result;
string id;
id = DocumentHelper.SaveDocument(filetype, file);
return Request.CreateResponse<string>(HttpStatusCode.OK, id);
}
public HttpResponseMessage UploadFile(string filetype)//Re-Written Code
{
HttpRequestMessageFeature requestMessage = new HttpRequestMessageFeature(Request.HttpContext);
HttpRequestMessage httpRequestMessage = requestMessage.HttpRequestMessage;
Stream file = httpRequestMessage.Content.ReadAsStreamAsync().Result;
string id;
id = DocumentHelper.SaveDocument(filetype, file);
return httpRequestMessage.CreateResponse<string>(HttpStatusCode.OK, id);
}
Quickwatch for ReWritten Code when trying to read content
[1]: https://i.stack.imgur.com/cc4AF.png
Tried using Request.Body with stream reader, and enabled buffering.
Any Pointers How to read the stream from Microsoft.AspNetCore.HTTP.HttpRequest,I AM TRYING TO AVOID async function that would force me to change return type

Sensenet: Upload Files through Sensenet Client API and Set Modified User

I have a requirement that consists on uploading files through other system to sensenet.
I'm trying to use the Sensenet Client API to upload files but I'm having difficult using the examples documented on the follow links:
Client Library (the code runs well but the file doesn't appear on Sensenet)
Common API Calls (I'm having trouble to compile the code... to instantiate the BinaryData object)
Beside this, I need for each uploading file define the "Modified By" that I specify in my code and not the user that I use to authenticate me in the API.
I think rewriting the ModifiedBy field is an edge case (or a small hack) but it is possible without any magic (see the code). The easiest way is a POST followed by a PATCH, that is perfectly managed by the SenseNet.Client (the code uses a local demo site):
static void Main(string[] args)
{
ClientContext.Initialize(new[]
{new ServerContext {Url = "http://localhost", Username = "admin", Password = "admin"}});
var localFilePath = #"D:\Projects\ConsoleApplication70\TestFileFromConsole1.txt";
var parentPath = "/Root/Sites/Default_Site/workspaces/Document/londondocumentworkspace/Document_Library";
var fileName = "TestFileFromConsole1.txt";
var path = parentPath + "/" + fileName;
var userPath = "/Root/IMS/BuiltIn/Demo/ProjectManagers/alba";
using (var stream = new FileStream(localFilePath, FileMode.Open))
Content.UploadAsync(parentPath, fileName, stream).Wait();
Console.WriteLine("Uploaded");
Modify(path, userPath).Wait();
Console.WriteLine("Modified");
Console.Write("Press <enter> to exit...");
Console.ReadLine();
}
// Rewrites the ModifiedBy field
private static async Task Modify(string path, string userPath)
{
var content = await Content.LoadAsync(path);
content["ModifiedBy"] = userPath;
await content.SaveAsync();
}

Programmatically upload synonyms to google search api using java

I'm having issues figuring out how to programmatically upload synonyms to the google search api from my server using java.
1. The Authorization: The description of how to do a server to google api is explained here. Where can I find a simple example of this using java?
2. Upload synonyms: I have created the xml to be uploaded, explained here. I am not able to see how I actually upload this to the google-api. Is there an example of how this is done?
1. The Authorization
public static String getAuthorizationToken() throws IOException, HttpException{
PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
method.addParameter("accountType", "HOSTED_OR_GOOGLE");
method.addParameter("Email", "my#gmail.com");
method.addParameter("Passwd", "myPassword");
method.addParameter("service", "cprose");
method.addParameter("source", "mySource");
String response = executeMethodAsString(method);
return retrieveAuthFromResponse(response);
}
2. Upload synonym
public static String updateSynonyms(String authToken, String xml) throws HttpException, IOException{
PostMethod method = new PostMethod("http://www.google.com/cse/api/default/synonyms/abcdefg1234");
method.addRequestHeader("Content-Type", "text/xml");
method.addRequestHeader("Authorization", "GoogleLogin auth=" + authToken);
RequestEntity entitiy = new StringRequestEntity(xml, "text/xml", "utf-8");
method.setRequestEntity(entitiy);
return executeMethodAsString(method);
}

WCF 4.0 REST Upload MS-Excel File

I am trying to upload MS-Excel file through WCF-REST Service.
I used the solution given in below post:-
RESTful WCF service image upload problem
My POST Method is declared as:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/RFQ")]
[WebContentType("application/octet-stream")]
void UploadRFQDoc(Stream fileContents);
When I debug, stream content is fine till the call goes, and when I attach service to debug, Stream fileContents parameter becomes null , and service returns with [Bad Request]. I am not sending large file (it is just 50 KB). I am using HttpClient to call the Post.
Here are the client code(RestClient is HttpClient).
protected void Post(string uri, Stream stream, int length)
{
var content = HttpContent.Create(output => CopyToStream(stream, output, length), "application/octet-stream", length);
Uri relativeUri = new Uri(uri, UriKind.Relative);
var resp = RestClient.Post(relativeUri, content);
ProcessResponse(resp);
}
void CopyToStream(Stream input, Stream output, int length)
{
var buffer = new byte[length];
var read = input.Read(buffer, 0, Convert.ToInt32 (length));
output.Write(buffer, 0, read);
}
Any clue what else can go wrong.
Many Thanks.
[WebContentType("application/octet-stream")] attribute was unnecessary here. I commented it out, and all worked fine :).

WCF + REST: Where is the request data?

I'm currently developing a WCF RESTful service. Within the validation of the POST data, I am throwing exceptions if the request XML does not conform to our business rules.
The goal is to send an e-mail to the appropriate staff if a request comes in that considered invalid. But, along with the incoming request headers, method and URI, I'd like to also send the XML that was posted.
I have not been able to find a way to access this data. Is WCF actually destroying the request body/data before I have a chance to access it or am I missing something?
Your help is appreciated as I'm confused as to why I can't access the request data.
This unfortunately isn't supported- we had a similar need, and did it by calling internal members with reflection. We just use it in an error handler (so we can dump the raw request), but it works OK. I wouldn't recommend it for a system you don't own and operate though (eg, don't ship this code to a customer), since it can change at any time with a service pack or whatever.
public static string GetRequestBody()
{
OperationContext oc = OperationContext.Current;
if (oc == null)
throw new Exception("No ambient OperationContext.");
MessageEncoder encoder = oc.IncomingMessageProperties.Encoder;
string contentType = encoder.ContentType;
Match match = re.Match(contentType);
if (!match.Success)
throw new Exception("Failed to extract character set from request content type: " + contentType);
string characterSet = match.Groups[1].Value;
object bufferedMessage = operationContextType.InvokeMember("request",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField,
null, oc, null);
//TypeUtility.AssertType(bufferedMessageType, bufferedMessage);
object messageData = bufferedMessageType.InvokeMember("MessageData",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty,
null, bufferedMessage, null);
//TypeUtility.AssertType(jsonBufferedMessageDataType, messageData);
object buffer = jsonBufferedMessageDataType.InvokeMember("Buffer",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty,
null, messageData, null);
ArraySegment<byte> arrayBuffer = (ArraySegment<byte>)buffer;
Encoding encoding = Encoding.GetEncoding(characterSet);
string requestMessage = encoding.GetString(arrayBuffer.Array, arrayBuffer.Offset, arrayBuffer.Count);
return requestMessage;
}
So, if you declare your contract something like:
[WebInvoke(Method = "POST", UriTemplate = "create", ResponseFormat=WebMessageFormat.Json)]
int CreateItem(Stream streamOfData);
(you can use XML instead)
The streamOfData should be the body of an HTTP POST. You can deserialize it using something like:
StreamReader reader = new StreamReader(streamId);
String res = reader.ReadToEnd();
NameValueCollection coll = HttpUtility.ParseQueryString(res);
It's working like that for us, at least. You may want to use a different approach to get the string into an XMLDocument or something. This works for our JSON posts. Might not be the most elegant solution, but it is working.
I hope this helps.
Glenn
Try this,
OperationContext.Current.RequestContext.RequestMessage
Here's how you do it without reflection:
using (var reader = OperationContext.Current.RequestContext.RequestMessage.GetReaderAtBodyContents ()) {
if (reader.Read ())
return new string (Encoding.ASCII.GetChars (reader.ReadContentAsBase64 ()));
return result;
}
}
If the reader is a HttpStreamXmlDictionaryReader (as it was in my case), the class's implementation of the method ReadContentAsBase64(byte[] buffer, int index, int count) simply passes these parameters to the Stream.Read method.
Once I have the byte[] I convert the bytes to a string via ASCII encoding. For a proper implementation, you could use the content type & encoding from the message's headers to do per HTTP spec.
You could arrest the HttpApplication.Request.InputStream in a custom HttpModule of the WCF Service, read the stream and again set its position to 0 in the custom HttpModule's event handler. Then store it in session and access it further in the actual OperationContract.
For example:
public class CustomModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AcquireRequestState +=context_AcquireRequestState;
}
void context_AcquireRequestState(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
Stream str = application.Request.InputStream;
StreamReader sr = new StreamReader(str);
string req = sr.ReadToEnd();
str.Position = 0;
application.Session["CurrentRequest"] = req;
}
}