public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType) { base.SetDefaultContentHeaders(type, headers, mediaType); headers.ContentType = new MediaTypeHeaderValue(ApplicationJsonMediaType); this.SerializerSettings.Formatting = Formatting.None; this.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }
protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context) { var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; // NOTE: we don't dispose or close these as they would // close the stream, which is used by the rest of the pipeline. var writer = default(JsonWriter); if (contentHeaders.ContentType.MediaType == "application/bson") writer = new BsonWriter(stream); else writer = new JsonTextWriter(new StreamWriter(stream)); if (UsesQueryComposition) { serializer.Serialize(writer, ((IEnumerable)value).OfType<object>().ToList()); } else { serializer.Serialize(writer, value); } writer.Flush(); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName"; //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped return(name.Replace("\"", string.Empty)); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { string filepath; filepath = Guid.NewGuid().ToString() + "_" + headers.ContentDisposition.FileName.Replace("\"", ""); return(filepath); }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { if (parent == null) { throw Error.ArgumentNull("parent"); } if (headers == null) { throw Error.ArgumentNull("headers"); } string localFilePath; try { string filename = this.GetLocalFileName(headers); localFilePath = Path.Combine(this._rootPath, Path.GetFileName(filename)); } catch (Exception e) { throw Error.InvalidOperation(e, Resources.MultipartStreamProviderInvalidLocalFileName); } // Add local file name MultipartFileData fileData = new MultipartFileData(headers, localFilePath); this._fileData.Add(fileData); return File.Create(localFilePath, this._bufferSize, FileOptions.Asynchronous); }
protected virtual string GetLocalFileName(HttpContentHeaders headers) { if (headers == null) { throw new ArgumentNullException("headers"); } string str = null; try { ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition != null) { str = ExtractLocalFileName(contentDisposition); } } catch (Exception) { } if (str == null) { str = string.Format(CultureInfo.InvariantCulture, "BodyPart_{0}", new object[] { Guid.NewGuid() }); } return str; }
/// <summary> /// <para>This method assumes that all form segments come before the actual file data.</para> /// <para>Otherwise, GetLocalFileName will fail.</para> /// </summary> public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { if (headers.ContentDisposition.FileName == null) { return base.GetStream(parent, headers); } string flowFileName = null; try { flowFileName = GetLocalFileName(headers); } catch (Exception ex) { throw new Exception("Flow chunk information was not properly transmitted before the chunk payload.", ex); } FileStream flowFileStream; var path = Path.Combine(RootPath, flowFileName); flowFileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write); flowFileStream.SetLength(MetaData.FlowTotalSize); flowFileStream.Seek(MetaData.FileOffset, 0); return flowFileStream; }
/// <summary> /// This body part stream provider examines the headers provided by the MIME multipart parser /// and decides whether it should return a file stream or a memory stream for the body part to be /// written to. /// </summary> /// <param name="parent">The parent MIME multipart HttpContent instance.</param> /// <param name="headers">Header fields describing the body part</param> /// <returns>The <see cref="Stream"/> instance where the message body part is written to.</returns> public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { if (parent == null) { throw Error.ArgumentNull("parent"); } if (headers == null) { throw Error.ArgumentNull("headers"); } // For form data, Content-Disposition header is a requirement ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition != null) { // If we have a file name then write contents out to temporary file. Otherwise just write to MemoryStream if (!String.IsNullOrEmpty(contentDisposition.FileName)) { // We won't post process files as form data _isFormData.Add(false); return base.GetStream(parent, headers); } // We will post process this as form data _isFormData.Add(true); // If no filename parameter was found in the Content-Disposition header then return a memory stream. return new MemoryStream(); } // If no Content-Disposition header was present. throw Error.InvalidOperation(Properties.Resources.MultipartFormDataStreamProviderNoContentDisposition, "Content-Disposition"); }
protected override System.Threading.Tasks.Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) { return new TaskFactory<object>().StartNew(() => { return new StreamReader(stream).ReadToEnd(); }); }
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(() => { Assert.True(false, "Delegate called."); return 0; }); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); }
public virtual void SetContentType(Type type, HttpContentHeaders headers, string mediaType) { if (this.SupportedMediaTypes == null) { throw new InvalidOperationException(string.Format("{0} does not set support media types", base.GetType())); } headers.ContentType = this.SupportedMediaTypes.Contains(mediaType) ? mediaType : this.SupportedMediaTypes.First(); }
public static void CopyTo(this HttpContentHeaders fromHeaders, HttpContentHeaders toHeaders) { foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) { toHeaders.TryAddWithoutValidation(header.Key, header.Value); } }
public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15)); // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison. Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); }); }
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => { throw new ShouldNotBeInvokedException(); })); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); }
protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) { return new TaskFactory().StartNew(() => { new StreamWriter(stream).Write((string)value); }); }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { if (parent == null) throw new ArgumentNullException(nameof(parent)); if (headers == null) throw new ArgumentNullException(nameof(headers)); if (!_supportedMimeTypes.Contains(headers.ContentType.ToString().ToLower())) { throw new NotSupportedException("Only jpeg and png are supported"); } // Generate a new filename for every new blob var fileName = Guid.NewGuid().ToString(); CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(fileName); if (headers.ContentType != null) { // Set appropriate content type for your uploaded file blob.Properties.ContentType = headers.ContentType.MediaType; } this.FileData.Add(new MultipartFileData(headers, blob.Name)); return blob.OpenWrite(); }
public static bool IsFileContent(HttpContent parent, HttpContentHeaders headers) { if (parent == null) { throw Error.ArgumentNull("parent"); } if (headers == null) { throw Error.ArgumentNull("headers"); } // For form data, Content-Disposition header is a requirement. ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition == null) { // If no Content-Disposition header was present. throw Error.InvalidOperation(Resources.MultipartFormDataStreamProviderNoContentDisposition, "Content-Disposition"); } // The file name's existence indicates it is a file data. if (!String.IsNullOrEmpty(contentDisposition.FileName)) { return true; } return false; }
internal static void CopyTo(this HttpContentHeaders from, HttpContentHeaders to) { foreach (var header in from) { to.TryAddWithoutValidation(header.Key, header.Value); } }
// Sealed because derived classes shouldn't override the async version. Override sync version instead. public sealed override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext) { if (type == null) { throw new ArgumentNullException("type"); } if (stream == null) { throw new ArgumentNullException("stream"); } // Underlying stream will do encoding into separate sections. This is just buffering. return TaskHelpers.RunSynchronously( () => { Stream bufferedStream = GetBufferStream(stream); try { WriteToStream(type, value, bufferedStream, contentHeaders); } finally { // Disposing the bufferStream will dispose the underlying stream. // So Flush any remaining bytes that have been written, but don't actually close the stream. bufferedStream.Flush(); } }); }
public void AddRange(HttpContentHeaders headers) { foreach (var header in headers) { this._headers.Add(header.Key, header.Value); } }
public override object ReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger) { BufferedMediaTypeFormatter innerFormatter = InnerBufferedFormatter; MediaTypeHeaderValue contentType = contentHeaders == null ? null : contentHeaders.ContentType; object value = null; _innerTracer.TraceWriter.TraceBeginEnd( _innerTracer.Request, TraceCategories.FormattingCategory, TraceLevel.Info, _innerTracer.InnerFormatter.GetType().Name, OnReadFromStreamMethodName, beginTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceReadFromStreamMessage, type.Name, contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString()); }, execute: () => { value = innerFormatter.ReadFromStream(type, stream, contentHeaders, formatterLogger); }, endTrace: (tr) => { tr.Message = Error.Format( SRResources.TraceReadFromStreamValueMessage, FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture)); }, errorTrace: null); return value; }
public static bool IsFileContent(HttpContent parent, HttpContentHeaders headers) { if (parent == null) { throw new ArgumentNullException("parent"); } if (headers == null) { throw new ArgumentNullException("headers"); } // For form data, Content-Disposition header is a requirement. ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition == null) { // If no Content-Disposition header was present. throw new InvalidOperationException("No Content-Disposition header found"); } // The file name's existence indicates it is a file data. if (!string.IsNullOrEmpty(contentDisposition.FileName)) { return true; } return false; }
public override Task<object> ReadFromStreamAsync(Type type, HttpContentHeaders headers, Stream stream) { var tcs = new TaskCompletionSource<object>(); try { var serializer = GetSerializerForType(type); if (serializer == null) { tcs.TrySetException(new InvalidOperationException(string.Format("Can not create serializer for {0}", type))); } else { Task<object>.Factory.StartNew(() => serializer.Deserialize(stream)) .ContinueWith(t => { if (t.IsFaulted) { tcs.TrySetException(t.Exception.GetBaseException()); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(t.Result); } }, TaskContinuationOptions.ExecuteSynchronously); } } catch (Exception ex) { tcs.TrySetException(ex); } return tcs.Task; }
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) { string callback; if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback)) { return Task.Factory.StartNew(() => { var writer = new StreamWriter(stream); writer.Write(callback + "("); writer.Flush(); base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext).Wait(); writer.Write(")"); writer.Flush(); }); } else { return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext); } }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { Stream stream = null; ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition != null) { if (!String.IsNullOrWhiteSpace(contentDisposition.FileName)) { CloudBlobContainer blobContainer = Util.GetContainer(); //blobContainer.CreateIfNotExists(); //blobContainer.SetPermissions(new BlobContainerPermissions //{ // PublicAccess = BlobContainerPublicAccessType.Blob //}); string fileName = Id + "\\" + contentDisposition.FileName.Trim('"'); //upload file CloudBlockBlob blob = blobContainer.GetBlockBlobReference( fileName); stream = blob.OpenWrite(); } } return stream; }
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext) { var serializer = JsonSerializer.Create(jsonSerializerSettings); var tcs = new TaskCompletionSource<object>(); try { using (var streamWriter = new StreamWriter(stream, Encoding)) { using (var jsonTextWriter = new JsonTextWriter(streamWriter)) { serializer.Serialize(jsonTextWriter, value); tcs.SetResult(null); } } } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) { Stream stream = null; ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition; if (contentDisposition != null) { if (!String.IsNullOrWhiteSpace(contentDisposition.FileName)) { string connectionString = ConfigurationManager.AppSettings["azureConnectionString"]; var containerName = ConfigurationManager.AppSettings["container"]; if (contentDisposition.Name.Contains("avatar")) containerName = "avatar"; if (contentDisposition.Name.Contains("headerImage")) containerName = "header"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName); CloudBlockBlob blob = blobContainer.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg"); blob.Metadata.Add("source", ConfigurationManager.AppSettings["source"]); if (_breweryDto != null) blob.Metadata.Add("breweryId", _breweryDto.Id.ToString()); if(_userDto != null) blob.Metadata.Add("username", _userDto.Username); stream = blob.OpenWrite(); headers.ContentDisposition.FileName = blob.Name; } } return stream; }
private static void CopyHeaders(HttpContentHeaders fromHeaders, HttpContentHeaders toHeaders) { foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) { toHeaders.Add(header.Key, header.Value); } }
/// <summary> /// This body part stream provider examines the headers provided by the MIME multipart parser /// and decides which <see cref="FileStream"/> to write the body part to. /// </summary> /// <param name="headers">Header fields describing the body part</param> /// <returns>The <see cref="Stream"/> instance where the message body part is written to.</returns> public virtual Stream GetStream(HttpContentHeaders headers) { if (headers == null) { throw new ArgumentNullException("headers"); } string localFilePath; try { string filename = GetLocalFileName(headers); localFilePath = Path.Combine(_rootPath, Path.GetFileName(filename)); } catch (Exception e) { throw new InvalidOperationException(Properties.Resources.MultipartStreamProviderInvalidLocalFileName, e); } // Add local file name lock (_thisLock) { _bodyPartFileNames.Add(localFilePath); } return File.Create(localFilePath, _bufferSize, FileOptions.Asynchronous); }
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext) { var serializer = JsonSerializer.Create(jsonSerializerSettings); var tcs = new TaskCompletionSource<object>(); try { using (var streamReader = new StreamReader(stream, Encoding)) { using (var jsonTextReader = new JsonTextReader(streamReader)) { var result = serializer.Deserialize(jsonTextReader, type); tcs.SetResult(result); } } } catch (Exception ex) { tcs.SetException(ex); } return tcs.Task; }
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger) { Task<IEnumerable<HttpContent>> readAsMultipartAsync = _httpRequestMessage.Content.ReadAsMultipartAsync(); IEnumerable<HttpContent> httpContents = readAsMultipartAsync.Result; HttpContent content = httpContents.First(x => SupportedMediaTypes.Contains(x.Headers.ContentType)); string fileName = content.Headers.ContentDisposition.FileName; string mediaType = content.Headers.ContentType.MediaType; Task<Stream> readAsStreamAsync = content.ReadAsStreamAsync(); byte[] readFully = readAsStreamAsync.Result.ReadFully(); var taskCompletionSource = new TaskCompletionSource<object>(); taskCompletionSource.SetResult(new ImageMedia(fileName, mediaType, readFully)); return taskCompletionSource.Task; // var taskCompletionSource = new TaskCompletionSource<object>(); // try // { // var memoryStream = new MemoryStream(); // stream.CopyTo(memoryStream); // var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()); // taskCompletionSource.SetResult(s); // } // catch (Exception e) // { // taskCompletionSource.SetException(e); // } // return taskCompletionSource.Task; }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { //Make the file name URL safe and then use it & is the only disallowed url character allowed in a windows filename var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName"; return(name.Trim(new char[] { '"' }) .Replace("&", "and")); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : Guid.NewGuid().ToString(); return(name.Replace("\"", string.Empty)); }
//public override string GetLocalFileName(HttpContentHeaders headers) //{ // string fileName = headers.ContentDisposition.FileName; // if (string.IsNullOrWhiteSpace(fileName)) // { // fileName = Guid.NewGuid().ToString() + ".data"; // } // return fileName.Replace("\"", string.Empty); //} public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { // override the filename which is stored by the provider (by default is bodypart_x) string oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty); string newFileName = System.DateTime.Now.Ticks.ToString() + Path.GetExtension(oldfileName); return(newFileName); }
//BUTTON: UPDATE CRYPTO KEY private async void updatePublicKey_Click(object sender, RoutedEventArgs e) { var dialog = new MessageDialog("Updating your current key will cause previous messages to no longer be decryptable"); dialog.Title = "Are you sure?"; dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 }); dialog.Commands.Add(new UICommand { Label = "Cancel", Id = 1 }); var res = await dialog.ShowAsync(); IBuffer clientPublicKeyBUFFER = Crypto.returnPublicKey(App.secrets); byte[] clientPublicKeyBYTE = new byte[512]; WindowsRuntimeBufferExtensions.CopyTo(clientPublicKeyBUFFER, clientPublicKeyBYTE); string clientPublicKeySTRING = Convert.ToBase64String(clientPublicKeyBYTE); //Create a Key and Pair match with object data (prepared for POST request) var values = new Dictionary <string, string> { { "key", clientPublicKeySTRING }, { "user", App.userManagement.getURL_string() } }; var theContent = new FormUrlEncodedContent(values); if ((int)res.Id == 0) { //PUT REQUEST string publicKeyURL = App.userManagement.getPublicKey_string(); using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { var byteArray = Encoding.ASCII.GetBytes(App.userManagement.getCurrentUser_string() + ":" + currentUserPasswordActual.Password); var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Authorization = header; using (HttpResponseMessage response = await client.PutAsync(publicKeyURL, theContent)) //BUG: HANDLE OFFLINE MODE { using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; } } } MessageDialog msgbox2 = new MessageDialog("Overwriting serverside key"); await msgbox2.ShowAsync(); } if ((int)res.Id == 1) { //DO NOTHING MessageDialog msgbox2 = new MessageDialog("Cancelling request"); await msgbox2.ShowAsync(); } }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1); int secondsSinceEpoch = (int)t.TotalSeconds; string fname = secondsSinceEpoch + "_" + headers.ContentDisposition.FileName.Replace("\"", ""); return(fname); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { //截取文件扩展名 string exp = Path.GetExtension(headers.ContentDisposition.FileName.TrimStart('\"').TrimEnd('\"')); if (string.IsNullOrWhiteSpace(_fileNameWithoutExtension)) { _fileNameWithoutExtension = base.GetLocalFileName(headers); } return(_fileNameWithoutExtension + exp); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { string fileName; if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName)) { fileName = headers.ContentDisposition.FileName; } else { fileName = Guid.NewGuid().ToString() + ".data"; } return(fileName.Replace("\"", string.Empty)); }
//Loads conversation for the currentUser public async Task loadLastConversation(ListView aChatListView) { //GET request to server (fetch new messages from server at the same time) using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { using (HttpResponseMessage response = await client.GetAsync("http://159.203.252.197/messages")) //BUG: HANDLE OFFLINE MODE { if (App.DEBUG_MODE) { Debug.WriteLine("GET Status Code: " + response.StatusCode); Debug.WriteLine("GET Reason: " + response.ReasonPhrase); } using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; if (App.DEBUG_MODE) { Debug.WriteLine("GET content: " + content_string); Debug.WriteLine("GET content headers: " + content_headers); } //Load messages into chat list window List <MessageItem> incomingMessages = JsonConvert.DeserializeObject <List <MessageItem> >(content_string); for (int x = 0; x < incomingMessages.Count; x++) { //FILTER MESSAGES BASED ON PARTICIPANTS string checkUser = incomingMessages[x].returnObject_userid(incomingMessages[x]); if (checkUser == currentUser.user_name || checkUser == otherUser.user_name) { ListViewItem incomingItems = new ListViewItem(); //Outputs desired text into the actual chat window incomingItems.Content = incomingMessages[x].messageText(); //References the MessageItem object incomingItems.Tag = incomingMessages[x]; aChatListView.Items.Add(incomingItems); } } } } } }
//NON-USER INTERFACE METHODS //Verify keys with client and server private async void verifyKeys() { //Convert client key from IBUFFER to STRING IBuffer clientPublicKeyBUFFER = Crypto.returnPublicKey(App.secrets); byte[] clientPublicKeyBYTE = new byte[512]; WindowsRuntimeBufferExtensions.CopyTo(clientPublicKeyBUFFER, clientPublicKeyBYTE); string clientPublicKeySTRING = Convert.ToBase64String(clientPublicKeyBYTE); String serverPublicKey; //GET request to server (fetch new messages from server at the same time) string publicKeyURL = App.userManagement.getPublicKey_string(); if (publicKeyURL != null) { using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { using (HttpResponseMessage response = await client.GetAsync(publicKeyURL)) //BUG: HANDLE OFFLINE MODE { using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; dynamic incomingJSON = JsonConvert.DeserializeObject(content_string); serverPublicKey = incomingJSON.key; } } } } else { serverPublicKey = "-1"; } if (clientPublicKeySTRING != serverPublicKey) { var dialog = new MessageDialog("Please Update your public key"); dialog.Title = "WARNING: Local and Server public keys are not in sync"; dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 }); var res = await dialog.ShowAsync(); } }
//Class Methods public async void initUserAndConversation(ListView aCurrentUserListView) { //GET request to server to update chatListView with recentely POSTed message using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { using (HttpResponseMessage response = await client.GetAsync("http://159.203.252.197/users/")) { if (App.DEBUG_MODE) { Debug.WriteLine("GET Status Code: " + response.StatusCode); Debug.WriteLine("GET Reason: " + response.ReasonPhrase); } using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; if (App.DEBUG_MODE) { Debug.WriteLine("GET content: " + content_string); Debug.WriteLine("GET content headers: " + content_headers); } //TEMPORARY METHOD TO POST MESSAGES FROM SERVER TO CHAT VIEW this.userList = JsonConvert.DeserializeObject <List <UserDetails> >(content_string); Debug.WriteLine("CONVERSATION PRINT: " + userList[0].conversations_leading[0]); for (int x = 0; x < userList.Count; x++) { ListViewItem aUser = new ListViewItem(); aUser.Content = userList[x].user_name; //Outputs desired text into the actual chat window aUser.Tag = userList[x]; //References the UserAndConversation object aCurrentUserListView.Items.Add(aUser); } currentUser = userList[0]; } } } }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { string oldfileName = null; string newfileName = null; if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName)) { oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty); newfileName = Guid.NewGuid().ToString() + Path.GetExtension(oldfileName);; } //if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName)) //{ // fileName = headers.ContentDisposition.FileName; //} //else //{ //} return(newfileName); }
//Loads the selected conversation from the friends list into chatListView (TASK METHOD INSURES ALL VARIABLES LOAD) public async Task parseSelectedConversation(string urlOfConversation) { using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { using (HttpResponseMessage response = await client.GetAsync(urlOfConversation)) { using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; currentConversation = JsonConvert.DeserializeObject <ConversationDetails>(content_string); //Load data into the otherUser variable (person you're speaking with) by matching the currentUser's url tag with participants //If they match, set the otherUser variable to the other participant in the conversation if (currentConversation.participant_1 == currentUser.user_url) { HttpClient subClient = new HttpClient(); HttpResponseMessage subResponse = await subClient.GetAsync(this.currentConversation.participant_2); HttpContent subContent = subResponse.Content; string content_string2 = await subContent.ReadAsStringAsync(); //System.Net.Http.Headers.HttpContentHeaders content_headers2 = subContent.Headers; otherUser = JsonConvert.DeserializeObject <UserDetails>(content_string2); } else if (currentConversation.participant_2 == currentUser.user_url) { HttpClient subClient = new HttpClient(); HttpResponseMessage subResponse = await subClient.GetAsync(this.currentConversation.participant_1); HttpContent subContent = subResponse.Content; string content_string2 = await subContent.ReadAsStringAsync(); //System.Net.Http.Headers.HttpContentHeaders content_headers2 = subContent.Headers; otherUser = JsonConvert.DeserializeObject <UserDetails>(content_string2); } //Loads the otherUser's public key into memory { HttpClient subClient = new HttpClient(); HttpResponseMessage subResponse = await subClient.GetAsync(otherUser.public_key); HttpContent subContent = subResponse.Content; string content_string2 = await subContent.ReadAsStringAsync(); dynamic incomingJSON = JsonConvert.DeserializeObject(content_string2); otherUser.public_key_ACTUAL = incomingJSON.key; Debug.WriteLine("PUB KEY ACTUAL: " + otherUser.public_key_ACTUAL); } if (App.DEBUG_MODE == true) { Debug.WriteLine("CONVO URL: " + this.currentConversation.conversation_url); Debug.WriteLine("PART 1: " + this.currentConversation.participant_1); Debug.WriteLine("PART 2: " + this.currentConversation.participant_2); for (int x = 0; x < this.currentConversation.conversation_Messages.Count; x++) { Debug.WriteLine("MESSAGES: " + this.currentConversation.conversation_Messages[x]); } } } } } App.secrets.loadOtherUserPublicKey(otherUser.public_key_ACTUAL); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { return(headers.ContentDisposition.FileName.Replace("\"", string.Empty)); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : ""; return(guid + extension); }
public override void OnWriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, System.Net.TransportContext context) { var contacts = (IEnumerable <Contact>)value; var writer = new ContactFeedWriter(this.rootUri); writer.Write(stream, contacts); }
//Loads conversation for selected user /*private async void loadLastConversation() * { * //GET request to server (fetch new messages from server at the same time) * using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) * { * using (HttpResponseMessage response = await client.GetAsync("http://159.203.252.197/messages")) //BUG: HANDLE OFFLINE MODE * { * if (App.DEBUG_MODE) * { * Debug.WriteLine("GET Status Code: " + response.StatusCode); * Debug.WriteLine("GET Reason: " + response.ReasonPhrase); * } * using (HttpContent content = response.Content) * { * string content_string = await content.ReadAsStringAsync(); * System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers; * if (App.DEBUG_MODE) * { * Debug.WriteLine("GET content: " + content_string); * Debug.WriteLine("GET content headers: " + content_headers); * } * * //Load messages into chat list window * List<MessageItem> incomingMessages = JsonConvert.DeserializeObject<List<MessageItem>>(content_string); * for (int x = 0; x < incomingMessages.Count; x++) * { * ListViewItem incomingItems = new ListViewItem(); * * //Outputs desired text into the actual chat window * incomingItems.Content = incomingMessages[x].messageText(); * * //References the MessageItem object * incomingItems.Tag = incomingMessages[x]; * chatListView.Items.Add(incomingItems); * } * } * } * } * } */ //POST FUNCTION private async void postMessage(String input, Boolean secureStatus) { if (input != String.Empty && App.userManagement.conversationIsNotNull()) { //Encrypt text from input box if encryption is on // String timeStamp = DateTime.Now.ToString("MM/d/yy h:mm tt"); String finalInput; if (secureStatus == false) { finalInput = input; } else { finalInput = Crypto.Encrypt(App.strAsymmetricAlgName, Crypto.returnPublicKey_OTHER_USER(App.secrets), input); } //Load the text and associated message data into a messageItem object MessageItem newMessage = new MessageItem { conversation = App.userManagement.getConversationURL_string(), message = finalInput, userSent = App.userManagement.getOtherUserURL_string(), //timeStamp = timeStamp, userid = App.userManagement.getCurrentUser_string(), isEncrypted = secureStatus }; //Create a Key and Pair match with the new messageItem object data in preparation of Http request var values = new Dictionary <string, string> { { "conversation", newMessage.returnObject_conversation(newMessage) }, { "encrypted", newMessage.returnObject_isEncryptedString(newMessage) }, { "sentTo", "http://159.203.252.197/users/1/" }, { "text", newMessage.returnObject_message(newMessage) } }; //Encode the key pair match in preparation of Http request var theContent = new FormUrlEncodedContent(values); //POST request to the server with the encoded data (create HttpClient) using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use) { //Check HTTP data if (App.DEBUG_MODE == true) { Debug.WriteLine("POST CREDENTIALS: " + App.userManagement.getCurrentUser_string() + ":" + currentUserPasswordActual.Password); } //Load User credentials from currentUser and password field located on user interface into the client object var byteArray = Encoding.ASCII.GetBytes(App.userManagement.getCurrentUser_string() + ":" + currentUserPasswordActual.Password); var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Authorization = header; //Post the message to the server using (HttpResponseMessage response = await client.PostAsync("http://159.203.252.197/messages/", theContent)) { //Check HTTP data if (App.DEBUG_MODE) { Debug.WriteLine("POST Status Code: " + response.StatusCode); Debug.WriteLine("POST Reason: " + response.ReasonPhrase); using (HttpContent content = response.Content) { string content_string = await content.ReadAsStringAsync(); Debug.WriteLine("POST contents: " + content_string); } } //Refreshes ChatListView with recently POSTed string. If credentials are wrong, output INVALID CREDENTIALS to chatwindow if (response.IsSuccessStatusCode == true) { //GET request to server to update chatListView with recentely POSTed message using (HttpClient client2 = new HttpClient()) //using block makes the object disposable (one time use) { using (HttpResponseMessage response2 = await client2.GetAsync("http://159.203.252.197/messages/")) { //Check HTTP data if (App.DEBUG_MODE) { Debug.WriteLine("GET Status Code: " + response2.StatusCode); Debug.WriteLine("GET Reason: " + response2.ReasonPhrase); } using (HttpContent content2 = response2.Content) { string content_string2 = await content2.ReadAsStringAsync(); System.Net.Http.Headers.HttpContentHeaders content_headers2 = content2.Headers; //Check HTTP data if (App.DEBUG_MODE) { Debug.WriteLine("GET content: " + content_string2); Debug.WriteLine("GET content headers: " + content_headers2); } //TEMPORARY METHOD TO POST MESSAGES FROM SERVER TO CHAT VIEW List <MessageItem> incomingMessages = JsonConvert.DeserializeObject <List <MessageItem> >(content_string2); ListViewItem incomingItems = new ListViewItem(); int lastMessage = incomingMessages.Count - 1; incomingItems.Content = incomingMessages[lastMessage].messageText(); //Outputs desired text into the actual chat window incomingItems.Tag = incomingMessages[lastMessage]; //References the MessageItem object chatListView.Items.Add(incomingItems); } } } } else { var dialog = new MessageDialog(""); dialog.Title = "INVALID USER/PASSWORD COMBINATION"; dialog.Content = "You have entered the wrong password for the selected user, please try again"; dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 }); var res = await dialog.ShowAsync(); } } } } //Clear textbox and auto scroll to the bottom inputBox.Text = String.Empty; chatListViewScroller.UpdateLayout(); chatListViewScroller.ScrollToVerticalOffset(chatListView.ActualHeight); }
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, System.Net.TransportContext transportContext) { var attributes = value.GetType().GetCustomAttributes(true); if (attributes.Any(x => x is HalResourceAttribute)) { var result = new HalJsonResource(value); return(base.WriteToStreamAsync(result.GetType(), result, stream, contentHeaders, transportContext)); } else if (attributes.Any(x => x is HalResourceCollectionAttribute)) { var results = new HalJsonResourceCollection(value); return(base.WriteToStreamAsync(results.GetType(), results, stream, contentHeaders, transportContext)); } else if (value.GetType().IsArray) { var values = value as object[]; var items = new HalJsonResource[values.Length]; for (int i = 0; i < items.Length; i++) { IEnumerable <HalLink> halLinks = null; var lp = value.GetType().GetProperty("Links"); if (lp != null) { halLinks = lp.GetValue(value) as IEnumerable <HalLink>; } items[i] = new HalJsonResource(values[i]); } return(base.WriteToStreamAsync(items.GetType(), items, stream, contentHeaders, transportContext)); } return(base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext)); }
public override System.Threading.Tasks.Task <object> ReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, System.Net.Http.Formatting.IFormatterLogger formatterLogger) { return(base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger)); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName"; return(MakeUniqeName(_path + name.Replace("\"", ""))); }
public override void OnWriteToStream(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, System.Net.TransportContext context) { var singleContact = value as Contact; if (singleContact != null) { WriteEvent(singleContact, stream); } }
public override object OnReadFromStream(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders) { throw new NotImplementedException(); }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); return(fileName + "_" + headers.ContentDisposition.FileName.Replace("\"", string.Empty)); //base.GetLocalFileName(headers); }
public string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) { var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName"; return(name.Replace("\"", string.Empty)); }
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, System.Net.TransportContext transportContext) { if (type != null) { if (stream != null) { return(Task.Factory.StartNew(() => { using (var writer = System.Xml.XmlWriter.Create(stream)) { var r = new HalXmlResource(value); r.XmlDocument.WriteTo(writer); } })); } else { throw new System.ArgumentNullException("stream"); } } else { throw new System.ArgumentNullException("type"); } }
public static void PopulateHeaders(this HttpPacket packet, HttpContentHeaders contentHeaders, HttpHeaders generalHeaders) { if (packet == null) throw new ArgumentNullException("packet"); string hdrKey; foreach (var hdr in packet.Headers) { if (hdr.Key == null) continue; hdrKey = hdr.Key.Trim().ToUpperInvariant(); if (hdrKey == "CONTENT-LENGTH") continue; //Content Length is automaitically calculated if (Array.IndexOf<String>(contentOnlyHeaders, hdrKey) >= 0) { //TODO: Confirm if HttpResponseMessage/HttpRequestMessage will break headers into "," commas whereas in actuality header in Packet is an entire header contentHeaders.Add(hdr.Key.Trim(), hdr.Value); } else { generalHeaders.Add(hdr.Key.Trim(), hdr.Value); } //TODO: Check if a string can be parsed properly into the typed header //Test adding multiple headers of the same name will do. // Look up the Add overload that takes an ienumerable<string> to figure out its purpose. } }