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);
                }
            }
        }
        /**
         * From Http request and response, construct the moesif EventModel
         */
        public async Task <EventModel> BuildMoesifEvent(HttpMessage request, HttpMessage response)
        {
            _Logger.LogDebug("Building Moesif event");

            string clientIpAddress  = "";
            string subscriptionId   = "";
            string subscriptionName = "";
            string correlationid    = "";

            Dictionary <string, string> reqheaders = HeadersUtils.deSerializeHeaders(request.HttpRequestMessage.Properties[ReqHeadersName]);

            foreach (var h in reqheaders)
            {
                string n = h.Key.Trim();
                string v = h.Value.Trim();
                if (n.Equals("clientIPAddress"))
                {
                    clientIpAddress = v;
                }
                if (n.Equals("subscription_id"))
                {
                    subscriptionId = v;
                }
                if (n.Equals("subscription_name"))
                {
                    subscriptionName = v;
                }
                if (n.Equals("correlationid"))
                {
                    correlationid = v;
                }
            }


            EventRequestModel moesifRequest = await genEventRequestModel(request,
                                                                         ReqHeadersName,
                                                                         RequestTimeName,
                                                                         _ApiVersion, clientIpAddress);

            EventResponseModel moesifResponse = await genEventResponseModel(response, clientIpAddress);

            Dictionary <string, object> metadata = genMetadata(request, MetadataName);

            metadata.Add("ApimSubscriptionId", subscriptionId);
            metadata.Add("ApimSubscriptionName", subscriptionName);
            metadata.Add("ApimCorrelationId", correlationid);

            string skey      = safeGetHeaderFirstOrDefault(request, _SessionTokenKey);
            string userId    = safeGetOrNull(request, UserIdName);
            string companyId = safeGetOrNull(request, CompanyIdName);


            EventModel moesifEvent = new EventModel()
            {
                Request      = moesifRequest,
                Response     = moesifResponse,
                SessionToken = skey,
                Tags         = null,
                UserId       = userId,
                CompanyId    = companyId,
                Metadata     = metadata,
                Direction    = "Incoming"
            };

            return(moesifEvent);
        }
        private async Task <EventResponseModel> FormatResponse(IOwinResponse response)
        {
            response.Body.Seek(0, SeekOrigin.Begin);

            // read the response body stream
            var responseBody = new StreamReader(response.Body).ReadToEnd();

            var rspHeaders = new Dictionary <string, string>();

            try
            {
                rspHeaders = response.Headers.ToDictionary(k => k.Key, k => k.Value.First());
            }
            catch (Exception inst)
            {
                if (debug)
                {
                    Console.WriteLine("error encountered while copying response header");
                    Console.WriteLine(inst);
                }
            }

            // Add Transaction Id to Response Header
            if (!string.IsNullOrEmpty(transactionId))
            {
                rspHeaders["X-Moesif-Transaction-Id"] = transactionId;
            }

            var rspBody = new object();

            rspBody = null;
            string responseTransferEncoding;

            responseTransferEncoding = null;
            if (logBody)
            {
                try
                {
                    rspBody = ApiHelper.JsonDeserialize <object>(responseBody);
                }
                catch (Exception inst)
                {
                    if (debug)
                    {
                        Console.WriteLine("About to parse Response body as Base64 encoding");
                    }
                    // Get Response body
                    rspBody = Base64Encode(responseBody);
                    responseTransferEncoding = "base64";
                }
            }

            var eventRsp = new EventResponseModel()
            {
                Time             = DateTime.UtcNow,
                Status           = response.StatusCode,
                Headers          = rspHeaders,
                Body             = rspBody,
                TransferEncoding = responseTransferEncoding
            };

            return(eventRsp);
        }
Exemplo n.º 4
0
        private async Task Middleware(EventRequestModel event_request, EventResponseModel event_response)
        {
            var eventModel = new EventModel()
            {
                Request      = event_request,
                Response     = event_response,
                UserId       = userId,
                SessionToken = sessionToken,
                Metadata     = metadata
            };

            string applicationId     = null;
            var    applicationId_out = new object();
            var    getApplicationId  = moesifOptions.TryGetValue("ApplicationId", out applicationId_out);

            if (getApplicationId)
            {
                applicationId = applicationId_out.ToString();
            }

            if (applicationId_out == null || applicationId == null)
            {
                Console.WriteLine("Please provide the application Id to send events to Moesif");
            }
            else
            {
                // 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
                {
                    double samplingPercentage = Convert.ToDouble(confDict["sample_rate"]);

                    Random random           = new Random();
                    double randomPercentage = random.NextDouble() * 100;
                    if (samplingPercentage >= randomPercentage)
                    {
                        var createEventResponse = await client.Api.CreateEventAsync(eventModel);

                        var eventResponseConfigETag = createEventResponse["X-Moesif-Config-ETag"];
                        cachedConfigETag = confDict["ETag"].ToString();

                        if (!(string.IsNullOrEmpty(eventResponseConfigETag)) &&
                            cachedConfigETag != eventResponseConfigETag &&
                            DateTime.UtcNow > ((DateTime)confDict["last_updated_time"]).AddMinutes(5))
                        {
                            confDict = await GetConfig(client, confDict, eventResponseConfigETag);
                        }
                        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);
                    }
                }
            }
        }
Exemplo n.º 5
0
        private EventModel CreateEvent()
        {
            // Parameters for the API call
            var reqHeaders = new Dictionary <string, string>();

            reqHeaders.Add("Host", "api.acmeinc.com");
            reqHeaders.Add("Accept", "*/*");
            reqHeaders.Add("Connection", "Keep-Alive");
            reqHeaders.Add("Content-Type", "application/json");
            reqHeaders.Add("Accept-Encoding", "gzip");

            var reqBody = ApiHelper.JsonDeserialize <object>(@" {
                    ""items"": [
                        {
                            ""type"": 1,
                            ""id"": ""fwfrf""
                        },
                        {
                            ""type"": 2,
                            ""id"": ""d43d3f""
                        }
                    ]
                }");

            var rspHeaders = new Dictionary <string, string>();

            rspHeaders.Add("Vary", "Accept-Encoding");
            rspHeaders.Add("Pragma", "no-cache");
            rspHeaders.Add("Expires", "-1");
            rspHeaders.Add("Content-Type", "application/json; charset=utf-8");
            rspHeaders.Add("Cache-Control", "no-cache");

            var rspBody = ApiHelper.JsonDeserialize <object>(@" {
                    ""Error"": ""InvalidArgumentException"",
                    ""Message"": ""Missing field field_a""
                }");

            var eventReq = new EventRequestModel()
            {
                Time       = DateTime.UtcNow.AddSeconds(-1),
                Uri        = "https://api.acmeinc.com/items/reviews/",
                Verb       = "PATCH",
                ApiVersion = "1.1.0",
                IpAddress  = "61.48.220.123",
                Headers    = reqHeaders,
                Body       = reqBody
            };

            var eventRsp = new EventResponseModel()
            {
                Time    = DateTime.UtcNow,
                Status  = 200,
                Headers = rspHeaders,
                Body    = rspBody
            };

            Dictionary <string, string> metadata = new Dictionary <string, string>
            {
                { "email", "*****@*****.**" },
                { "name", "abcdef" },
                { "image", "123" }
            };

            var eventModel = new EventModel()
            {
                Request      = eventReq,
                Response     = eventRsp,
                UserId       = "123456",
                CompanyId    = "67890",
                SessionToken = "XXXXXXXXX",
                Metadata     = metadata
            };

            return(eventModel);
        }
Exemplo n.º 6
0
        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.ToDictionary(k => k.Key.ToLower(), k => k.Value)["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);
        }
Exemplo n.º 7
0
        private async Task LogEventAsync(EventRequestModel event_request, EventResponseModel event_response, string userId, string companyId, string sessionToken, Dictionary <string, object> metadata)
        {
            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
                {
                    LoggerHelper.LogDebugMessage(debug, "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)
                    {
                        LoggerHelper.LogDebugMessage(debug, "Add Event to the batch");

                        if (MoesifQueue.Count < queueSize)
                        {
                            // Add event to the batch
                            MoesifQueue.Enqueue(eventModel);

                            if (DateTime.Compare(lastWorkerRun, DateTime.MinValue) != 0)
                            {
                                if (lastWorkerRun.AddMinutes(1) < DateTime.UtcNow)
                                {
                                    LoggerHelper.LogDebugMessage(debug, "Scheduling worker thread. lastWorkerRun=" + lastWorkerRun.ToString());
                                    ScheduleWorker();
                                }
                            }
                        }
                        else
                        {
                            LoggerHelper.LogDebugMessage(debug, "Queue is full, skip adding events ");
                        }
                    }
                    else
                    {
                        await client.Api.CreateEventAsync(eventModel);

                        LoggerHelper.LogDebugMessage(debug, "Event sent successfully to Moesif");
                    }
                }
                else
                {
                    LoggerHelper.LogDebugMessage(debug, "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);
                }
            }
        }