ReadAsStringAsync() public méthode

public ReadAsStringAsync ( ) : Task
Résultat Task
        public static SchemaValidationResults IsValid(string rawSchema, HttpContent content)
        {
            if (content.Headers.ContentType == null || !content.Headers.ContentType.MediaType.Equals("application/json",
                StringComparison.InvariantCultureIgnoreCase))
            {
                return new SchemaValidationResults(true, new List<string>());
            }

            var readTask = content.ReadAsStringAsync().ConfigureAwait(false);
            var rawResponse = readTask.GetAwaiter().GetResult();

            return IsValidJSON(rawSchema, rawResponse);

        }
Exemple #2
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);
        }
 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);
 }
Exemple #4
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);
            }
        }
 private static void ValidateEntity(HttpContent content)
 {
     Assert.NotNull(content);
     Assert.Equal(ParserData.TextContentType, content.Headers.ContentType.ToString());
     string entity = content.ReadAsStringAsync().Result;
     Assert.Equal(ParserData.HttpMessageEntity, entity);
 }
Exemple #6
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);
            }
        }
Exemple #7
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
            }
        }
        HttpContent IHttpContentEncryptor.Decrypt(HttpContent encryptedContent)
        {
            if (encryptedContent == null)
            {
                throw new ArgumentNullException("encryptedContent");
            }

            var encodedString = encryptedContent.ReadAsStringAsync().Result;

            using (var encryptedData = new MemoryStream(Convert.FromBase64String(encodedString)))
            {
                if (encryptedData.Length == 0)
                {
                    return encryptedContent;
                }

                this.algorithm.Key = this.keyProvider.Key;
                this.algorithm.IV = this.keyProvider.IV;

                using (var decryptor = algorithm.CreateDecryptor())
                {
                    var cryptoStream = new CryptoStream(encryptedData, decryptor, CryptoStreamMode.Read);
                    var originData = new MemoryStream((int)encryptedData.Length);
                    cryptoStream.CopyTo(originData);
                    originData.Flush();
                    originData.Position = 0;

                    var originContent = new StreamContent(originData);
                    originContent.Headers.ContentType = encryptedContent.Headers.ContentType;

                    return originContent;
                }
            }
        }
Exemple #9
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);
            }
        }
        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);
            }
        }
        /// <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);
            }
        }
Exemple #12
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;
            }
        }
        // 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);
            }
        }
 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;
     });
 }
 private static string ReadContentAsync(HttpContent content)
 {
     Task task = content.LoadIntoBufferAsync();
     task.Wait(TimeoutConstant.DefaultTimeout);
     Assert.Equal(TaskStatus.RanToCompletion, task.Status);
     return content.ReadAsStringAsync().Result;
 }
Exemple #16
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();
 }
		/// <inheritdoc />
		public async Task<object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (!CanConvertFromHttpContent(resultType, httpContent))
			{
				throw new NotSupportedException("CanConvertFromHttpContent resulted in false, this is not supposed to be called.");
			}
			return await httpContent.ReadAsStringAsync().ConfigureAwait(false);
		}
 public static async Task<JObject> GetResponseAsJObject(HttpContent response)
 {
     string rawContent = await response.ReadAsStringAsync();
     JObject json = JObject.Parse(rawContent);
     ResponseHelper.EnsureValidSyncResponse(json);
     Debug.WriteLine("Reponse returned:    {0}", json);
     return json;
 }
 protected override void Act()
 {
     // Act
     using (DomainEvent.Disable())
         responseMessage = Client.GetAsync("http://temp.uri/api/registermatch").Result;
     httpContent = responseMessage.Content;
     content = httpContent.ReadAsStringAsync().Result;
 }
        /// <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));
        }
Exemple #21
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);
        }
        public static async Task<HttpContent> TransformSyncInsertResponse(HttpContent syncContent)
        {
            string rawContent = await syncContent.ReadAsStringAsync();
            JObject jobject = JObject.Parse(rawContent);
            EnsureValidSyncResponse(jobject);
            jobject.Remove("deleted");
            jobject.Remove("__version");

            return new StringContent(((JArray)jobject["results"]).First.ToString());
        }
        /// <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));
        }
        private void CacheResponse(HttpContent content)
        {
            var cachedResponse = new CachedResponse
            {
                Body = content.ReadAsStringAsync().Result,
                ContentType = content.Headers.ContentType.ToString()
            };

            OutputCacheAttribute.cache.Put(this.cacheKey, cachedResponse, this.timeout);
        }
        public static async Task<SchemaValidationResults> IsValidAsync(string rawSchema, HttpContent content)
        {
            if (content.Headers.ContentType == null || !content.Headers.ContentType.MediaType.Equals("application/json",
                StringComparison.InvariantCultureIgnoreCase))
            {
                return new SchemaValidationResults(true, new List<string>());
            }

            var rawContent = await content.ReadAsStringAsync();
            return IsValidJSON(rawSchema, rawContent);
        }
Exemple #26
0
        /// <summary>
        /// Constructor.  Creates the Rates instance from the BitPay server response.
        /// </summary>
        /// <param name="response">The raw HTTP response from BitPay server api/rates call.</param>
        /// <param name="bp">bp - used to update self.</param>
        public Rates(HttpContent response, BitPay bp)
        {
            dynamic obj = Json.Decode(response.ReadAsStringAsync().Result);
            this._bp = bp;

            _rates = new List<Rate>();
            foreach (dynamic rateObj in obj)
            {
                _rates.Add(new Rate(rateObj.name, rateObj.code, rateObj.rate));
            }
        }
Exemple #27
0
        /// <inheritdoc />
        /// <exception cref="System.ArgumentNullException">
        /// The <paramref name="content"/> parameter is <c>null</c>.
        /// </exception>
        protected internal override void SetContent(HttpContent content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            var result = content.ReadAsStringAsync().Result;

            _content = result;
        }
Exemple #28
0
        private IEnumerable<KeyValuePair<string, string>> GetFormData(HttpContent content)
        {
            if (content is MultipartFormDataContent)
            {
                return ((MultipartFormDataContent)content)
                    .Where(CanProcessContent)
                    .SelectMany(GetFormData);
            }

            string rawFormData = content.ReadAsStringAsync().Result;

            return QueryStringMatcher.ParseQueryString(rawFormData);
        }
        private void CacheResponse(HttpContent content)
        {
            if (content != null)
            {
                var cachedResponse = new CachedResponse
                {
                    Body = content.ReadAsStringAsync().Result,
                    ContentType = content.Headers.ContentType.ToString()
                };

                //OutputCacheAttribute.Cache.Put(this.cacheKey, cachedResponse, this.timeout);
                OutputCacheAttribute.Cache.Add(this.cacheKey, cachedResponse, DateTime.Now.Add(this.timeout));
            }
        }
        public async Task<bool> ParseAccessToken(HttpContent response)
        {
            var dataResponse = await response.ReadAsStringAsync();

            var parsedDataResponse = JsonConvert.DeserializeObject<AuthorizationRootObject>(dataResponse);

            if (parsedDataResponse.Code.ToLower() == "ok")
            {
                ReadWriteAccessToken = parsedDataResponse.Result.AccessToken;
                SetExpiresAt(parsedDataResponse.Result.ExpiresIn);

                return true;
            }
            return false;
        }
        /// <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));
        }
        public static void VerifyJsonResponse(HttpContent responseContent, string expected)
        {
            string response = responseContent.ReadAsStringAsync().Result;

            // resource file complains if "{" is present in the value
            Regex updatedRegEx = new Regex("{");
            response = updatedRegEx.Replace(response, "%");
            expected = expected.Trim();
            response = response.Trim();

            // compare line by line since odata json typically differs from baseline by spaces
            string[] expectedLines = expected.Split('\n').ToList().ConvertAll((str) => str.Trim()).ToArray();
            string[] responseLines = response.Split('\n').ToList().ConvertAll((str) => str.Trim()).ToArray();
            Assert.Equal(expectedLines, responseLines);
        }
        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("");
        }
Exemple #34
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);
    }
        /// <summary>
        /// Check is service is alive
        /// </summary>
        /// <returns>True/False</returns>
        public async Task<bool> IsAlive()
        {
            try
            {
                wcfResponse = client.GetAsync("http://localhost:20236/GameService.svc/IsAlive/").Result;
                stream = wcfResponse.Content;
                string data = await stream.ReadAsStringAsync();

                return Convert.ToBoolean(data);
            }
            catch(AggregateException)
            {
                //throw new AggregateException(ex.Message);
                // Write to logger;
                return false;
            }
        }
        private async Task DumpContent(HttpContent content, bool isErrorContent = false)
        {
            if (content == null || content.Headers.ContentType == null)
            {
                return;
            }
            var result = await content.ReadAsStringAsync();

            LogInfoLn(string.Empty);
            if (!string.IsNullOrWhiteSpace(result))
            {
                dynamic parsedJson = JsonConvert.DeserializeObject(result);
                string indentedResult = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);

                Logger.WriteLn(indentedResult, isErrorContent ? Logger.ErrorBrush : _infoBrush);
            }
        }
        public static void SendDataToODS_ContainerLog(bool useMmaCert)
        {
            X509Certificate2 cert = null;

            if (useMmaCert)
            {
                cert = CertificateManagement.FindOdsCertificateByWorkspaceId(WorkspaceId);
            }
            else
            {
                cert = Find(StoreLocation.LocalMachine, MyThumbprint);
            }


            // string rawCert = Convert.ToBase64String(cert.GetRawCertData()); //base64 binary
            string requestId   = Guid.NewGuid().ToString("D");
            string jsonContent = File.ReadAllText("ContainerLog.json");

            string dateTime = DateTime.Now.ToString("O");

            try
            {
                WebRequestHandler clientHandler = new WebRequestHandler();
                clientHandler.ClientCertificates.Add(cert);
                var client = new HttpClient(clientHandler);

                string url = "https://" + WorkspaceId + ".ods.opinsights.azure.com/OperationalData.svc/PostJsonDataItems?api-version=2016-04-01";
                client.DefaultRequestHeaders.Add("X-Request-ID", requestId);

                System.Net.Http.HttpContent httpContent = new StringContent(jsonContent, 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);
                Console.WriteLine("requestId: " + requestId);
                Console.WriteLine(response.Result);
            }
            catch (Exception excep)
            {
                Console.WriteLine("API Post Exception: " + excep.Message);
            }
        }
        /// <summary>
        /// Load user from restfull service 
        /// </summary>
        /// <param name="userNick"></param>
        /// <returns>User object</returns>
        public User LoadUserInfo(string userNick)
        {
            User user = null;
            try
            {
                wcfResponse = client.GetAsync("http://localhost:20236/GameService.svc/LoadUserInfo/" + userNick + "").Result;
                stream = wcfResponse.Content;
                Task<string> data = stream.ReadAsStringAsync();

                User us = User.CurrentUser;
                dataObject = JObject.Parse(data.Result.ToString());
                user = JsonConvert.DeserializeObject<User>(dataObject.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return user;
        }
Exemple #39
0
    // Send a request to the POST API endpoint
    void PostData(string signature, string date, string json)
    {
        string url = "https://" + Workspace + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";

        using (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");
            var response = client.PostAsync(new Uri(url), httpContent);

            System.Net.Http.HttpContent responseContent = response.Result.Content;
            string result = responseContent.ReadAsStringAsync().Result;
        }
    }
        private async Task DumpContent(HttpContent content, bool isErrorContent = false)
        {
            if (content == null || content.Headers.ContentType == null)
            {
                return;
            }
            var result = await content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(_siteName))
            {
                var tmpLocation = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _siteName+".PublishSettings");
                File.WriteAllText(tmpLocation, string.IsNullOrWhiteSpace(result) ? "" : result);
            }
            else if (!string.IsNullOrWhiteSpace(result))
            {
                dynamic parsedJson = JsonConvert.DeserializeObject(result);
                string indentedResult = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);

                //Logger.WriteLn(indentedResult, isErrorContent ? Logger.ErrorBrush : _infoBrush);
            }
        }
        HttpContent IHttpContentEncryptor.Decrypt(HttpContent encryptedContent)
        {
            if (encryptedContent == null)
            {
                throw new ArgumentNullException("encryptedContent");
            }

            var encodedString = encryptedContent.ReadAsStringAsync().Result;

            if (string.IsNullOrEmpty(encodedString))
            {
                return encryptedContent;
            }

            var originBytes = Convert.FromBase64String(encodedString);
            var originStream = new MemoryStream(originBytes);

            var originContent = new StreamContent(originStream);
            originContent.Headers.ContentType = encryptedContent.Headers.ContentType;

            return originContent;
        }
Exemple #42
0
        /// <summary>
        /// Extracts the CRM specific error message and stack trace from an HTTP content. 
        /// </summary>
        /// <param name="content">The HTTP content in Json format.</param>
        /// <returns>The error message.</returns>
        private static string ExtractMessageFromContent(HttpContent content)
        {
            string message = String.Empty;
            string downloadedContent = content.ReadAsStringAsync().Result;

            JObject jcontent = (JObject)JsonConvert.DeserializeObject(downloadedContent);
            IDictionary<string, JToken> d = jcontent;

            if (d.ContainsKey("error"))
            {
                JObject error = (JObject)jcontent.Property("error").Value;
                message = (String)error.Property("message").Value;
            }
            else if (d.ContainsKey("Message"))
                message = (String)jcontent.Property("Message").Value;

            if(d.ContainsKey("StackTrace"))
                _stackTrace = (String)jcontent.Property("StackTrace").Value;

            return message;
        #endregion Methods
        }
        // Send a request to the POST API endpoint
        public static TaskStatus PostData(string json, string CustomerId, string SharedKey, string LogName)
        {
            // Create a hash for the API signature
            var    datestring   = DateTime.UtcNow.ToString("r");
            string stringToHash = "POST\n" + json.Length + "\napplication/json\n" + "x-ms-date:" + datestring + "\n/api/logs";
            string hashedString = BuildSignature(stringToHash, SharedKey);
            string signature    = "SharedKey " + CustomerId + ":" + hashedString;

            // 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", datestring);
                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("Status: " + response.Status + " Return Result: " + result);
                return(response.Status);
            }
            catch (Exception excep)
            {
                Console.WriteLine("API Post Exception: " + excep.Message);
            }

            return(TaskStatus.Faulted);
        }
        private HttpContent CustomizeIndexContent(HttpContent content)
        {
            var originalText = content.ReadAsStringAsync().Result;

            var listOfSubmitMethods = String.Join(",", _config.SupportedSubmitMethods
                .Select(sm => String.Format("'{0}'", sm)));

            var scriptIncludes = String.Join("\r\n", _config.CustomScriptPaths
                .Select(path => String.Format("$.getScript('{0}');", path)));

            var stylesheetIncludes = String.Join("\r\n", _config.CustomStylesheetPaths
                .Select(path => String.Format("<link href='{0}' rel='stylesheet' type='text/css'/>", path)));

            var customizedText = originalText
                .Replace("%(DiscoveryUrl)", "window.location.href.replace(/ui\\/index\\.html.*/, 'api-docs')")
                .Replace("%(SupportHeaderParams)", _config.SupportHeaderParams.ToString().ToLower())
                .Replace("%(SupportedSubmitMethods)", String.Format("[{0}]", listOfSubmitMethods))
                .Replace("%(DocExpansion)", String.Format("\"{0}\"", _config.DocExpansion.ToString().ToLower()))
                .Replace("%(CustomScripts)", scriptIncludes)
                .Replace("%(CustomStylesheets)", stylesheetIncludes);

            return new StringContent(customizedText);
        }
Exemple #45
0
        /// <summary>
        /// Reads as asynchronous.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content">The content.</param>
        /// <returns>A <see cref="Task{TResult}"/> represents the put operation.</returns>
        public async static Task <T> ReadAsAsync <T>(this HttpContent content)
        {
            var json = await content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <T>(json));
        }
Exemple #46
0
 public static async Task <TEntity> ReadAsAsync <TEntity>(this HttpContent content)
 {
     return(JsonConvert.DeserializeObject <TEntity>(await content.ReadAsStringAsync()));
 }
 public static Task <string> ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)
 {
     return(content.ReadAsStringAsync());
 }
Exemple #48
0
        public static void Run([BlobTrigger("fastly-logs/{name}", Connection = "storageString")] Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            //https://docs.microsoft.com/en-us/rest/api/loganalytics/create-request

            //Get the application settings
            //You need to have the following defined for this to work:
            //"storageString": storage endpoint for the blob to monitor
            //"workspaceID": The GUID ID of the Log Analytics workspace
            //"logAnalyticsURL": "https://<yourworkspaceID>.ods.opinsights.azure.com/api/logs?api-version=2016-04-01",
            //"sharedKey": the shared key for your workspace,
            //"logType":  a string which will be the custom log type

            //https://www.koskila.net/how-to-access-azure-function-apps-settings-from-c/
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var logAnalyticsURL = config["logAnalyticsURL"];
            var workspaceID     = config["workspaceID"];
            var sharedKey       = config["sharedKey"];
            var logType         = config["logType"];

            String outputJSON = "[\n";

            log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
            using (var reader = new StreamReader(myBlob))
            {
                //write out the first line so we can include the comma at the start of following lines
                var line = reader.ReadLine();
                outputJSON = outputJSON + line;

                //Read the rest of the file
                while (!reader.EndOfStream)
                {
                    //Read our lines one by one and split into values
                    line = reader.ReadLine();
                    //Add the line to the output
                    outputJSON = outputJSON + ",\n" + line;
                }

                //Close the JSON
                outputJSON = outputJSON + "\n]";

                log.LogInformation("Added: " + outputJSON);
            }

            //upload the data

            //Get the current time
            //https://docs.microsoft.com/en-us/dotnet/api/system.datetime.now?view=netframework-4.8
            DateTime timestamp = DateTime.Now;

            //Set up variables with required date formats for current time
            //Note you may want to take the time generated from the actual log time, perhaps the time of the Blob creation, or a line in the file?
            //You may also want to decontruct the file into lines and send each one as a log event with it's correct time
            //https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
            String xMSDate       = timestamp.ToString("R");
            String timeGenerated = timestamp.ToString("O");

            //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(outputJSON);
            string stringToHash = "POST\n" + jsonBytes.Length + "\napplication/json\n" + "x-ms-date:" + xMSDate + "\n/api/logs";
            string hashedString = "";
            var    encoding     = new System.Text.ASCIIEncoding();

            byte[] keyByte      = Convert.FromBase64String(sharedKey);
            byte[] messageBytes = encoding.GetBytes(stringToHash);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hash = hmacsha256.ComputeHash(messageBytes);
                hashedString = Convert.ToBase64String(hash);
            }

            string signature = "SharedKey " + workspaceID + ":" + hashedString;

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

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

                System.Net.Http.HttpContent responseContent = response.Result.Content;
                string result = responseContent.ReadAsStringAsync().Result;
                log.LogInformation("Return Result: " + result);
            }
            catch (Exception excep)
            {
                log.LogInformation("API Post Exception: " + excep.Message);
            }
        }
Exemple #49
0
        internal static async Task <T> ReadAs <T>(this HttpContent content)
        {
            string value = await content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <T>(value));
        }
Exemple #50
0
 public Task <string> ReadAsStringAsync()
 {
     return(content.ReadAsStringAsync());
 }
        private Boolean SessionHasStarted(HttpContent content)
        {
            //check the response body
            Dictionary<string,object> jsonResponse = JsonConvert.DeserializeObject<Dictionary<string, object>>(content.ReadAsStringAsync().Result);

            // only check for ok:true, https://issues.apache.org/jira/browse/COUCHDB-1356
            // means we cannot check that the name returned is the one we sent.

            Object obj;
            jsonResponse.TryGetValue("ok", out obj);

            if (obj is Boolean)
                return (Boolean)obj;

            return false;
        }
Exemple #52
0
        private static async Task <string> ReadContentAsync(HttpContent content)
        {
            await content.LoadIntoBufferAsync();

            return(await content.ReadAsStringAsync());
        }
Exemple #53
0
        public static async Task <T> ReadJsonAsync <T>(this System.Net.Http.HttpContent content)
        {
            var json = await content.ReadAsStringAsync();

            return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(json));
        }
        private async Task DumpContent(HttpContent content)
        {
            if (content == null || content.Headers.ContentType == null)
            {
                return;
            }

            var result = await content.ReadAsStringAsync();
            if (content.Headers.ContentType.MediaType.Contains(Constants.JsonContentType))
            {
                if (result.StartsWith("["))
                {
                    Program.PrintColoredJson(JArray.Parse(result));
                    return;
                }
                else if (result.StartsWith("{"))
                {
                    Program.PrintColoredJson(JObject.Parse(result));
                    return;
                }
            }

            Console.Write(result);
        }
 /// <summary>
 ///     Serialize the HTTP content to a string as a synchronous operation.
 /// </summary>
 public static string ReadAsString(this HttpContent content)
 {
     return(Task.Run(() => content.ReadAsStringAsync()).Result);
 }
 public static async Task <Tout> ReadAsAsync <Tout>(this System.Net.Http.HttpContent content)
 {
     return(Newtonsoft.Json.JsonConvert.DeserializeObject <Tout>(await content.ReadAsStringAsync()));
 }
Exemple #57
0
        private async Task<HttpResponseMessage> RequestInnerAsync(
            TimeSpan? requestTimeout,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken,
            HttpMethod method,
            string path,
            HttpContent content = null,
            IDictionary<string, string> extraParams = null,
            bool includeAuthToQuery = true)
        {
            HttpClient client = GetHttpClient();

            if (requestTimeout.HasValue)
            {
                client.Timeout = requestTimeout.Value;
            }

            StringBuilder uri = BuildUri(path, extraParams, includeAuthToQuery);
            HttpRequestMessage request = BuildRequest(method, content, uri);

#if DEBUG
            Debug.WriteLine("[Request] {0}", request.ToJson());
            if (content != null)
            {
                Debug.WriteLine("[RequestData] {0}", content.ReadAsStringAsync().Result);
            }
#endif

            return await client.SendAsync(request, completionOption, cancellationToken);
        }
 public static void VerifyResponse(HttpContent actualContent, string expected)
 {
     string actual = actualContent.ReadAsStringAsync().Result;
     JsonAssert.Equal(expected, actual);
 }
Exemple #59
0
        /// <summary>
        /// This will email super admins a notification of an exception. The exception details
        /// are logged to AWS CloudWatch.
        /// </summary>
        /// <param name="exception">The captured exception object.</param>
        /// <param name="emailText">The body text to send in the email.</param>
        public void handleError(Exception exception, string emailText)
        {
            //Send the Super Admins a notification
            try
            {
                //Let's not get stuck in a loop, if an excpeption occurs at the email code don't try to email
                if (emailText != "Exception occured attempting to send email.")
                {
                    //Fire off email
                    Email email = new Email();

                    //Add custom recipients here
                    //email.SendEmail("*****@*****.**", WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText);
                    //email.SendEmail("*****@*****.**", WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText);

                    //Add Exception details to the email message text in the same format that is sent to AWS below
                    //if stack trace is null reference then targetsite also returns null reference
                    //Get the name of the method that threw the exception
                    MethodBase site       = exception.TargetSite;
                    string     methodName = site == null ? null : site.Name;

                    //Get the  filename and linenumber that threw the exception
                    var st       = new StackTrace(exception, true);
                    var frame    = st.GetFrame(0);
                    var line     = frame.GetFileLineNumber();
                    var filename = frame.GetFileName();

                    //Attach the full error message to the custom one sent in from the controller source
                    //Current Format is: [FileName:value][MethodName:value][LineNumber:value][RawMessage:value]
                    var full_error_message = "[Filename:" + filename + "][MethodName:" + methodName + "][LineNumber:" + line + "][RawMessage:" + exception.Message.ToString() + "]";
                    emailText += full_error_message;

                    //Email Super Admins about the exception
                    email.EmailSuperAdmins(WebConfigurationManager.AppSettings["loginTitle"].ToString() + " Exception", emailText);
                }
            }
            //Logging to the System Error log requires some configuration
            //1) Add a Registry(Folder) Key on the server/localhost. The last folder name matching the web config loginTitle key value
            // -> “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\WRDSB\System.Web.Configuration.WebConfigurationManager.AppSettings["loginTitle"].ToString()”
            //2) Add a "String Value" titled "EventMessageFile" with a value of "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll"
            //See Documentation for more detailed instructions:
            //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/
            catch (Exception ex)
            {
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
                string errorMessage             = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace;
                if (ex.TargetSite != null)
                {
                    errorMessage += "\r\nTarget: " + ex.TargetSite.ToString();
                }

                if (ex.InnerException != null)
                {
                    errorMessage += "\r\nInner: " + ex.InnerException.ToString();
                }
                log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString();
                log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error);
            }

            //You can now log the error to Azure or AWS or even both.

            //Send the exception information to AWS Cloudwatch
            //This requires configuration, see documentation:
            //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/
            try
            {
                //Set the logging group based on debug/production switch
                //Logs will be sent to "/dotnet/$your_applictation_name/$environment
                #if DEBUG
                string environment = "test";
                #else
                string environment = "production";
                #endif

                //Set the AWS values, log group, log level
                var config = new LoggingConfiguration();

                //The log group name cannot have spaces, but the loginTitle is meant to be human readable, transform it for format AWS requires
                var application_name = WebConfigurationManager.AppSettings["loginTitle"].ToString().ToLower().Replace(" ", "_");

                var awsTarget = new AWSTarget()
                {
                    LogGroup = "/dotnet/" + application_name + "/" + environment,
                    Region   = "us-east-1"
                };
                config.AddTarget("aws", awsTarget);
                config.LoggingRules.Add(new LoggingRule("*", LogLevel.Fatal, awsTarget));
                LogManager.Configuration = config;
                Logger logger = LogManager.GetCurrentClassLogger();

                //if stack trace is null reference then targetsite also returns null reference
                //Get the name of the method that threw the exception
                MethodBase site       = exception.TargetSite;
                string     methodName = site == null ? null : site.Name;

                //Get the  filename and linenumber that threw the exception
                var st       = new StackTrace(exception, true);
                var frame    = st.GetFrame(0);
                var line     = frame.GetFileLineNumber();
                var filename = frame.GetFileName();

                //Send the event to AWS CloudWatch
                //Current Format is: [FileName:value][MethodName:value][LineNumber:value][RawMessage:value]
                //This will be found in the Message portion of Cloudwatch logs
                logger.Fatal("[Filename:" + filename + "][MethodName:" + methodName + "][LineNumber:" + line + "][RawMessage:" + exception.Message.ToString() + "]");
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
                string errorMessage             = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace;
                if (ex.TargetSite != null)
                {
                    errorMessage += "\r\nTarget: " + ex.TargetSite.ToString();
                }

                if (ex.InnerException != null)
                {
                    errorMessage += "\r\nInner: " + ex.InnerException.ToString();
                }
                log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString();
                log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error);
            }

            //Send the exception information to Azure Log Analytics
            //This requires configuration, see documentation:
            //https://staff.wrdsb.ca/software-development/documentation/dot-net-theme/general-configuration-options/
            string result = string.Empty;
            try
            {
                string customer_id = WebConfigurationManager.AppSettings["workspace_id"].ToString();
                string shared_key  = WebConfigurationManager.AppSettings["primary_key"].ToString();

#if DEBUG
                string environment = "test";
#else
                string environment = "production";
#endif
                var application_name = WebConfigurationManager.AppSettings["loginTitle"].ToString().ToLower().Replace(" ", "");

                string log_name = "dotnet" + application_name + environment;

                string timestamp = DateTime.Now.ToString();

                //if stack trace is null reference then targetsite also returns null reference
                //Get the name of the method that threw the exception
                MethodBase site       = exception.TargetSite;
                string     methodName = site == null ? null : site.Name;

                //Get the  filename and linenumber that threw the exception
                var st       = new StackTrace(exception, true);
                var frame    = st.GetFrame(0);
                var line     = frame.GetFileLineNumber();
                var filename = frame.GetFileName();

                dynamic jsonObject = new JObject();
                jsonObject.Add("FileName", filename);
                jsonObject.Add("MethodName", methodName);
                jsonObject.Add("LineNumber", line);
                jsonObject.Add("RawMessage", exception.Message.ToString());

                string json = jsonObject.ToString(Newtonsoft.Json.Formatting.None);

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

                string url = "https://" + customer_id + ".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", log_name);
                client.DefaultRequestHeaders.Add("Authorization", signature);
                client.DefaultRequestHeaders.Add("x-ms-date", datestring);
                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;
                result = responseContent.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
                string errorMessage             = "Message: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nStack: " + ex.StackTrace;
                if (ex.TargetSite != null)
                {
                    errorMessage += "\r\nTarget: " + ex.TargetSite.ToString();
                }

                if (ex.InnerException != null)
                {
                    errorMessage += "\r\nInner: " + ex.InnerException.ToString();
                }
                if (!String.IsNullOrEmpty(result))
                {
                    errorMessage += "\r\nAzureResponse: " + result;
                }
                log.Source = WebConfigurationManager.AppSettings["loginTitle"].ToString();
                log.WriteEntry(errorMessage, System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemple #60
0
        /// <summary>
        /// Creates an invoice object given the BitPay server response.
        /// Throws a BitPayException if the content of the response indicates an error occurred.
        /// </summary>
        /// <param name="response">The HTTP response object from the BitPay server when attempting to create
        /// an invoice.</param>
        /// <returns>A populated Inovice object.</returns>
        private Invoice createInvoiceObjectFromResponse(HttpContent response)
        {
            dynamic obj = Json.Decode(response.ReadAsStringAsync().Result);
            if (dynamicObjectHasProperty(obj, "error"))
            {
                throw new BitPayException("Error: " + obj.error.message);
            }

            return new Invoice(obj);
        }