public int getSamplingPercentage(Api.Http.Response.HttpStringResponse config, String userId, string companyId)
        {
            // Get sampling percentage

            var userDefaultRate = new object();

            var companyDefaultRate = new object();

            var defaultRate = new object();

            var configBody = ApiHelper.JsonDeserialize <Dictionary <string, object> >(config.Body);

            Dictionary <string, object> userSampleRate = configBody.TryGetValue("user_sample_rate", out userDefaultRate)
                ? ApiHelper.JsonDeserialize <Dictionary <string, object> >(userDefaultRate.ToString())
                : null;

            Dictionary <string, object> companySampleRate = configBody.TryGetValue("company_sample_rate", out companyDefaultRate)
                ? ApiHelper.JsonDeserialize <Dictionary <string, object> >(companyDefaultRate.ToString())
                : null;

            if (!string.IsNullOrEmpty(userId) && userSampleRate.Count > 0 && userSampleRate.ContainsKey(userId))
            {
                return(Int32.Parse(userSampleRate[userId].ToString()));
            }

            if (!string.IsNullOrEmpty(companyId) && companySampleRate.Count > 0 && companySampleRate.ContainsKey(companyId))
            {
                return(Int32.Parse(companySampleRate[companyId].ToString()));
            }

            return(configBody.TryGetValue("sample_rate", out defaultRate) ? Int32.Parse(defaultRate.ToString()) : 100);
        }
Exemple #2
0
        private void ScheduleAppConfig()
        {
            LoggerHelper.LogDebugMessage(debug, "Starting a new thread to sync the application configuration");

            new Thread(async() =>  // Create a new thread to fetch the application configuration
            {
                Tasks task = new Tasks();
                while (true)
                {
                    try
                    {
                        lastAppConfigWorkerRun = DateTime.UtcNow;
                        LoggerHelper.LogDebugMessage(debug, "Last App Config Worker Run - " + lastAppConfigWorkerRun.ToString() + " for thread Id - " + Thread.CurrentThread.ManagedThreadId.ToString());
                        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)
                        {
                            LoggerHelper.LogDebugMessage(debug, "Error while parsing application configuration on initialization");
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerHelper.LogDebugMessage(debug, "Error while scheduling appConfig job");
                    }
                    Thread.Sleep(appConfigSyncTime * 1000);
                }
            }).Start();
        }
 public (String, int, DateTime) parseConfiguration(Api.Http.Response.HttpStringResponse config, bool debug)
 {
     // Parse configuration object and return Etag, sample rate and last updated time
     try
     {
         var rspBody = ApiHelper.JsonDeserialize <Dictionary <string, object> >(config.Body);
         return(config.Headers["X-Moesif-Config-ETag"], Int32.Parse(rspBody["sample_rate"].ToString()), DateTime.UtcNow);
     }
     catch (Exception ex)
     {
         if (debug)
         {
             Console.WriteLine("Error while parsing the configuration object, setting the sample rate to default.");
         }
         return(null, 100, DateTime.UtcNow);
     }
 }
        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");
            }
        }
Exemple #5
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);
        }
        public async Task <HttpResponseMessage> SendEvent(HttpRequestMessage request, DateTime reqTime, HttpResponseMessage response, DateTime respTime)
        {
            if (debug)
            {
                Console.WriteLine("Calling the API to send the event to Moesif");
            }

            // Request Body Encoding
            var reqBody = new object();

            reqBody = null;
            string requestTransferEncoding;

            requestTransferEncoding = null;
            if (logBodyOutgoing && request.Content != null)
            {
                try
                {
                    if (debug)
                    {
                        Console.WriteLine("About to parse Request body as json");
                    }
                    // Get Request Body
                    string requestBody = await request.Content.ReadAsStringAsync();

                    reqBody = ApiHelper.JsonDeserialize <object>(requestBody);
                    requestTransferEncoding = "json";
                }
                catch (Exception e)
                {
                    if (debug)
                    {
                        Console.WriteLine("About to parse Request body as Base64 encoding");
                    }
                    // Get Request Body
                    string requestBody = await request.Content.ReadAsStringAsync();

                    reqBody = Base64Encode(requestBody);
                    requestTransferEncoding = "base64";
                }
            }

            // Prepare Moesif EventRequest Model
            Dictionary <string, string> reqHeaders = request.Headers.ToDictionary(a => a.Key, a => string.Join(";", a.Value));

            var eventReq = new EventRequestModel()
            {
                Time             = reqTime,
                Uri              = request.RequestUri.AbsoluteUri,
                Verb             = request.Method.ToString(),
                ApiVersion       = null,
                IpAddress        = null,
                Headers          = reqHeaders,
                Body             = reqBody,
                TransferEncoding = requestTransferEncoding
            };

            // Response Body Encoding
            var rspBody = new object();

            rspBody = null;
            string responseTransferEncoding;

            responseTransferEncoding = null;
            if (logBodyOutgoing && response.Content != null)
            {
                try
                {
                    if (debug)
                    {
                        Console.WriteLine("About to parse Response body as json");
                    }
                    // Get Response body
                    string responseBody = await response.Content.ReadAsStringAsync();

                    rspBody = ApiHelper.JsonDeserialize <object>(responseBody);
                    responseTransferEncoding = "json";
                }
                catch (Exception e)
                {
                    if (debug)
                    {
                        Console.WriteLine("About to parse Response body as Base64 encoding");
                    }
                    // Get Response body
                    string responseBody = await response.Content.ReadAsStringAsync();

                    rspBody = Base64Encode(responseBody);
                    responseTransferEncoding = "base64";
                }
            }

            // Response header
            Dictionary <string, string> respHeaders = response.Headers.ToDictionary(a => a.Key, a => string.Join(";", a.Value));

            // Prepare Moesif EventResponse Model
            var eventRsp = new EventResponseModel()
            {
                Time             = respTime,
                Status           = (int)response.StatusCode,
                Headers          = respHeaders,
                Body             = rspBody,
                TransferEncoding = responseTransferEncoding
            };

            // Get Outgoing Metadata
            var metadata_out = new object();
            var getMetadata  = moesifConfigOptions.TryGetValue("GetMetadataOutgoing", out metadata_out);

            Func <HttpRequestMessage, HttpResponseMessage, Dictionary <string, object> > GetMetadata = null;

            if (getMetadata)
            {
                GetMetadata = (Func <HttpRequestMessage, HttpResponseMessage, Dictionary <string, object> >)(metadata_out);
            }

            // Metadata
            metadataOutgoing = null;
            if (GetMetadata != null)
            {
                try
                {
                    metadataOutgoing = GetMetadata(request, response);
                }
                catch
                {
                    Console.WriteLine("Can not execute GetMetadataOutgoing function. Please check moesif settings.");
                }
            }

            // Get Outgoing SessionToken
            var token_out       = new object();
            var getSessionToken = moesifConfigOptions.TryGetValue("GetSessionTokenOutgoing", out token_out);

            Func <HttpRequestMessage, HttpResponseMessage, string> GetSessionToken = null;

            if (getSessionToken)
            {
                GetSessionToken = (Func <HttpRequestMessage, HttpResponseMessage, string>)(token_out);
            }

            // Session Token
            sessionTokenOutgoing = null;
            if (GetSessionToken != null)
            {
                try
                {
                    sessionTokenOutgoing = GetSessionToken(request, response);
                }
                catch {
                    Console.WriteLine("Can not execute GetSessionTokenOutgoing function. Please check moesif settings.");
                }
            }

            // Get UserId outgoing
            var user_out  = new object();
            var getUserId = moesifConfigOptions.TryGetValue("IdentifyUserOutgoing", out user_out);

            Func <HttpRequestMessage, HttpResponseMessage, string> IdentifyUser = null;

            if (getUserId)
            {
                IdentifyUser = (Func <HttpRequestMessage, HttpResponseMessage, string>)(user_out);
            }

            // UserId
            userIdOutgoing = null;
            if (IdentifyUser != null)
            {
                try
                {
                    userIdOutgoing = IdentifyUser(request, response);
                }
                catch {
                    Console.WriteLine("Can not execute IdentifyUserOutgoing function. Please check moesif settings.");
                }
            }

            // Get CompanyId outgoing
            var company_out  = new object();
            var getCompanyId = moesifConfigOptions.TryGetValue("IdentifyCompanyOutgoing", out company_out);

            Func <HttpRequestMessage, HttpResponseMessage, string> IdentifyCompany = null;

            if (getCompanyId)
            {
                IdentifyCompany = (Func <HttpRequestMessage, HttpResponseMessage, string>)(company_out);
            }

            // CompanyId
            companyIdOutgoing = null;
            if (IdentifyCompany != null)
            {
                try
                {
                    companyIdOutgoing = IdentifyCompany(request, response);
                }
                catch
                {
                    Console.WriteLine("Can not execute IdentifyCompanyOutgoing function. Please check moesif settings.");
                }
            }

            // Prepare Moesif Event Model
            var eventModel = new EventModel()
            {
                Request      = eventReq,
                Response     = eventRsp,
                UserId       = userIdOutgoing,
                CompanyId    = companyIdOutgoing,
                SessionToken = sessionTokenOutgoing,
                Metadata     = metadataOutgoing,
                Direction    = "Outgoing"
            };

            // Mask Outgoing Event Model
            var maskEvent_out = new object();
            var getMaskEvent  = moesifConfigOptions.TryGetValue("MaskEventModelOutgoing", out maskEvent_out);

            // Check to see if we need to send event to Moesif
            Func <EventModel, EventModel> MaskEventOutgoing = null;

            if (getMaskEvent)
            {
                MaskEventOutgoing = (Func <EventModel, EventModel>)(maskEvent_out);
            }

            // Mask event
            if (MaskEventOutgoing != null)
            {
                try
                {
                    eventModel = MaskEventOutgoing(eventModel);
                }
                catch
                {
                    Console.WriteLine("Can not execute MaskEventModelOutgoing function. Please check moesif settings.");
                }
            }

            // Send Event
            try
            {
                // Get Sampling percentage
                samplingPercentage = appConfig.getSamplingPercentage(config, eventModel.UserId, eventModel.CompanyId);

                Random random           = new Random();
                double randomPercentage = random.NextDouble() * 100;
                if (samplingPercentage >= randomPercentage)
                {
                    eventModel.Weight = appConfig.calculateWeight(samplingPercentage);

                    var createEventResponse = await client.Api.CreateEventAsync(eventModel);

                    var eventResponseConfigETag = createEventResponse["X-Moesif-Config-ETag"];

                    if (!(string.IsNullOrEmpty(eventResponseConfigETag)) &&
                        !(string.IsNullOrEmpty(configETag)) &&
                        configETag != eventResponseConfigETag &&
                        DateTime.UtcNow > lastUpdatedTime.AddMinutes(5))
                    {
                        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 updating the application configuration");
                            }
                        }
                    }
                    if (debug)
                    {
                        Console.WriteLine("Event sent successfully to Moesif");
                    }
                }
                else
                {
                    if (debug)
                    {
                        Console.WriteLine("Skipped Event due to sampling percentage: " + samplingPercentage.ToString() + " and random percentage: " + randomPercentage.ToString());
                    }
                }
            }
            catch (APIException inst)
            {
                if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                {
                    Console.WriteLine("Unauthorized access sending event to Moesif. Please check your Appplication Id.");
                }
                if (debug)
                {
                    Console.WriteLine("Error sending event to Moesif, with status code:");
                    Console.WriteLine(inst.ResponseCode);
                }
            }

            // Return Response back to the client
            return(response);
        }
Exemple #7
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);
        }
        private async Task Middleware(EventRequestModel event_request, EventResponseModel event_response)
        {
            var eventModel = new EventModel()
            {
                Request      = event_request,
                Response     = event_response,
                UserId       = userId,
                CompanyId    = companyId,
                SessionToken = sessionToken,
                Metadata     = metadata,
                Direction    = "Incoming"
            };

            // Get Mask Event
            var maskEvent_out = new object();
            var getMaskEvent  = moesifOptions.TryGetValue("MaskEventModel", out maskEvent_out);

            // Check to see if we need to send event to Moesif
            Func <EventModel, EventModel> MaskEvent = null;

            if (getMaskEvent)
            {
                MaskEvent = (Func <EventModel, EventModel>)(maskEvent_out);
            }

            // Mask event
            if (MaskEvent != null)
            {
                try
                {
                    eventModel = MaskEvent(eventModel);
                }
                catch
                {
                    Console.WriteLine("Can not execute MASK_EVENT_MODEL function. Please check moesif settings.");
                }
            }

            // Send Events
            try
            {
                // Get Sampling percentage
                samplingPercentage = appConfig.getSamplingPercentage(config, userId, companyId);

                Random random           = new Random();
                double randomPercentage = random.NextDouble() * 100;
                if (samplingPercentage >= randomPercentage)
                {
                    eventModel.Weight = appConfig.calculateWeight(samplingPercentage);

                    if (isBatchingEnabled)
                    {
                        if (debug)
                        {
                            Console.WriteLine("Add Event to the batch");
                        }
                        // Add event to queue
                        MoesifQueue.Enqueue(eventModel);
                    }
                    else
                    {
                        var createEventResponse = await client.Api.CreateEventAsync(eventModel);

                        var eventResponseConfigETag = createEventResponse["X-Moesif-Config-ETag"];

                        if (!(string.IsNullOrEmpty(eventResponseConfigETag)) &&
                            !(string.IsNullOrEmpty(configETag)) &&
                            configETag != eventResponseConfigETag &&
                            DateTime.UtcNow > lastUpdatedTime.AddMinutes(5))
                        {
                            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 updating the application configuration");
                                }
                            }
                        }
                        if (debug)
                        {
                            Console.WriteLine("Event sent successfully to Moesif");
                        }
                    }
                }
                else
                {
                    if (debug)
                    {
                        Console.WriteLine("Skipped Event due to sampling percentage: " + samplingPercentage.ToString() + " and random percentage: " + randomPercentage.ToString());
                    }
                }
            }
            catch (APIException inst)
            {
                if (401 <= inst.ResponseCode && inst.ResponseCode <= 403)
                {
                    Console.WriteLine("Unauthorized access sending event to Moesif. Please check your Appplication Id.");
                }
                if (debug)
                {
                    Console.WriteLine("Error sending event to Moesif, with status code:");
                    Console.WriteLine(inst.ResponseCode);
                }
            }
        }
        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");
            }
        }