A base class representing an HTTP entity body and content headers.
Inheritance: IDisposable
Example #1
1
        /*
         * Responsible for creating a success result of some sort.
         */
        async Task <Response <TOut> > GetSuccessResult <TOut>(
            net.HttpContent content,
            Response <TOut> responseResult)
        {
            if (typeof(TOut) == typeof(byte[]) || typeof(TOut) == typeof(object))
            {
                var contentType = content.Headers.ContentType?.MediaType ?? "application/json";
                switch (contentType)
                {
                case "application/json":
                case "application/hyperlambda":
                    responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();

                    break;

                default:
                    if (contentType.StartsWith("text/"))
                    {
                        responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();
                    }
                    else
                    {
                        responseResult.Content = (TOut)(object)await content.ReadAsByteArrayAsync();
                    }
                    break;
                }
            }
            else if (typeof(TOut) == typeof(string))
            {
                responseResult.Content = (TOut)(object)await content.ReadAsStringAsync();
            }
            else if (typeof(IConvertible).IsAssignableFrom(typeof(TOut)))
            {
                var txtContent = await content.ReadAsStringAsync();

                responseResult.Content = (TOut)Convert.ChangeType(txtContent, typeof(TOut));
            }
            else
            {
                var txtContent = await content.ReadAsStringAsync();

                var objResult = JToken.Parse(txtContent);
                responseResult.Content = objResult.ToObject <TOut>();
            }

            return(responseResult);
        }
Example #2
0
        private void PostData(string customer_id, string signature, string json, string logName, string date, string timestamp = "")
        {
            try
            {
                string url = "https://" + customer_id + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
                AFLog.LogInformation(url);

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", logName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", timestamp);

                System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                AFLog.LogInformation("Return Result: " + result);
            }
            catch (Exception ex)
            {
                AFLog.LogError("API Post Exception: " + ex.Message);
            }
        }
Example #3
0
        public async Task PostData(string logMessage)
        {
            try
            {
                //See code from https://docs.microsoft.com/en-us/azure/azure-monitor/platform/data-collector-api
                // Create a hash for the API signature
                var    datestring   = DateTime.UtcNow.ToString("r");
                var    jsonBytes    = Encoding.UTF8.GetBytes(logMessage);
                string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";
                string hashedString = BuildSignature(stringToHash, this.SharedKey);
                string signature    = "SharedKey " + this.CustomerId + ":" + hashedString;

                string url = "https://" + CustomerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", LogName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", datestring);
                //client.DefaultRequestHeaders.Add("time-generated-field", TimeStampField);

                System.Net.Http.HttpContent httpContent = new StringContent(logMessage, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
            }
            catch (Exception excep)
            {
                InternalLogger.Error("API Post Exception: " + excep.Message);
            }
        }
        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;
        }
Example #5
0
        //Login to the TDAmeritrade system
        public Boolean login2(String userName, String password)
        {
            Boolean hasLoggedinSuccessfully = false;


            String UrlAuthentication = "https://auth.tdameritrade.com/auth?response_type=code&redirect_uri={URLENCODED REDIRECT URI}&client_id={URLENCODED OAUTH USER ID}";

            UrlAuthentication = UrlAuthentication.Replace("{URLENCODED REDIRECT URI}", "http://localhost");
            UrlAuthentication = UrlAuthentication.Replace("{URLENCODED OAUTH USER ID}", this.key);
            System.Net.Http.HttpContent content = null;
            var isAuth = http.asyncPost(UrlAuthentication, content);

            String urlAddress = "/apps/300/LogIn?source=" + Uri.EscapeDataString(this.key) + "&version=" + Uri.EscapeDataString(this.version);

            urlAddress = BaseAddress + urlAddress;

            System.Net.Http.HttpContent httpContent = new System.Net.Http.FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("userid", userName),
                new KeyValuePair <string, string>("password", password),
                new KeyValuePair <string, string>("source", this.key),
                new KeyValuePair <string, string>("version", this.version)
            });



            var result = http.asyncPost(urlAddress, httpContent);

            return(hasLoggedinSuccessfully);
        }
Example #6
0
        public async Task StreamVideo(Stream stream, HttpContent content, TransportContext transport)
        {
            try
            {
                var buffer = new byte[65536];
                var filename = Path.Combine(String.Format("{0}{1}video.{2}", System.Web.HttpContext.Current.Server.MapPath("~"), Constants.FilePath, _fileExtension));
                using (var file = File.Open(filename, FileMode.Open, FileAccess.Read))
                {
                    var videoLength = (int)file.Length;
                    var placeInFile = 1;

                    while (videoLength > 0 && placeInFile > 0)
                    {
                        placeInFile = file.Read(buffer, 0, Math.Min(videoLength, buffer.Length));
                        await stream.WriteAsync(buffer, 0, placeInFile);
                        videoLength -= placeInFile;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.InnerException);
            }
            finally
            {
                stream.Close();
            }
        }
Example #7
0
 public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     return Task.Factory.StartNew(() =>
     {
         return (object)null;
     });
 }
        // Send a request to the POST API endpoint
        public static void PostData(string signature, string date, string json)
        {
            try
            {
                string url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", LogName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", TimeStampField);

                System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                Console.WriteLine("Return Result: " + result);
            }
            catch (Exception excep)
            {
                Console.WriteLine("API Post Exception: " + excep.Message);
            }
        }
        private string PostData(string postUrl, string logType, string authSignature, string xmsDate, string json)
        {
            try
            {
                var client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", logType);
                client.DefaultRequestHeaders.Add("Authorization", authSignature);
                client.DefaultRequestHeaders.Add("x-ms-date", xmsDate);
                client.DefaultRequestHeaders.Add("time-generated-field", "");

                var httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(postUrl, httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result + "";
                if (result == "")
                {
                    return("Return Result: Success - " + DateTime.Now.ToLocalTime().ToString());;
                }
                else
                {
                    return("Return Result: " + result);
                };
            }
            catch (Exception ex)
            {
                return("API Post Exception: " + ex.Message);
            }
        }
Example #10
0
        //public JsonFormatter()
        //{
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        //}
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = new TaskCompletionSource<object>();

              using (var ms = new MemoryStream())
              {
            readStream.CopyTo(ms);
            //ms.Seek(0, SeekOrigin.Begin);

            //var result = JsonSchemaValidator.Instance().Validate(ms, type);

            //if (!string.IsNullOrWhiteSpace(result))
            //  task.SetResult(result);
            //else
            {
              ms.Seek(0, SeekOrigin.Begin);
              using (var reader = new JsonTextReader(new StreamReader(ms)))
              {
            var serializer = new JsonSerializer();
            task.SetResult(serializer.Deserialize(reader, type));
              }
            }
              }
              return task.Task;
        }
Example #11
0
        public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[65536];

                using (var video = new MemoryStream(this.videoData))
                {
                    var length = (int)video.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (Exception ex)
            {
                return;
            }
            finally
            {
                outputStream.Close();
            }
        }
Example #12
0
        public static async Task GetAttachment(string url, string filename)
        {
            UriBuilder uriBuilder = new UriBuilder(url);

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(uriBuilder.ToString());
                client.DefaultRequestHeaders.Accept.Clear();
                HttpResponseMessage response = await client.GetAsync(uriBuilder.ToString());

                if (response.IsSuccessStatusCode)
                {
                    System.Net.Http.HttpContent content = response.Content;
                    var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream

                    using (var outputStream = File.OpenWrite(filename))
                    {
                        contentStream.CopyTo(outputStream);
                        contentStream.Flush();
                    }
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
        }
Example #13
0
        public async Task DownloadFile(string route, string filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }

            var httpClient = await GetHttpClient();

            HttpResponseMessage response = await httpClient.GetAsync(route);

            if (response.IsSuccessStatusCode)
            {
                System.Net.Http.HttpContent content = response.Content;
                var contentStream = await content.ReadAsStreamAsync();

                using (var stream = new FileStream(filename, FileMode.Create))
                {
                    await contentStream.CopyToAsync(stream);
                }
            }
            else
            {
                throw new FileNotFoundException();
            }
        }
Example #14
0
 private static void Request_GET(string url, string timeKey)
 {
     System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(async() =>
     {
         try
         {
             using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
             {
                 using (System.Net.Http.HttpResponseMessage response = await client.GetAsync(url))
                 {
                     using (System.Net.Http.HttpContent content = response.Content)
                     {
                         string myContent = await content.ReadAsStringAsync();
                         dicResult.Add(timeKey, myContent);
                     }
                 }
             }
         }
         catch (System.Net.Http.HttpRequestException)
         {
         }
     }))
     {
         IsBackground = true
     };
     th.Start();
 }
Example #15
0
        public static async Task <int> obLogAnalytics(string newClientContent, ILogger log)
        {
            // Update customerId to your Log Analytics workspace ID
            string customerId = Util.GetEnvironmentVariable("customerId");

            // For sharedKey, use either the primary or the secondary Connected Sources client authentication key
            string sharedKey = Util.GetEnvironmentVariable("sharedKey");

            // LogName is name of the event type that is being submitted to Azure Monitor
            string LogName = "DemoExample";

            // You can use an optional field to specify the timestamp from the data. If the time field is not specified, Azure Monitor assumes the time is the message ingestion time
            string TimeStampField = "";

            var    records    = denormalizedRecords(newClientContent, null, log);
            string serialized = JsonConvert.SerializeObject(records, new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                }
            });

            // Create a hash for the API signature
            var    datestring   = DateTime.UtcNow.ToString("r");
            var    jsonBytes    = Encoding.UTF8.GetBytes(serialized);
            string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";
            string hashedString = BuildSignature(stringToHash, sharedKey);
            string signature    = "SharedKey " + customerId + ":" + hashedString;

            try
            {
                string url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", LogName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", datestring);
                client.DefaultRequestHeaders.Add("time-generated-field", TimeStampField);

                System.Net.Http.HttpContent httpContent = new StringContent(serialized, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = await client.PostAsync(new Uri(url), httpContent);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    log.LogError($"StatusCode from Loganalytics: {response.StatusCode}, and reason: {response.ReasonPhrase}");
                }
                System.Net.Http.HttpContent responseContent = response.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                Console.WriteLine("Return Result: " + result);
                return(jsonBytes.Length);
            }
            catch (Exception ex)
            {
                log.LogError($"Unknown error caught while sending to Loganalytics: \"{ex.Message}\"");
                throw ex;
            }
        }
Example #16
0
        protected virtual void OnStreamAvailable(Stream stream, System.Net.Http.HttpContent content, System.Net.TransportContext context)
        {
            string lastMessageId = GetLastMessageId(content);
            Client client        = new Client(stream, lastMessageId);

            AddClient(client);
        }
Example #17
0
 /*
  * Decorates the HTTP content with the relevant HTTP headers from the
  * specified dictionary.
  */
 void AddContentHeaders(
     net.HttpContent content,
     Dictionary <string, string> headers)
 {
     foreach (var idx in headers.Keys)
     {
         /*
          * Adding all Content HTTP headers, and ignoring the rest
          */
         switch (idx)
         {
         case "Allow":
         case "Content-Disposition":
         case "Content-Encoding":
         case "Content-Language":
         case "Content-Length":
         case "Content-Location":
         case "Content-MD5":
         case "Content-Range":
         case "Content-Type":
         case "Expires":
         case "Last-Modified":
             if (content.Headers.Contains(idx))
             {
                 content.Headers.Remove(idx);
             }
             content.Headers.Add(idx, headers[idx]);
             break;
         }
     }
 }
Example #18
0
        // Send a request to the POST API endpoint
        private void PostData(string omsWorkspaceId, string logName, string signature, string date, string json)
        {
            try
            {
                string url = "https://" + omsWorkspaceId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", logName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", "");

                System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
            }
            catch (Exception x)
            {
                //Console.WriteLine(x.Message);
                // do nothing, fail silently
            }
        }
Example #19
0
        public static string BuildBase64Signature(
                string apiKey,
                string appId,
                Uri rawUri,
                HttpMethod httpMethod,
                HttpContent content,
                string nonce,
                string requestTimeStamp
            )
        {
            var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
            var requestHttpMethod = httpMethod.Method;

            // Get the content string out of the content.
            string requestContentBase64String = ComputeBase64RequestContent(content);

            // Rebuild the signature raw data.
            var signatureRawData =
            $"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";

            // Get the api key bytes.
            var secretKeyBytes = Convert.FromBase64String(apiKey);

            // Get the signature.
            var signature = Encoding.UTF8.GetBytes(signatureRawData);

            // Create HMAC SHA class with key data.
            using (var hmac = new HMACSHA256(secretKeyBytes))
            {
                return Convert.ToBase64String(hmac.ComputeHash(signature));
            }
        }
        //below only allows images and pdf files to be uploaded.
        public override Stream GetStream(System.Net.Http.HttpContent parent, System.Net.Http.Headers.HttpContentHeaders headers)
        {
            // following line handles other form fields other than files.
            if (String.IsNullOrEmpty(headers.ContentDisposition.FileName))
            {
                return(base.GetStream(parent, headers));
            }

            // restrict what filetypes can be uploaded
            List <string> extensions = new List <string> {
                "png", "gif",
                "jpg", "jpeg", "tiff", "pdf", "tif", "bmp", "doc", "docx", "ods", "xls", "odt", "csv", "txt", "rtf"
            };
            var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty); // correct for chrome.

            //make sure it has an extension
            if (filename.IndexOf('.') < 0)
            {
                return(Stream.Null);
            }

            //get the extension
            var extension = filename.Split('.').Last();

            //Return stream if match otherwise return null stream.
            return(extensions.Contains(extension) ? base.GetStream(parent, headers) : Stream.Null);
        }
Example #21
0
        public async Task <ActionResult> GetAttachment(int FileID)
        {
            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = "https";
            uriBuilder.Host   = "api.example.com";

            var Path = "/files/download";

            uriBuilder.Path = Path;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(uriBuilder.ToString());
                client.DefaultRequestHeaders.Accept.Clear();
                //client.DefaultRequestHeaders.Add("authorization", access_token); //if any
                //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(uriBuilder.ToString());

                if (response.IsSuccessStatusCode)
                {
                    response.Headers[""];
                    System.Net.Http.HttpContent content = response.Content;
                    var contentStream = await content.ReadAsStreamAsync();                     // get the actual content stream

                    return(File(contentStream, content_type, filename));
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
        }
Example #22
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew<object>( () => 
            {
                try
                {
                    var body = base.ReadBodyFromStream(readStream, content);

                    if (type == typeof(Bundle))
                    {
                        if (XmlSignatureHelper.IsSigned(body))
                        {
                            if (!XmlSignatureHelper.VerifySignature(body))
                                throw Error.BadRequest("Digital signature in body failed verification");
                        }
                    }

                    if (typeof(Resource).IsAssignableFrom(type))
                    {
                        Resource resource = FhirParser.ParseResourceFromXml(body);
                        return resource;
                    }
                    else
                        throw Error.Internal("The type {0} expected by the controller can not be deserialized", type.Name);
                }
                catch (FormatException exc)
                {
                    throw Error.BadRequest("Body parsing failed: " + exc.Message);
                }
            });
        }
Example #23
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, Encoding.UTF8);
                // todo: klopt het dat Bundle wel en <?xml ...> header heeft een Resource niet?
                // follow up: is now ticket in FhirApi. Check later.

                if (type == typeof(OperationOutcome)) 
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer);
                }
                else if (type == typeof(ResourceEntry))
                {
                    ResourceEntry entry = (ResourceEntry)value;
                    FhirSerializer.SerializeResource(entry.Resource, writer);
                    
                    content.Headers.SetFhirTags(entry.Tags);
                }

                else if (type == typeof(Bundle))
                {
                    FhirSerializer.SerializeBundle((Bundle)value, writer);
                }
                else if (type == typeof(TagList))
                {
                    FhirSerializer.SerializeTagList((TagList)value, writer); 
                }
                
                writer.Flush();
            });
        }
Example #24
0
        async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
        {
            try
            {
                var buffer = new byte[_chunkSize];
                using (var inputStream = OpenInputStream())
                {
                    var length = (int)inputStream.Length;
                    var bytesRead = 1;

                    while (length > 0 && bytesRead > 0)
                    {
                        bytesRead = inputStream.Read(buffer, 0, Math.Min(length, buffer.Length));
                        await outputStream.WriteAsync(buffer, 0, bytesRead);
                        length -= bytesRead;
                    }
                }
            }
            catch (HttpException)
            {
            }
            finally
            {
                outputStream.Close();
                outputStream.Dispose();
            }
        }
        /// <summary>
        /// Creates the web request.
        /// </summary>
        /// <param name="uri">The request Uri.</param>
        /// <param name="timeout">The timeout.</param>
        /// <param name="builder">The builder.</param>
        /// <returns>A web request for performing the operation.</returns>
        internal static StorageRequestMessage CreateRequestMessage(HttpMethod method, Uri uri, int? timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
        {
            if (builder == null)
            {
                builder = new UriQueryBuilder();
            }

            if (timeout.HasValue && timeout.Value > 0)
            {
                builder.Add("timeout", timeout.ToString());
            }

#if WINDOWS_RT && !NETCORE
            // Windows Phone does not allow the caller to disable caching, so a random GUID
            // is added to every URI to make it look like a different request.
            builder.Add("randomguid", Guid.NewGuid().ToString("N"));
#endif

            Uri uriRequest = builder.AddToUri(uri);

            StorageRequestMessage msg = new StorageRequestMessage(method, uriRequest, canonicalizer, credentials, credentials.AccountName);
            msg.Content = content;

            return msg;
        }
Example #26
0
        public CompressedContent(HttpContent content, string encodingType)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (encodingType == null)
            {
                throw new ArgumentNullException("encodingType");
            }

            originalContent = content;
            this.encodingType = encodingType.ToLowerInvariant();

            if (this.encodingType != "gzip" && this.encodingType != "deflate")
            {
                throw new InvalidOperationException(string.Format("Encoding '{0}' is not supported. Only supports gzip or deflate encoding.", this.encodingType));
            }

            // copy the headers from the original content
            foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
            {
                Headers.TryAddWithoutValidation(header.Key, header.Value);
            }

            Headers.ContentEncoding.Add(encodingType);
        }
        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
        {
            if (type == typeof (AdminProject))
            {
                var project = (AdminProject)value;
                await WriteAsync(project, writeStream, cancellationToken);
            }
            else if (typeof (IEnumerable<AdminProject>).IsAssignableFrom(type))
            {
                var projects = (IEnumerable<AdminProject>)value;
                foreach (AdminProject project in projects)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    await WriteAsync(project, writeStream, cancellationToken);
                }
            }
            else
            {
                throw new NotSupportedException("Cannot serialize type");
            }
        }
Example #28
0
        HttpAbfrage(String Ziel, HttpContent content)
        {
           
            //################################################################################################

            var httpClient = new HttpClient();      // Neue httpClient instanz

            //##################################################################################################
            // mit Cockies aber nicht zu ende Programmiert weil wir keine Cockies nutzen 

            CookieContainer cookie = new CookieContainer();             // Cockie Container Construcktor
            HttpClientHandler handler = new HttpClientHandler()         // nutze beim zugriff cockies
            {
            };
            HttpClient client = new HttpClient(handler as HttpMessageHandler) // neuer http client
            {
                BaseAddress = new Uri(GlobalData.Uri2 + Ziel + GlobalData.SessionID)     // hier wird auch gleich die Session an das ziel angehangen                                        // url aus uri 2 nutzen test2.php
            };
            handler.UseCookies = false;                                        // beim zugriff cockies nicht zulassen
            handler.UseDefaultCredentials = false;

            //#################################################################################################
            // Jetzt mit POST
            // Schritt 4 Abfrage abschicken und ergebnis entgegennehmen 
            HttpResponseMessage response = await httpClient.PostAsync(client.BaseAddress, content); // schicke die abfrage an die Url , dann warte bis antwort komplett und speicher erst mal alles
            GlobalData.HttpResponse = await response.Content.ReadAsStringAsync();
           // MessageDialog msgboxRespons = new MessageDialog(GlobalData.HttpResponse);
           // await msgboxRespons.ShowAsync();        // Zeige mir an was angekommen ist 
            return GlobalData.HttpResponse;
        }
 public override Task<object> ReadFromStreamAsync(Type type, System.IO.Stream readStream, HttpContent content, System.Net.Http.Formatting.IFormatterLogger formatterLogger)
 {
     var commandType = type;
     if (type.IsAbstract || type.IsInterface)
     {
         var commandContentType = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "command");
         if (commandContentType != null)
         {
             commandType = GetCommandType(HttpUtility.UrlDecode(commandContentType.Value));
         }
         else
         {
             commandType = GetCommandType(HttpContext.Current.Request.Url.Segments.Last());
         }
     }
     var part = content.ReadAsStringAsync();
     var mediaType = content.Headers.ContentType.MediaType;
     return Task.Factory.StartNew<object>(() =>
     {
         object command = null;
         if (mediaType == "application/x-www-form-urlencoded" || mediaType == "application/command+form")
         {
             command = new FormDataCollection(part.Result).ConvertToObject(commandType);
         }
         if (command == null)
         {
             command = part.Result.ToJsonObject(commandType);
         }
         return command;
     });
 }
Example #30
0
 public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     var reader = new StreamReader(readStream);
     var deserialize = TypedDeserializers.GetTyped(type);
     var result = deserialize(reader, options);
     return Task.FromResult(result);
 }
        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;
        }
Example #32
0
 public void WriteToStream(Type type, object value, Stream stream, HttpContent content)
 {
     Author author = (Author)value;
     Image image = Image.FromFile(@"D:\dev\CodicePlastico\WebApiBook\HelloWebApi\HelloWebApi\Content\Photos\" + author.Name + ".png");
     image.Save(stream, ImageFormat.Png);
     image.Dispose();
 }
        public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
                                                        HttpContent httpContent,
                                                        IFormatterLogger iFormatterLogger)
        {
            MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();
            IEnumerable<HttpContent> contents = parts.Contents;

            HttpContent content = contents.FirstOrDefault();
            foreach (HttpContent c in contents ) {
                if (SupportedMediaTypes.Contains(c.Headers.ContentType)) {
                    content = c;
                    break;
                }
            }

            using (var msgStream = await content.ReadAsStreamAsync())
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
                TenMsg msg = (TenMsg)js.ReadObject(msgStream);
                Debug.WriteLine("msgString: " + msgStream.ToString());

                int sender = msg.Sender;
                int receiver = msg.Receiver;
                byte phoneType = msg.PhoneType;
                bool isLocked = msg.IsLocked;
                DateTime msgTime = msg.MsgTime;
                string msgContent = msg.MsgContent;
                Debug.WriteLine("Msg Content: " + msg.MsgContent);
                
                return new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent);
            }
        }
 public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
 {
     MultipartMemoryStreamProvider multipartMemoryStreamProvider = await content.ReadAsMultipartAsync();
     Collection<HttpContent> contents = multipartMemoryStreamProvider.Contents;
     ImageSet imageSet = await contents.FirstOrDefault<HttpContent>((HttpContent c) => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset").ReadAsAsync<ImageSet>();
     ImageSet images = imageSet;
     Collection<HttpContent> httpContents = multipartMemoryStreamProvider.Contents;
     List<HttpContent> list = (
         from c in httpContents
         where c.Headers.ContentDisposition.Name.NormalizeName().Matches("image\\d+")
         select c).ToList<HttpContent>();
     images.Images = new List<Image>();
     foreach (HttpContent httpContent in list)
     {
         List<Image> images1 = images.Images;
         Image image = new Image();
         Image image1 = image;
         image1.ImageData = await httpContent.ReadAsByteArrayAsync();
         image.MimeType = httpContent.Headers.ContentType.MediaType;
         image.FileName = httpContent.Headers.ContentDisposition.FileName.NormalizeName();
         images1.Add(image);
         images1 = null;
         image1 = null;
         image = null;
     }
     return images;
 }
 private static string ReadContentAsync(HttpContent content)
 {
     Task task = content.LoadIntoBufferAsync();
     task.Wait(TimeoutConstant.DefaultTimeout);
     Assert.Equal(TaskStatus.RanToCompletion, task.Status);
     return content.ReadAsStringAsync().Result;
 }
Example #36
0
 public static void VerifyResponse(HttpContent responseContent, string expected)
 {
     string response = responseContent.ReadAsStringAsync().Result;
     Regex updatedRegEx = new Regex("<updated>*.*</updated>");
     response = updatedRegEx.Replace(response, "<updated>UpdatedTime</updated>");
     Assert.Xml.Equal(expected, response);
 }
Example #37
0
        // Send a request to the POST API endpoint
        public static void PostData(string signature, string date, string json, string customerId, string LogName, TraceWriter log)
        {
            // You can use an optional field to specify the timestamp from the data. If the time field is not specified, Log Analytics assumes the time is the message ingestion time
            string TimeStampField = "";

            try
            {
                string url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", LogName);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", date);
                client.DefaultRequestHeaders.Add("time-generated-field", TimeStampField);

                System.Net.Http.HttpContent httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                log.Error("Return Result: " + result);
            }
            catch (Exception excep)
            {
                log.Error("API Post Exception: " + excep.Message);
            }
        }
        /// <summary>
        /// Sets the response of the current <see cref="T:MockedRequest"/>
        /// </summary>
        /// <param name="source">The source mocked request</param>
        /// <param name="statusCode">The <see cref="T:HttpStatusCode"/> of the response</param>
        /// <param name="content">The content of the response</param>
        public static void Respond(this MockedRequest source, HttpStatusCode statusCode, HttpContent content)
        {
            HttpResponseMessage message = new HttpResponseMessage(statusCode);
            message.Content = content;

            source.Respond(message);
        }
Example #39
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            
            return Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
                bool summary = requestMessage.RequestSummary();

                if (type == typeof(OperationOutcome)) 
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);
                }
                else if (type.IsAssignableFrom(typeof(Resource)))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);
                    
                    content.Headers.ContentLocation = resource.ExtractKey().ToUri();
                }
                else if (type == typeof(FhirResponse))
                {
                    FhirResponse response = (value as FhirResponse);
                    if (response.HasBody)
                    FhirSerializer.SerializeResource(response.Resource, writer, summary);
                }
                
                writer.Flush();
            });
        }
        private Dictionary<string, string> ConvertHeaders(HttpResponseHeaders responseHeaders, HttpContent httpContent)
        {
            if ((responseHeaders == null || !responseHeaders.Any()) &&
                (httpContent == null || (httpContent.Headers == null || !httpContent.Headers.Any())))
            {
                return null;
            }

            var headers = new Dictionary<string, string>();

            if (responseHeaders != null && responseHeaders.Any())
            {
                foreach (var responseHeader in responseHeaders)
                {
                    headers.Add(responseHeader.Key, String.Join(", ", responseHeader.Value.Select(x => x)));
                }
            }

            if (httpContent != null && httpContent.Headers != null && httpContent.Headers.Any())
            {
                foreach (var contentHeader in httpContent.Headers)
                {
                    headers.Add(contentHeader.Key, String.Join(", ", contentHeader.Value.Select(x => x)));
                }
            }

            return headers;
        }
        /// <summary>
        /// This method posts a json object to the OMS Workspace, into a table called "CustomLogName"_CL
        /// </summary>
        /// <param name="WorkSpaceId">OMS WorkSpace ID</param>
        /// <param name="WorkSpaceKey">OMS WorkSpace Key</param>
        /// <param name="CustomLogName">Name of the CustomLog Table, automatically appended with "_CL" in OMS</param>
        /// <param name="EventJson">JSON object containing one or more log events. Each property will be dynamically created as a column in OMS</param>
        /// <returns></returns>
        public static string Send(string WorkSpaceId, string WorkSpaceKey, string CustomLogName, string EventJson)
        {
            var    eventDate    = DateTime.UtcNow.ToString("r");
            var    jsonBytes    = Encoding.UTF8.GetBytes(EventJson);
            string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + eventDate + "\n/api/logs";

            var signature = BuildSignature(stringToHash, WorkSpaceKey);

            try
            {
                string url = "https://" + WorkSpaceId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Log-Type", CustomLogName);
                client.DefaultRequestHeaders.Add("Authorization", "SharedKey " + WorkSpaceId + ":" + signature);
                client.DefaultRequestHeaders.Add("x-ms-date", eventDate);
                client.DefaultRequestHeaders.Add("time-generated-field", eventDate);

                System.Net.Http.HttpContent httpContent = new StringContent(EventJson, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                return(responseContent.ReadAsStringAsync().Result);
            }
            catch (Exception excep)
            {
                throw new Exception("API Post Exception: " + excep.Message);
            }
        }
        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);
        }
Example #43
0
        public async Task Download()
        {
            var index = 0;

            for (int i = 0; i < files.Count; i++)
            {
                if (files[i] == selectedfile)
                {
                    index = i;
                }
            }
            if (index != 0)
            {
                UploadText.Text = selectedfile + " has been downloaded to [DownloadBook] folder!";
                string path = downloadpath + "\\" + selectedfile;
                Console.Write("\n[{0} has been downloaded to {1}!]", files[index], path);
                //download file
                string display = baseUrl_ + "/" + index;
                var    resp2   = await client.GetAsync(baseUrl_ + "/" + index).ConfigureAwait(false);

                System.Net.Http.HttpContent content = resp2.Content;       // actually a System.Net.Http.StreamContent instance but you do not need to cast as the actual type does not matter in this case
                using (var file = System.IO.File.Create(path))
                {                                                          // create a new file to write to
                    var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream

                    await contentStream.CopyToAsync(file);                 // copy that stream to the file stream

                    await file.FlushAsync();                               // flush back to disk before disposing
                }
            }
        }
Example #44
0
        private static async Task GetAttachment(int FileID)
        {
            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = "https";
            uriBuilder.Host   = "www1.nseindia.com/content/historical/EQUITIES/2020/MAR/cm04MAR2020bhav.csv.zip";
            //https://www1.nseindia.com/content/historical/EQUITIES/2020/MAR/cm04MAR2020bhav.csv.zip
            var Path = "/files/download";

            uriBuilder.Path = Path;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(uriBuilder.ToString());
                client.DefaultRequestHeaders.Accept.Clear();
                //client.DefaultRequestHeaders.Add("authorization", access_token); //if any
                //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(uriBuilder.ToString());

                if (response.IsSuccessStatusCode)
                {
                    System.Net.Http.HttpContent content = response.Content;
                    var contentStream = await content.ReadAsStreamAsync(); // get the actual content stream

                    // return File(contentStream, content_type, filename);
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
        }
Example #45
0
 private async Task<HttpResponseMessage> DoPostAsync(Uri uri, HttpContent content)
 {
     _logger.LogInformation("POST {0}", uri.ToString());
     var resp= await _httpClient.PostAsync(uri, content);
     LogHeaders(resp, LogLevel.Information);
     return resp;
 }
 /// <summary>
 /// Generates a web request to return the user-defined metadata for this container.
 /// </summary>
 /// <param name="uri">The absolute URI to the container.</param>
 /// <param name="timeout">The server timeout interval.</param>
 /// <param name="accessCondition">The access condition to apply to the request.</param>
 /// <returns>A web request to use to perform the operation.</returns>
 public static HttpRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
 {
     UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
     HttpRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext);
     request.ApplyAccessCondition(accessCondition);
     return request;
 }
Example #47
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                MemoryStream stream = new MemoryStream();
                readStream.CopyTo(stream);

                IEnumerable<string> xContentHeader;
                var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);

                if (!success)
                {
                    throw Error.BadRequest("POST to binary must provide a Content-Type header");
                }

                string contentType = xContentHeader.FirstOrDefault();

                Binary binary = new Binary();
                binary.Content = stream.ToArray();
                binary.ContentType = contentType;

                //ResourceEntry entry = ResourceEntry.Create(binary);
                //entry.Tags = content.Headers.GetFhirTags();
                return (object)binary;
            });
        }
		private async Task<JObject> AuthRequest(string path, string method, HttpContent data, RequestingUser u) {

			using(HttpClientHandler handler = new HttpClientHandler())
			using(HttpClient client = new HttpClient(handler)) {

				HttpResponseMessage msg = null;
				string str;

				if(u != null) {
					handler.UseCookies = true;
					handler.CookieContainer = new CookieContainer();
					u.Cookies.ToList().ForEach(c => handler.CookieContainer.Add(c));
					client.DefaultRequestHeaders.Add("x-csrf", u.CsrfToken);
				}
				else {
					handler.UseCookies = false;
				}

				if(method.ToUpper() == WebRequestMethods.Http.Get.ToUpper()) {
					msg = await client.GetAsync(BungieNet.PlatformPath + path);
				}
				else if(method.ToUpper() == WebRequestMethods.Http.Post.ToUpper()) {
					msg  = await client.PostAsync(BungieNet.PlatformPath + path, data);
				}

				str = await msg.Content.ReadAsStringAsync();

				return JObject.Parse(str);

			}

		}
        /// <summary>
        /// Reads from application/json message
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private async static Task <OAuthROCRequest> ReadJson(System.Net.Http.HttpContent content)
        {
            var raw = await content.ReadAsStringAsync();

            var serializer  = JsonSerializer.Create();
            var dicitionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(raw);

            return(FromDictionary(dicitionary));
        }
        /// <summary>
        /// Reads from application/xml message
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private async static Task <OAuthROCRequest> ReadXml(System.Net.Http.HttpContent content)
        {
            var raw = await content.ReadAsStringAsync();

            var root       = XElement.Parse(raw);
            var dictionary = root.Elements()
                             .ToDictionary(e => e.Name.LocalName, e => e.Value);

            return(FromDictionary(dictionary));
        }
Example #51
0
        public string ReadResponse(HttpResponseMessage response)
        {
            string result = string.Empty;

            System.Net.Http.HttpContent sm = response.Content;
            Task <string> res = sm.ReadAsStringAsync();

            result = res.Result;
            return(result);
        }
Example #52
0
        public async Task <IHttpResponseMessage> PutAsync(Uri requestUri, IHttpContent content, CancellationToken cancellationToken)
        {
            Http.HttpContent httpContent = null;
            if (content != null)
            {
                httpContent = ((HttpContent)content).Content;
            }
            var response = await client.PutAsync(requestUri, httpContent, cancellationToken);

            return(new HttpResponseMessage(response));
        }
        public override Task WriteToStreamAsync
        (
            Type type, object value,
            Stream stream,
            System.Net.Http.HttpContent content,
            System.Net.TransportContext transportContext
        )
        {
            string callback;

            /*
             * if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback))
             * {
             *  return Task.Factory.StartNew
             *  (
             *      () =>
             *      {
             *          var writer = new StreamWriter(stream);
             *          writer.Write(string.Format("callback{0}", "("));
             *          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
             *              );
             * }
             */

            return(default(Task));
        }
Example #54
0
        /// <summary>
        /// Get all tracks from serverDb
        /// </summary>
        /// <returns></returns>
        public static List <Track> GetTracks()
        {
            var responseTask = client.GetAsync("track");

            responseTask.Wait();

            var result = responseTask.Result;
            IDictionary <string, dynamic> json = null;

            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync <IDictionary <string, dynamic> >();
                readTask.Wait();
                json = readTask.Result;
            }
            List <Track> tracks = JsonConvert.DeserializeObject <List <Track> >(json["objects"].ToString());

            foreach (var track in tracks)
            {
                string[] splitAlbumPath = track.album.Split('/');
                track.album = splitAlbumPath[splitAlbumPath.Length - 1];

                // < Audio download >
                var httpResponseMessage = dlClient.GetAsync("song_file/" + track.id + "/");
                httpResponseMessage.Wait();

                var resp = httpResponseMessage.Result;
                if (resp.IsSuccessStatusCode)
                {
                    System.Net.Http.HttpContent content = resp.Content;
                    string format = content.Headers.ContentDisposition.FileName.Split('.')[content.Headers.ContentDisposition.FileName.Split('.').Length - 1];
                    format = format.Replace("\"", "");

                    if (format == "wav" || format == "mp3")
                    {
                        Stream contentStream = content.ReadAsStreamAsync().Result; // get the actual content stream

                        string path = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)).LocalPath + "/Data/Tracks/" + track.title + "." + format;

                        using (FileStream fileStream = File.Create(path))
                        {
                            contentStream.Seek(0, SeekOrigin.Begin);
                            contentStream.CopyTo(fileStream);
                            track.audio = path;
                        }
                    }
                }
                // </ Audio download >
            }
            return(tracks);
        }
        /// <summary>
        /// Reads from application/x-www-form-urlencoded message
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        private async static Task <OAuthROCRequest> ReadForm(System.Net.Http.HttpContent content)
        {
            var raw = await content.ReadAsStringAsync();

            var tokens     = raw.Split('&');
            var dictionary = new Dictionary <string, string>();

            foreach (var token in tokens)
            {
                var kp = token.Split('=');
                dictionary[Uri.UnescapeDataString(kp[0])] = Uri.UnescapeDataString(kp[1]);
            }

            return(FromDictionary(dictionary));
        }
        protected override void OnStreamAvailable(Stream stream, System.Net.Http.HttpContent content, System.Net.TransportContext context)
        {
            ClientInfo info = default(ClientInfo);

            if (content is PushStreamContentWithClientInfomation <ClientInfo> )
            {
                PushStreamContentWithClientInfomation <ClientInfo> contentWithInfo = content as PushStreamContentWithClientInfomation <ClientInfo>;
                info = contentWithInfo.Info;
            }

            string lastMessageId = GetLastMessageId(content);
            ClientWithInformation <ClientInfo> client = new ClientWithInformation <ClientInfo>(stream, lastMessageId, info);

            AddClient(client);
        }
Example #57
0
        public async Task <FileDTO> GetExampleFileAsync()
        {
            /*
             * TODO - esse método poderia ser melhorado. Em vez de ler o arquivo do disco,
             * seria mais interessante gerar um arquivo de exemplo com as configurações presentes
             * no appsettings.json referentes à posição e tamanho dos campos. Dessa forma, se mudarmos
             * o layout do arquivo, não temos que alterar o arquivo de "exemplo".
             */
            FileDTO file = new FileDTO();

            file.ContentType = "text/plain";
            file.Extension   = "txt";
            file.Name        = "EXAMPLE.txt";
            file.Content     = new MemoryStream();

            if (this._fileServerSettings.Type == "file")
            {
                using (FileStream fs = new FileStream(this._fileServerSettings.Path, FileMode.Open, FileAccess.Read))
                {
                    await fs.CopyToAsync(file.Content);

                    file.Content.Position = 0;
                }
            }
            else
            {
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(this._fileServerSettings.Path);

                    if (response.IsSuccessStatusCode)
                    {
                        System.Net.Http.HttpContent content = response.Content;
                        var contentStream = await content.ReadAsStreamAsync();

                        await contentStream.CopyToAsync(file.Content);

                        file.Content.Position = 0;
                    }
                    else
                    {
                        throw new FileNotFoundException("Impossível obter arquivo do servidor");
                    }
                }
            }

            return(file);
        }
Example #58
0
        public async Task <string> GetDataJson(string url, string param)
        {
            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url + param))
                    using (System.Net.Http.HttpContent content = response.Content)
                    {
                        string result = await content.ReadAsStringAsync();

                        if (result != null &&
                            result.Length >= 50)
                        {
                            return(result);
                        }
                    }
            return("");
        }
Example #59
0
    public String sendData(String returnedData)      // Sends parsed data to the correct table in our Log Analytics instance
    {
        // Build authorization signature for API POST. Details of this are here: https://docs.microsoft.com/en-us/azure/azure-monitor/platform/data-collector-api
        var    customerID   = "<customer/appID>";
        var    sharedKey    = "<Log Analytics Shared Key>";
        var    logName      = "<Log Analytics Table Name>"; // Name of the table in Log Analytics
        var    datestring   = DateTime.UtcNow.ToString("r");
        var    jsonBytes    = Encoding.UTF8.GetBytes(returnedData);
        string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";

        var encoding = new System.Text.ASCIIEncoding();

        byte[] keyByte      = Convert.FromBase64String(sharedKey);
        byte[] messageBytes = encoding.GetBytes(stringToHash);
        var    hmacsha256   = new HMACSHA256(keyByte);

        byte[] hash         = hmacsha256.ComputeHash(messageBytes);
        String hashedString = Convert.ToBase64String(hash);
        string signature    = "SharedKey " + customerID + ":" + hashedString;

        // Send POST call containing our data to the Log Analytics API endpoint
        try
        {
            string url = "https://" + customerID + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.DefaultRequestHeaders.Add("Log-Type", logName);
            client.DefaultRequestHeaders.Add("Authorization", signature);
            client.DefaultRequestHeaders.Add("x-ms-date", datestring);
            client.DefaultRequestHeaders.Add("time-generated-field", datestring);

            System.Net.Http.HttpContent httpContent = new StringContent(returnedData, Encoding.UTF8);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            Task <System.Net.Http.HttpResponseMessage> response = client.PostAsync(new Uri(url), httpContent);

            System.Net.Http.HttpContent responseContent = response.Result.Content;
            string result = responseContent.ReadAsStringAsync().Result;
            returnedData = result;
        }
        catch (Exception excep)                 // Catch bad repsonses
        {
            returnedData = excep.Message;
        }
        return(returnedData);
    }
Example #60
-1
 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
 {
     var writer = new StreamWriter(writeStream);
     JSON.Serialize(value, writer, _options);
     writer.Flush();
     return Task.FromResult(writeStream);
 }