public static void LoadWebProxyConfig() { try { string val = Config.Get("Stackify.ProxyServer"); if (!string.IsNullOrEmpty(val)) { StackifyAPILogger.Log("Setting proxy server based on override config", true); var uri = new Uri(val); var proxy = new WebProxy(uri, false); if (!string.IsNullOrEmpty(uri.UserInfo) && uri.UserInfo.Contains(":")) { string[] pieces = uri.UserInfo.Split(':'); proxy.Credentials = new NetworkCredential(pieces[0], pieces[1]); } else { string settingUseDefault = Config.Get("Stackify.ProxyUseDefaultCredentials"); bool useDefault; if (!string.IsNullOrEmpty(settingUseDefault) && bool.TryParse(settingUseDefault, out useDefault)) { //will make it use the user of the running windows service proxy.UseDefaultCredentials = useDefault; } } CustomWebProxy = proxy; } } catch (Exception ex) { StackifyAPILogger.Log("Error setting default web proxy " + ex.Message, true); } }
public string GetResponseString(HttpWebResponse response, DateTime started) { if (response == null) { return(null); } try { using (var responseStream = response.GetResponseStream()) { if (responseStream == null || !responseStream.CanRead) { return(null); } using (var sr = new StreamReader(responseStream)) { string responseData = sr.ReadToEnd(); long took = (long)DateTime.UtcNow.Subtract(started).TotalMilliseconds; bool forceLog = ((int)response.StatusCode) > 400; StackifyAPILogger.Log("GetResponseString HTTP Response: " + ((int)response.StatusCode).ToString() + ", Took: " + took + "ms - " + responseData + " " + response.ResponseUri.ToString(), forceLog); return(responseData); } } } catch (Exception ex) { StackifyAPILogger.Log("HTTP Response Error: " + ex.ToString() + " " + response.ResponseUri.ToString(), true); LastErrorMessage = ex.Message; CalcNextTryOnError(); return(null); } }
public StackifyWebResponse POSTAndGetResponse(string url, string postData) { if (url == null || this.APIKey == null) { StackifyAPILogger.Log("unable to send. Missing url or api key"); return(new StackifyWebResponse() { Exception = new Exception("Missing url or api key") }); } if (!IsAuthorized()) { StackifyAPILogger.Log("Preventing API call due to unauthorized error"); return(new StackifyWebResponse() { Exception = new Exception("unauthorized") }); } StackifyAPILogger.Log("Send to " + url + " key " + this.APIKey + "\r\n" + postData); //default to 500. Should get set below. StackifyWebResponse result = new StackifyWebResponse() { StatusCode = HttpStatusCode.InternalServerError }; DateTime started = DateTime.UtcNow; try { var request = BuildPOSTRequest(url, postData); using (var response = (HttpWebResponse)request.GetResponseAsync().GetAwaiter().GetResult()) { if (response == null) { return(null); } if (response.StatusCode == HttpStatusCode.Unauthorized) { _UnauthorizedResponse = DateTime.UtcNow; } result.ResponseText = GetResponseString(response, started); result.StatusCode = response.StatusCode; _LastSuccess = DateTime.UtcNow; _LastError = null; LastErrorMessage = null; response.Dispose(); } } catch (WebException ex) { StackifyAPILogger.Log(ex.ToString()); CalcNextTryOnError(); result.Exception = ex; LastErrorMessage = ex.Message; if (ex.Response != null) { HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.Unauthorized) { _UnauthorizedResponse = DateTime.UtcNow; } result.StatusCode = response.StatusCode; result.ResponseText = GetResponseString(response, started); response.Dispose(); } } } catch (Exception ex) { StackifyAPILogger.Log(ex.ToString()); CalcNextTryOnError(); LastErrorMessage = ex.Message; result.Exception = ex; } return(result); }
public bool IdentifyApp() { //if identify fails for some reason we can return the previous state incase it was completed before. bool currentIdentityStatus = IdentityComplete; try { int waitTime = 5; //check every 5 //was successful before and we know the appid if (this.AppIdentity != null && this.AppIdentity.DeviceAppID.HasValue) { waitTime = 15; //refresh every 15 } if (_LastIdentityAttempt.AddMinutes(waitTime) > DateTime.UtcNow) { return(currentIdentityStatus); } //if we get this far that means it failed more than 5 minutes ago, is the first time, or succeeded more than 15 minutes ago if (string.IsNullOrEmpty(APIKey)) { StackifyAPILogger.Log("Skipping IdentifyApp(). No APIKey configured.", true); return(false); } StackifyAPILogger.Log("Calling to Identify App"); EnvironmentDetail env = EnvironmentDetail.Get(true); string jsonData = JsonConvert.SerializeObject(env, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var response = SendJsonAndGetResponse( (BaseAPIUrl) + "Metrics/IdentifyApp", jsonData); if (response.Exception == null && response.StatusCode == HttpStatusCode.OK) { _LastIdentityAttempt = DateTime.UtcNow; AppIdentity = JsonConvert.DeserializeObject <AppIdentityInfo>(response.ResponseText); if (AppIdentity != null) { //always use whatever the configured app name is, don't just use what comes back in case they don't match if (!string.IsNullOrEmpty(env.ConfiguredAppName) && env.ConfiguredAppName != AppIdentity.AppName) { AppIdentity.AppName = env.ConfiguredAppName; AppIdentity.AppNameID = null; AppIdentity.AppEnvID = null; } IdentityComplete = true; return(true); } } return(currentIdentityStatus); } catch (Exception ex) { _LastIdentityAttempt = DateTime.UtcNow; StackifyAPILogger.Log("IdentifyApp() HTTP Response Error: " + ex.ToString(), true); return(currentIdentityStatus); } }
/// <summary> /// Trying to serialize something that the user passed in. Sometimes this is used to serialize what we know is additional debug and sometimes it is the primary logged item. This is why the serializeSimpleTypes exists. For additional debug stuff we always serialize it. For the primary logged object we won't because it doesn't make any sense to put a string in the json as well as the main message. It's meant for objects. /// </summary> /// <param name="logObject"></param> /// <param name="serializeSimpleTypes"></param> /// <param name="properties"></param> /// <returns></returns> public static string SerializeDebugData(object logObject, bool serializeSimpleTypes, Dictionary <string, object> properties = null) { Type t = null; // TypeInfo typeInfo = null; JObject jObject = null; try { if (logObject == null) { } else { t = logObject.GetType(); #if NET40 var typeInfo = t; #else var typeInfo = t.GetTypeInfo(); #endif if (logObject is string || t.FullName == "log4net.Util.SystemStringFormat") { if (serializeSimpleTypes) { jObject = new JObject(); jObject.Add("logArg", new JValue(logObject.ToString())); } } else if (typeInfo.IsPrimitive || typeInfo.BaseType == typeof(ValueType)) { if (serializeSimpleTypes) { jObject = new JObject(); try { jObject.Add("logArg", new JValue(logObject)); } catch (ArgumentException) { jObject.Add("logArg", new JValue(logObject.ToString())); } } } //look for some things we don't want to touch else if (logObject is IDisposable)// || logObject is MarshalByRefObject) { } else if (!_BadTypes.Contains(t.ToString())) { var token = JToken.FromObject(logObject, serializer); if (token is JObject) { jObject = (JObject)token; var type = logObject.GetType(); //do we log the objectType? Not logging it for simple things if (typeInfo.IsPrimitive || type.Name == "String" || typeInfo.BaseType == typeof(ValueType) || type.Name.Contains("AnonymousType") || type.FullName.Contains("System.Collections.Generic.Dictionary")) { } else { jObject.Add("objectType", type.FullName); } } else if (token is JArray) { jObject = new JObject(); jObject.Add("logArg", token); var type = logObject.GetType(); if (type.IsArray) { var array = (Array)logObject; if (array.Length > 0) { var child = array.GetValue(0); var childtype = child.GetType(); #if NET40 var childtypeinfo = childtype; #else var childtypeinfo = childtype.GetTypeInfo(); #endif if (childtypeinfo.IsPrimitive || childtype.Name == "String" || childtypeinfo.BaseType == typeof(ValueType)) { } else { jObject.Add("objectType", childtype.FullName); } } } else { if (!typeInfo.ContainsGenericParameters) { jObject.Add("objectType", type.FullName); } else { #if NETFULL var genericArgs = typeInfo.GetGenericArguments(); #else var genericArgs = typeInfo.IsGenericTypeDefinition ? type.GetTypeInfo().GenericTypeParameters : type.GetTypeInfo().GenericTypeArguments; #endif if (genericArgs != null && genericArgs.Length > 0) { var childtype = genericArgs.First(); #if NET40 var childtypeinfo = childtype; #else var childtypeinfo = childtype.GetTypeInfo(); #endif if (childtypeinfo.IsPrimitive || childtype.Name == "String" || childtypeinfo.BaseType == typeof(ValueType)) { } else { jObject.Add("objectType", childtype.FullName); } } else { jObject.Add("objectType", type.FullName); } } } } else if (token is JValue) { if (serializeSimpleTypes) { jObject = new JObject(); jObject.Add("logArg", token); } } } } } catch (Exception ex) { lock (_BadTypes) { _BadTypes.Add(t.ToString()); } Utils.StackifyAPILogger.Log(ex.ToString()); } string data = null; if (properties != null && properties.Count > 0) { if (jObject == null) { jObject = new JObject(); } JObject props = new JObject(); foreach (var prop in properties) { try { if (IsValueType(prop.Value)) { props.Add(prop.Key, new JValue(prop.Value)); } else { props.Add(prop.Key, JObject.FromObject(prop.Value, serializer)); } } catch (Exception ex) { StackifyAPILogger.Log(ex.ToString()); } } jObject.Add("context", props); } if (jObject != null) { return(JsonConvert.SerializeObject(jObject, serializerSettings)); } return(null); }