Exemple #1
0
        internal void Populate(JToken meta, JToken data, ClientSecrets clientSecrets, Tokens apiTokens)
        {
            this.Populate(clientSecrets, apiTokens);

            //Now populate the meta
            try
            {
                this.Meta = meta.ToObject <ApiMetaData>();
            }
            catch (Exception ex)
            {
                LogEventManager.Error("Error deserializing the Meta node.", ex);
                this.Meta = new ApiMetaData();
                this.Meta.ErrorMessages.Add(new ApiErrorMessage {
                    DeveloperMessage = ex.Message
                });
                this.Meta.StatusCode = HttpStatusCode.BadRequest;
            }


            if (data != null)
            {
                this.PopulateData(data);
            }
        }
Exemple #2
0
        private static void HandleTaskException(Task <HttpResponseMessage> taskwithresponse, Exception exception, HttpMethod method)
        {
            try
            {
                if (taskwithresponse.Result.Content != null)
                {
                    LogEventManager.Warn(method + " to " + taskwithresponse.Result.Content + " error. Original exception: " + exception);
                    if (taskwithresponse.Result.Content.Headers.ContentType.MediaType.StartsWith("text/", StringComparison.OrdinalIgnoreCase))
                    {
                        Task task = taskwithresponse.Result.Content.ReadAsStringAsync().ContinueWith(async taskReader => { LogEventManager.Error("Response could not be converted to JSON because it was of type: " + taskwithresponse.Result.Content.Headers.ContentType.MediaType + ". Response:" + taskReader.Result); });

                        task.Wait();
                    }
                    else
                    {
                        LogEventManager.Error("Unable to parse response of type: " + taskwithresponse.Result.Content.Headers.ContentType.MediaType);
                    }
                }
                else
                {
                    LogEventManager.Error("Response for " + method + " unavailable to parse for error messages.");
                }
            }
            catch (Exception ex)
            {
                LogEventManager.Error("Error occurred while trying to handle exception from " + method + " operation", ex);
            }
        }
Exemple #3
0
        public void TypedLogger()
        {
            ILog logger = null;

            Assert.DoesNotThrow(() => logger = LogEventManager.GetTypedLogger <Glossary <int> >());
            Assert.NotNull(logger);
            Assert.DoesNotThrow(() => logger.Error("ErrorMessage from TypedLogger"));
        }
Exemple #4
0
        private string SerializeRequest(object value)
        {
            JsonSerializerOptions options = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            };
            string json = JsonSerializer.Serialize(value);

            LogEventManager.Info($"JSON request sent: {json}");
            return(json);
        }
Exemple #5
0
 public virtual void Init()
 {
     try
     {
         LogEventManager.Init();
         ConnectionString = ConnectionManager.TestConnection;
     }
     catch (Exception ex)
     {
         Logger.Fatal(ex.Message, ex);
         throw;
     }
 }
        /// <summary>
        ///     Gets the current user based on the CurrentToken
        /// </summary>
        /// <param name="dataTypeName"> </param>
        /// <returns></returns>
        public MetaDataType GetDataType(string dataTypeName)
        {
            MetaDataType dataType = null;

            try
            {
                dataType = HttpHelper.Get <MetaDataType>(GlobalConfiguration.Routes.MetaId, string.Empty, null, GetUrlParts(), this.ClientSecrets, this.ApiTokens, dataTypeName);
            }
            catch (Exception e)
            {
                LogEventManager.Error("Error getting data type", e);
            }

            return(dataType);
        }
Exemple #7
0
        public void Sample()
        {
            var client = ClientHelper.GetSdkClient();


            LogEventManager.Verbose("This is a verbose message.");
            LogEventManager.Debug("This is a debug message.");
            LogEventManager.Info("This is a info message.");
            LogEventManager.Warn("This is a info message.");
            LogEventManager.Error("This is an error message.", new Sdk.Common.MetrikException("This is an ERROR exception test."));
            LogEventManager.Fatal("This is a fatal message", new Sdk.Common.MetrikException("This is a FATAL exception test."));

            // This is for checking if the logs are populated properly for each event type
            Assert.IsTrue(true);
        }
Exemple #8
0
        private static T ConvertToRestTokenObject <T>(SessionToken token, JObject resultData) where T : RestObject, new()
        {
            T result = null;

            if (resultData != null)
            {
                JToken dataNode = resultData["data"];
                if (dataNode != null)
                {
                    if (dataNode.Type == JTokenType.Array)
                    {
                        if (dataNode.First != null)
                        {
                            result = JsonConvert.DeserializeObject <T>(dataNode.First.ToString(), GlobalConfiguration.GetJsonSerializerSettings());

                            if (result != null)
                            {
                                result.PopulateSessionToken(token);
                                result.Meta = resultData["meta"].ToObject <ApiMetaData>(); // JsonConvert.DeserializeObject<ApiMetaData>(resultData["meta"].ToString(), GlobalConfiguration.GetJsonSerializerSettings());
                            }
                        }
                    }
                    else
                    {
                        result = JsonConvert.DeserializeObject <T>(dataNode.ToString(), GlobalConfiguration.GetJsonSerializerSettings());

                        if (result != null)
                        {
                            result.PopulateSessionToken(token);
                            result.Meta = resultData["meta"].ToObject <ApiMetaData>();
                        }
                    }
                }
                else
                {
                    JToken metaNode = resultData["meta"];
                    if (metaNode != null)
                    {
                        LogEventManager.Error(string.Format("No data returned: {0}{1}", Environment.NewLine, metaNode.ToString()));
                    }
                }
            }

            return(result);
        }
Exemple #9
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            if (filterContext.Exception == null)
            {
                //save and destroy instance
                if (AppContext.UnitOfWork != null)
                {
                    AppContext.UnitOfWork.Save();
                }
            }

            //log user request
            var logmgr = new LogEventManager(_requestInfo);

            logmgr.Info("User Request", null, DateTime.Now.Subtract(_startAction).TotalSeconds);
        }
        /// <summary>
        ///     Gets the current user based on the CurrentToken
        /// </summary>
        /// <returns></returns>
        public List <MetaDataType> GetDataTypes()
        {
            // Let's reuse the list of names once we have gotten them
            if (this.DataTypes == null)
            {
                try
                {
                    RequestOptions options = new RequestOptions {
                        Expand = true
                    };
                    this.DataTypes = new List <MetaDataType>(HttpHelper.GetPagedResult <MetaDataType>(GlobalConfiguration.Routes.Meta, string.Empty, options, GetUrlParts(), this.ClientSecrets, this.ApiTokens).Items);
                }
                catch (Exception e)
                {
                    LogEventManager.Error("Error getting data types", e);
                }
            }

            return(this.DataTypes);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="idOfUser"></param>
        /// <returns></returns>
        public bool IsInGroup(Guid idOfUser)
        {
            bool isInGroup = false;

            var result = HttpHelper.Get(GlobalConfiguration.Routes.GroupsIdActionId, string.Empty, null, GetUrlParts(), this.ApiTokens, this.ClientSecrets, this.Id, "users", idOfUser);

            if (result.IsHttpStatus(HttpStatusCode.OK))
            {
                isInGroup = true;
            }
            else if (result.IsHttpStatus(HttpStatusCode.NotFound))
            {
                isInGroup = false;
            }
            else
            {
                LogEventManager.Error("Failed to correctly determine if the user was in the group. There was an error on the server.");
            }

            return(isInGroup);
        }
        /// <summary>
        ///     Gets the current user based on the CurrentToken
        /// </summary>
        /// <returns></returns>
        public List <string> GetDataTypeNames()
        {
            // Let's reuse the list of names once we have gotten them
            if (this.DataTypeNames == null)
            {
                try
                {
                    JObject result = HttpHelper.Get(GlobalConfiguration.Routes.Meta, string.Empty, null, GetUrlParts(), this.ApiTokens, this.ClientSecrets);
                    if (result.IsHttpStatus(HttpStatusCode.OK))
                    {
                        string json   = result["data"]["dataTypes"].ToString();
                        JArray jArray = JArray.Parse(json);
                        this.DataTypeNames = jArray.ToObject <List <string> >();
                    }
                }
                catch (Exception e)
                {
                    LogEventManager.Error("Error getting data type names", e);
                }
            }

            return(this.DataTypeNames);
        }
 private void Awake()
 {
     Instance            = this;
     allLogEventListener = new List <LogEventListenerBaseEnitity>();
 }
Exemple #14
0
        /// <summary>
        ///     Processes the resultData and extracts the status code
        /// </summary>
        /// <param name="resultData"></param>
        /// <param name="targetUrl"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        public static JObject ProcessResultData(JObject resultData, string targetUrl, HttpMethod method)
        {
            var statusCode = HttpStatusCode.NotFound;

            if (resultData == null)
            {
                LogEventManager.Warn(GenerateMessage("Http response returned null.", null, targetUrl, method));
                statusCode = HttpStatusCode.ExpectationFailed;
                return(null);
            }

            JObject jData = resultData;

            try
            {
                if (jData != null)
                {
                    if (jData["meta"] != null)
                    {
                        if (jData["meta"]["status"] != null)
                        {
                            statusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), ((int)jData["meta"]["status"]).ToString());

                            if (!IsAffirmativeStatusCode(statusCode))
                            {
                                LogEventManager.Warn(GenerateMessage("JSON response did not return an affirmative response.", resultData, targetUrl, method));
                            }
                            else
                            {
                                LogEventManager.Verbose(GenerateMessage(string.Empty, resultData, targetUrl, method));
                            }
                        }
                        else
                        {
                            LogEventManager.Warn(GenerateMessage("JSON response did not define 'status' (HttpStatusCode) on the 'meta' node.", resultData, targetUrl, method));
                        }
                    }
                    else
                    {
                        LogEventManager.Warn(GenerateMessage("JSON response did not define 'meta'.", resultData, targetUrl, method));
                    }
                }
                else
                {
                    LogEventManager.Warn(GenerateMessage("Unable to preprocess the returned data because it could not be cast to a JSON Object.", resultData, targetUrl, method));
                }
            }
            catch (Exception ex)
            {
                if (jData != null)
                {
                    LogEventManager.Error(GenerateMessage("Error processing the JSON result.", resultData, targetUrl, method), ex);
                }
                else
                {
                    LogEventManager.Error("Error processing the JSON result.", ex);
                }
            }

            return(jData);
        }
Exemple #15
0
        public static void OutputCurlCommand(HttpClient client, HttpMethod method, string url, StringContent content, bool writeAllHeaders = false)
        {
            if (GlobalEvents.IsListening(LogLevelType.Debug))
            {
                var sbCurl = new StringBuilder("CURL equivalent command: " + Environment.NewLine);
                sbCurl.Append("curl ");
                if (method == HttpMethod.Get)
                {
                    sbCurl.AppendLine(@"-X GET \");
                }
                else if (method == HttpMethod.Delete)
                {
                    sbCurl.AppendLine(@"-X DELETE \");
                }
                else if (method == HttpMethod.Post)
                {
                    sbCurl.AppendLine(@"-X POST \");
                }
                else if (method == HttpMethod.Put)
                {
                    sbCurl.AppendLine(@"-X PUT \");
                }

                if (content != null)
                {
                    sbCurl.AppendFormat("\t-H \"Content-Type: {0}\" \\{1}", content.Headers.ContentType.MediaType, Environment.NewLine);
                }

                foreach (var header in client.DefaultRequestHeaders)
                {
                    bool writeHeader = true;

                    // if (writeAllHeaders)
                    // {
                    // writeHeader = true;
                    // }
                    // else if (header.Key.StartsWith("x-", StringComparison.OrdinalIgnoreCase) || header.Key.StartsWith("Authorization"))
                    // {
                    // writeHeader = true;
                    // }
                    if (writeHeader)
                    {
                        sbCurl.AppendFormat("\t-H \"{0}: {1}\" \\{2}", header.Key, header.Value.Aggregate((i, j) => i + " " + j), Environment.NewLine);
                    }
                }

                if (content != null)
                {
                    string jsonData = string.Empty;
                    Task   task     = content.ReadAsStringAsync().ContinueWith(async f => { jsonData = f.Result; });

                    task.Wait();

                    if (!string.IsNullOrWhiteSpace(jsonData))
                    {
                        sbCurl.AppendFormat("\t-d \'{0}\' \\ {1}", jsonData.Replace(Environment.NewLine, Environment.NewLine + "\t\t"), Environment.NewLine);
                    }
                }

                sbCurl.AppendLine(url);

                LogEventManager.Debug(sbCurl.ToString());
            }
        }