Beispiel #1
0
        // Get application configuration
        public async Task <Dictionary <string, object> > GetConfig(MoesifApiClient client, Dictionary <string, object> appConfigDict, string cachedETag)
        {
            // Remove cached ETag if exist
            if (!(string.IsNullOrEmpty(cachedETag)) && confDict.ContainsKey(cachedETag))
            {
                confDict.Remove(cachedETag);
            }

            // Call the api to get the application config
            var appConfig = await client.Api.GetAppConfigAsync();

            // Set default config
            if (string.IsNullOrEmpty(appConfig.Body))
            {
                appConfigDict["ETag"]              = null;
                appConfigDict["sample_rate"]       = 100;
                appConfigDict["last_updated_time"] = DateTime.UtcNow;
            }
            // Set application config
            else
            {
                var rspBody = ApiHelper.JsonDeserialize <Dictionary <string, object> >(appConfig.Body);
                appConfigDict["ETag"]              = appConfig.Headers["X-Moesif-Config-ETag"];
                appConfigDict["sample_rate"]       = rspBody["sample_rate"];
                appConfigDict["last_updated_time"] = DateTime.UtcNow;
            }

            // Return config dictionary
            return(appConfigDict);
        }
Beispiel #2
0
        public async Task <Api.Http.Response.HttpStringResponse> getConfig(MoesifApiClient client, bool debug)
        {
            // Get Config
            Api.Http.Response.HttpStringResponse appConfig;
            try
            {
                appConfig = await client.Api.GetAppConfigAsync();

                if (debug)
                {
                    Console.WriteLine("Application Config fetched Successfully");
                }
            }
            catch (APIException inst)
            {
                appConfig = null;
                if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                {
                    Console.WriteLine("Unauthorized access getting application configuration. Please check your Appplication Id.");
                }
                if (debug)
                {
                    Console.WriteLine("Error getting application configuration, with status code:");
                    Console.WriteLine(inst.ResponseCode);
                }
            }
            return(appConfig);
        }
Beispiel #3
0
        public MoesifHttpMessageProcessor(ILogger logger)
        {
            var appId  = Environment.GetEnvironmentVariable("APIMEVENTS-MOESIF-APP-ID", EnvironmentVariableTarget.Process);
            var client = new MoesifApiClient(appId);

            _SessionTokenKey = Environment.GetEnvironmentVariable("APIMEVENTS-MOESIF-SESSION-TOKEN", EnvironmentVariableTarget.Process);
            _SessionTokenKey = Environment.GetEnvironmentVariable("APIMEVENTS-MOESIF-API-VERSION", EnvironmentVariableTarget.Process);
            _Logger          = logger;
        }
        public MoesifHttpMessageProcessor(ILogger logger)
        {
            var appId = ParamConfig.loadNonEmpty(MoesifAppParamNames.APP_ID);

            _MoesifClient    = new MoesifApiClient(appId);
            _SessionTokenKey = ParamConfig.loadDefaultEmpty(MoesifAppParamNames.SESSION_TOKEN);
            _ApiVersion      = ParamConfig.loadDefaultEmpty(MoesifAppParamNames.API_VERSION);
            _Logger          = logger;
            ScheduleWorkerToFetchConfig();
        }
 /// <summary>
 /// Get client instance
 /// </summary>
 /// <returns></returns>
 public static MoesifApiClient GetClient()
 {
     lock (clientSync)
     {
         if (client == null)
         {
             client = new MoesifApiClient("Your Moesif Application Id");
         }
         return(client);
     }
 }
Beispiel #6
0
 public MoesifMiddleware(RequestDelegate next, Dictionary <string, object> _middleware)
 {
     moesifOptions = _middleware;
     // Initialize client
     client = new MoesifApiClient(moesifOptions["ApplicationId"].ToString());
     debug  = Debug();
     _next  = next;
     // Initialize Transaction Id
     transactionId = null;
     // Create a new thread to get the application config
     new Thread(async() =>
     {
         confDict = await GetConfig(client, confDict, cachedConfigETag);
     }).Start();
 }
Beispiel #7
0
        public MoesifMiddlewareNetCore(Dictionary <string, object> _middleware)
        {
            moesifOptions = _middleware;

            try
            {
                // Initialize client
                client = new MoesifApiClient(moesifOptions["ApplicationId"].ToString());
                debug  = LoggerHelper.GetConfigBoolValues(moesifOptions, "LocalDebug", false);
            }
            catch (Exception e)
            {
                throw new Exception("Please provide the application Id to send events to Moesif");
            }
        }
        public MoesifMiddlewareNetCore(Dictionary <string, object> _middleware)
        {
            moesifOptions = _middleware;

            try
            {
                // Initialize client
                client = new MoesifApiClient(moesifOptions["ApplicationId"].ToString());
                debug  = Debug();
            }
            catch (Exception e)
            {
                throw new Exception("Please provide the application Id to send events to Moesif");
            }
        }
        // Function to update users in batch
        public async void UpdateUsersBatch(MoesifApiClient client, List <Dictionary <string, object> > userProfiles, bool debug)
        {
            if (!userProfiles.Any())
            {
                Console.WriteLine("Expecting the input to be of the type - List of dictionary while updating users in batch");
            }
            else
            {
                List <UserModel> userModels = new List <UserModel>();
                foreach (Dictionary <string, object> user in userProfiles)
                {
                    if (user.ContainsKey("user_id"))
                    {
                        UserModel userModel = createUserModel(user);
                        userModels.Add(userModel);
                    }
                    else
                    {
                        Console.WriteLine("To update an user, an user_id field is required");
                    }
                }

                // Perform API call
                try
                {
                    await client.Api.UpdateUsersBatchAsync(userModels);

                    if (debug)
                    {
                        Console.WriteLine("Users Updated Successfully");
                    }
                }
                catch (APIException inst)
                {
                    if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                    {
                        Console.WriteLine("Unauthorized access updating users to Moesif. Please check your Appplication Id.");
                    }
                    if (debug)
                    {
                        Console.WriteLine("Error updating users to Moesif, with status code:");
                        Console.WriteLine(inst.ResponseCode);
                    }
                }
            }
        }
        public MoesifMiddlewareNetFramework(OwinMiddleware next, Dictionary <string, object> _middleware) : base(next)
        {
            moesifOptions = _middleware;

            try
            {
                // Initialize client
                debug                    = LoggerHelper.GetConfigBoolValues(moesifOptions, "LocalDebug", false);
                client                   = new MoesifApiClient(moesifOptions["ApplicationId"].ToString(), "moesif-netframework/1.3.8", debug);
                logBody                  = LoggerHelper.GetConfigBoolValues(moesifOptions, "LogBody", true);
                isBatchingEnabled        = LoggerHelper.GetConfigBoolValues(moesifOptions, "EnableBatching", true);         // Enable batching
                disableStreamOverride    = LoggerHelper.GetConfigBoolValues(moesifOptions, "DisableStreamOverride", false); // Reset Request Body position
                batchSize                = LoggerHelper.GetConfigIntValues(moesifOptions, "BatchSize", 25);                 // Batch Size
                queueSize                = LoggerHelper.GetConfigIntValues(moesifOptions, "QueueSize", 1000);               // Event Queue Size
                batchMaxTime             = LoggerHelper.GetConfigIntValues(moesifOptions, "batchMaxTime", 2);               // Batch max time in seconds
                appConfigSyncTime        = LoggerHelper.GetConfigIntValues(moesifOptions, "appConfigSyncTime", 300);        // App config sync time in seconds
                appConfig                = new AppConfig();                                                                 // Create a new instance of AppConfig
                userHelper               = new UserHelper();                                                                // Create a new instance of userHelper
                companyHelper            = new CompanyHelper();                                                             // Create a new instane of companyHelper
                clientIpHelper           = new ClientIp();                                                                  // Create a new instance of client Ip
                authorizationHeaderName  = LoggerHelper.GetConfigStringValues(moesifOptions, "AuthorizationHeaderName", "authorization");
                authorizationUserIdField = LoggerHelper.GetConfigStringValues(moesifOptions, "AuthorizationUserIdField", "sub");
                samplingPercentage       = 100;                   // Default sampling percentage
                configETag               = null;                  // Default configETag
                lastUpdatedTime          = DateTime.UtcNow;       // Default lastUpdatedTime

                MoesifQueue = new ConcurrentQueue <EventModel>(); // Initialize queue

                new Thread(async() =>                             // Create a new thread to read the queue and send event to moesif
                {
                    Thread.CurrentThread.IsBackground = true;
                    if (isBatchingEnabled)
                    {
                        ScheduleWorker();
                    }
                    else
                    {
                        ScheduleAppConfig(); // Scheduler to fetch application configuration every 5 minutes
                    }
                }).Start();
            }
            catch (Exception e)
            {
                throw new Exception("Please provide the application Id to send events to Moesif");
            }
        }
        public MoesifCaptureOutgoingRequestHandler(HttpMessageHandler innerHandler, Dictionary <string, object> moesifOptions) : base(innerHandler)
        {
            moesifConfigOptions = moesifOptions;

            try {
                client          = new MoesifApiClient(moesifConfigOptions["ApplicationId"].ToString());
                debug           = Debug();
                logBodyOutgoing = LogBodyOutgoing();
                // Create a new instance of AppConfig
                appConfig = new AppConfig();
                // Default configuration values
                samplingPercentage = 100;
                configETag         = null;
                lastUpdatedTime    = DateTime.UtcNow;

                // Create a new thread to get the application config
                new Thread(async() =>
                {
                    Thread.CurrentThread.IsBackground = true;
                    try
                    {
                        // Get Application config
                        config = await appConfig.getConfig(client, debug);
                        if (!string.IsNullOrEmpty(config.ToString()))
                        {
                            (configETag, samplingPercentage, lastUpdatedTime) = appConfig.parseConfiguration(config, debug);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (debug)
                        {
                            Console.WriteLine("Error while parsing application configuration on initialization");
                        }
                    }
                }).Start();
            }
            catch (Exception e)
            {
                throw new Exception("Please provide the application Id to send events to Moesif");
            }
        }
        // Function to update company
        public async void UpdateCompany(MoesifApiClient client, Dictionary <string, object> companyProfile, bool debug)
        {
            if (!companyProfile.Any())
            {
                Console.WriteLine("Expecting the input to be of the type - dictionary while updating company");
            }
            else
            {
                if (companyProfile.ContainsKey("company_id"))
                {
                    CompanyModel companyModel = createCompanyModel(companyProfile);

                    // Perform API call
                    try
                    {
                        await client.Api.UpdateCompanyAsync(companyModel);

                        if (debug)
                        {
                            Console.WriteLine("Company Updated Successfully");
                        }
                    }
                    catch (APIException inst)
                    {
                        if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                        {
                            Console.WriteLine("Unauthorized access updating company to Moesif. Please check your Appplication Id.");
                        }
                        if (debug)
                        {
                            Console.WriteLine("Error updating company to Moesif, with status code:");
                            Console.WriteLine(inst.ResponseCode);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("To update a comapny, an company_id field is required");
                }
            }
        }
Beispiel #13
0
        public async Task <Moesif.Api.Http.Response.HttpStringResponse> getConfig(MoesifApiClient client, ILogger logger)
        {
            // Get Config
            Moesif.Api.Http.Response.HttpStringResponse appConfig;
            try
            {
                appConfig = await client.Api.GetAppConfigAsync();

                logger.LogDebug("Application Config fetched Successfully");
            }
            catch (APIException inst)
            {
                appConfig = null;
                if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                {
                    logger.LogError("Unauthorized access getting application configuration. Check Moesif Appplication Id. [" + inst.ResponseCode + "] " + inst.Message);
                }
                else
                {
                    logger.LogError("Moesif Api Exception getting application configuration: " + inst.ResponseCode);
                }
            }
            return(appConfig);
        }
        public MoesifMiddlewareNetFramework(OwinMiddleware next, Dictionary <string, object> _middleware) : base(next)
        {
            moesifOptions = _middleware;

            try
            {
                // Initialize client
                client  = new MoesifApiClient(moesifOptions["ApplicationId"].ToString());
                debug   = Debug();
                logBody = LogBody();
                // Initialize Transaction Id
                transactionId = null;
                // Create a new instance of AppConfig
                appConfig = new AppConfig();

                // Enable batching
                isBatchingEnabled = EnableBatching();

                // Batch Size
                batchSize = BatchSize();

                // Default configuration values
                samplingPercentage = 100;
                configETag         = null;
                lastUpdatedTime    = DateTime.UtcNow;

                if (isBatchingEnabled)
                {
                    // Initialize queue
                    MoesifQueue = new Queue <EventModel>();

                    // Create a new thread to read the queue and send event to moesif
                    new Thread(async() =>
                    {
                        Thread.CurrentThread.IsBackground = true;
                        try
                        {
                            // Get Application config
                            config = await appConfig.getConfig(client, debug);
                            if (!string.IsNullOrEmpty(config.ToString()))
                            {
                                (configETag, samplingPercentage, lastUpdatedTime) = appConfig.parseConfiguration(config, debug);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (debug)
                            {
                                Console.WriteLine("Error while parsing application configuration on initialization");
                            }
                        }
                        try
                        {
                            var startTimeSpan  = TimeSpan.Zero;
                            var periodTimeSpan = TimeSpan.FromSeconds(1);
                            Tasks task         = new Tasks();

                            var timer = new Timer((e) =>
                            {
                                var updatedConfig = task.AsyncClientCreateEvent(client, MoesifQueue, batchSize, debug, config, configETag, samplingPercentage, lastUpdatedTime, appConfig);
                                (config, configETag, samplingPercentage, lastUpdatedTime) = (updatedConfig.Result.Item1, updatedConfig.Result.Item2, updatedConfig.Result.Item3, updatedConfig.Result.Item4);
                            }, null, startTimeSpan, periodTimeSpan);
                        }
                        catch (Exception ex)
                        {
                            if (debug)
                            {
                                Console.WriteLine("Error while scheduling events batch job every 5 seconds");
                            }
                        }
                    }).Start();
                }
                else
                {
                    // Create a new thread to get the application config
                    new Thread(async() =>
                    {
                        Thread.CurrentThread.IsBackground = true;
                        try
                        {
                            // Get Application config
                            config = await appConfig.getConfig(client, debug);
                            if (!string.IsNullOrEmpty(config.ToString()))
                            {
                                (configETag, samplingPercentage, lastUpdatedTime) = appConfig.parseConfiguration(config, debug);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (debug)
                            {
                                Console.WriteLine("Error while parsing application configuration on initialization");
                            }
                        }
                    }).Start();
                }
            }
            catch (Exception e)
            {
                throw new Exception("Please provide the application Id to send events to Moesif");
            }
        }
Beispiel #15
0
        public async Task <(Moesif.Api.Http.Response.HttpStringResponse, string, int, DateTime)> GetAppConfig(string configETag, int samplingPercentage, DateTime lastUpdatedTime, MoesifApiClient client, ILogger logger)
        {
            Moesif.Api.Http.Response.HttpStringResponse config = null;
            try
            {
                // Get Application config
                config = await getConfig(client, logger);

                if (!string.IsNullOrEmpty(config.ToString()))
                {
                    (configETag, samplingPercentage, lastUpdatedTime) = parseConfiguration(config, logger);
                }
            }
            catch (Exception ex)
            {
                logger.LogError("Error while parsing application configuration " + ex.Message);
            }
            return(config, configETag, samplingPercentage, lastUpdatedTime);
        }
Beispiel #16
0
        public async Task <(Api.Http.Response.HttpStringResponse, string, int, DateTime)> GetAppConfig(string configETag, int samplingPercentage, DateTime lastUpdatedTime, MoesifApiClient client, bool debug)
        {
            Api.Http.Response.HttpStringResponse config = null;
            try
            {
                // Get Application config
                config = await getConfig(client, debug);

                if (!string.IsNullOrEmpty(config.ToString()))
                {
                    (configETag, samplingPercentage, lastUpdatedTime) = parseConfiguration(config, debug);
                }
            }
            catch (Exception ex)
            {
                if (debug)
                {
                    Console.WriteLine("Error while parsing application configuration");
                }
            }
            return(config, configETag, samplingPercentage, lastUpdatedTime);
        }
Beispiel #17
0
        public async Task <(Api.Http.Response.HttpStringResponse, String, int, DateTime)> AsyncClientCreateEvent(MoesifApiClient client, Queue <EventModel> MoesifQueue,
                                                                                                                 int batchSize, bool debug, Api.Http.Response.HttpStringResponse defaultConfig, string configETag, int samplingPercentage, DateTime lastUpdatedTime,
                                                                                                                 AppConfig appConfig)
        {
            List <EventModel> batchEvents = new List <EventModel>();

            while (MoesifQueue.Count > 0)
            {
                batchEvents = QueueGetAll(MoesifQueue, batchSize);

                if ((batchEvents.Any()))
                {
                    // Send Batch Request
                    var createBatchEventResponse = await client.Api.CreateEventsBatchAsync(batchEvents);

                    var batchEventResponseConfigETag = createBatchEventResponse["X-Moesif-Config-ETag"];

                    if (!(string.IsNullOrEmpty(batchEventResponseConfigETag)) &&
                        !(string.IsNullOrEmpty(configETag)) &&
                        configETag != batchEventResponseConfigETag &&
                        DateTime.UtcNow > lastUpdatedTime.AddMinutes(5))
                    {
                        try
                        {
                            Api.Http.Response.HttpStringResponse config;
                            // Get Application config
                            config = await appConfig.getConfig(client, debug);

                            if (!string.IsNullOrEmpty(config.ToString()))
                            {
                                (configETag, samplingPercentage, lastUpdatedTime) = appConfig.parseConfiguration(config, debug);
                                return(config, configETag, samplingPercentage, lastUpdatedTime);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (debug)
                            {
                                Console.WriteLine("Error while updating the application configuration");
                            }
                        }
                    }
                    if (debug)
                    {
                        Console.WriteLine("Events sent successfully to Moesif");
                    }
                }
                else
                {
                    if (debug)
                    {
                        Console.WriteLine("No events in the queue");
                    }
                    return(defaultConfig, configETag, samplingPercentage, lastUpdatedTime);
                }
            }
            if (debug)
            {
                Console.WriteLine("No events in the queue");
            }
            return(defaultConfig, configETag, samplingPercentage, lastUpdatedTime);
        }