private Task <IIndexResponse> CreateSystemEvent(EventRequestModel model, CancellationToken cancellationToken) { if (model.Tags == null) { model.Tags = new List <string>(); } model.Tags.Add(model.Level.ToString()); model.Tags.Add(model.Category); model.Tags.Add(model.TargetKey); // Remove duplicates var hashset = model.Tags.ToHashSet(); var eventTimestamp = _timeStampFactory.GetTimestamp(); var systemEvent = new SystemEventElasticsearchDocument { Category = model.Category, Level = model.Level.ToString(), TargetKey = model.TargetKey, Message = $"{model.Message} by {model.Sender}", Tags = hashset.ToArray(), Sender = model.Sender, Timestamp = eventTimestamp, Endtime = eventTimestamp }; return(_esClient.IndexAsync(systemEvent, cancellationToken: cancellationToken)); }
public static Event CastEventRequestToEvent(EventRequestModel model) { var evnt = new Event(); evnt.EventCreateTime = DateTime.Now; evnt.EventType = (int)EventTypes.GoReturn; evnt.EventCoductorName = model.Name; evnt.EventCoductorFamily = model.Family; evnt.EventCoductorMobile = model.Mobile; evnt.EventName = model.EventName; evnt.EventLink = model.EventLink; var startTime = new DateTime(model.Edate.Year, model.Edate.Month, model.Edate.Day, model.TimeStart.Hour, model.TimeStart.Minute, 0); evnt.EventStartTime = startTime; var endTime = new DateTime(model.Edate.Year, model.Edate.Month, model.Edate.Day, model.TimeEnd.Hour, model.TimeEnd.Minute, 0); evnt.EventEndTime = endTime; evnt.EventDeadLine = endTime.AddHours(2); evnt.EventConfirmed = 0;//false evnt.EventDesc = ""; evnt.EventAddress = ""; evnt.EventLat = decimal.Parse(model.Latitude); evnt.EventLng = decimal.Parse(model.Longitude); evnt.IsConfirmed = false; return(evnt); }
public async static Task <EventRequestModel> genEventRequestModel(HttpMessage request, string ReqHeadersName, string RequestTimeName, string _ApiVersion, string clientIpAddress) { var h = request.HttpRequestMessage; var reqBody = h.Content != null ? await h.Content.ReadAsStringAsync() : null; var reqHeaders = HeadersUtils.deSerializeHeaders(h.Properties[ReqHeadersName]); var reqBodyWrapper = BodyUtil.Serialize(reqBody); EventRequestModel moesifRequest = new EventRequestModel() { Time = (DateTime)h.Properties[RequestTimeName], Uri = h.RequestUri.OriginalString, /* Uri = (String)request.HttpRequestMessage.Headers.GetValues("originalURL").FirstOrDefault(),*/ Verb = h.Method.ToString(), Headers = reqHeaders, ApiVersion = _ApiVersion, /*IpAddress = null,*/ /*IpAddress = (String)request.HttpRequestMessage.Headers.GetValues("clientIPAddress").FirstOrDefault(),*/ IpAddress = clientIpAddress, Body = reqBodyWrapper.Item1, TransferEncoding = reqBodyWrapper.Item2 }; return(moesifRequest); }
/** * From Http request and response, construct the moesif EventModel */ public async Task <EventModel> BuildMoesifEvent(HttpMessage request, HttpMessage response) { _Logger.LogDebug("Building Moesif event"); EventRequestModel moesifRequest = await genEventRequestModel(request, ReqHeadersName, RequestTimeName, _ApiVersion); EventResponseModel moesifResponse = await genEventResponseModel(response); Dictionary <string, object> metadata = genMetadata(request, MetadataName); 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); }
public async static Task <EventRequestModel> genEventRequestModel(HttpMessage request, string ReqHeadersName, string RequestTimeName, string _ApiVersion) { var h = request.HttpRequestMessage; var reqBody = h.Content != null ? await h.Content.ReadAsStringAsync() : null; var reqHeaders = HeadersUtils.deSerializeHeaders(h.Properties[ReqHeadersName]); var reqBodyWrapper = BodyUtil.Serialize(reqBody); EventRequestModel moesifRequest = new EventRequestModel() { Time = (DateTime)h.Properties[RequestTimeName], Uri = h.RequestUri.OriginalString, Verb = h.Method.ToString(), Headers = reqHeaders, ApiVersion = _ApiVersion, IpAddress = null, Body = reqBodyWrapper.Item1, TransferEncoding = reqBodyWrapper.Item2 }; return(moesifRequest); }
public int Save(EventRequestModel model) { EventRequest _eventRequest = new EventRequest(model); if (model.Id != null && model.Id != 0) { _EventRequest.Update(_eventRequest); } else { RequestSubmitModel res = new RequestSubmitModel(); res.RequestTypeId = 9; res.UserId = model.UserId; res.ShortDesc = model.Description; int id = new RequestSubmitBs().Save(res); _eventRequest.RequestSubmitId = id; _eventRequest.Poster = model.Poster; _eventRequest.CreatedDate = System.DateTime.Now; _eventRequest.RequestTypeId = 9; _EventRequest.Insert(_eventRequest); } return(_eventRequest.Id); }
public ActionResult CreateEvent(EventRequestModel model) { long i = 0; if (model != null) { //if (File != null) //{ // model.Poster = new byte[File.ContentLength]; // File.InputStream.Read(model.Poster, 0, File.ContentLength); //} model.UserId = new UserRegistrationBs().UserRegistrationList().Where(x => x.UserName == User.Identity.Name).FirstOrDefault().Id; i = _EventRequestBs.Save(model); } if (i > 0) { TempData["msg"] = "Save Successfully"; } else { TempData["msg"] = "Error while saving data"; } return(RedirectToAction("Index", "EventRequest", new { area = "User" })); }
private async Task <(EventRequestModel, String)> FormatRequest(HttpRequest request, string transactionId) { // Request headers var reqHeaders = LoggerHelper.ToHeaders(request.Headers, debug); // RequestBody request.EnableBuffering(bufferThreshold: 1000000); string bodyAsText = null; string contentEncoding = ""; string contentLength = ""; int parsedContentLength = 100000; reqHeaders.TryGetValue("Content-Encoding", out contentEncoding); reqHeaders.TryGetValue("Content-Length", out contentLength); int.TryParse(contentLength, out parsedContentLength); bodyAsText = await LoggerHelper.GetRequestContents(bodyAsText, request, contentEncoding, parsedContentLength, debug); // Add Transaction Id to the Request Header bool disableTransactionId = LoggerHelper.GetConfigBoolValues(moesifOptions, "DisableTransactionId", false); if (!disableTransactionId) { transactionId = LoggerHelper.GetOrCreateTransactionId(reqHeaders, "X-Moesif-Transaction-Id"); reqHeaders = LoggerHelper.AddTransactionId("X-Moesif-Transaction-Id", transactionId, reqHeaders); } // Serialize request body var bodyWrapper = LoggerHelper.Serialize(bodyAsText, request.ContentType, logBody, debug); // Client Ip Address string ip = clientIpHelper.GetClientIp(reqHeaders, request); var uri = new Uri(request.GetDisplayUrl()).ToString(); string apiVersion = null; var apiVersion_out = new object(); var getApiVersion = moesifOptions.TryGetValue("ApiVersion", out apiVersion_out); if (getApiVersion) { apiVersion = apiVersion_out.ToString(); } var eventReq = new EventRequestModel() { Time = DateTime.UtcNow, Uri = uri, Verb = request.Method, ApiVersion = apiVersion, IpAddress = ip, Headers = reqHeaders, Body = bodyWrapper.Item1, TransferEncoding = bodyWrapper.Item2 }; return(eventReq, transactionId); }
public EventRequestModel GetByRequestSubmitIdBoard(int id, int userid) { EventRequestModel varList = new EventRequestModel(); var item = _EventRequest.GetAll().Where(x => x.RequestSubmitId == id).FirstOrDefault(); item = item ?? new EventRequest(); varList = new EventRequestModel { Id = item.Id, EventName = item.EventName, Description = item.Description, TotalSpeakers = item.TotalSpeakers, Poster = item.Poster, FromDate = item.FromDate, ToDate = item.ToDate, CreatedDate = item.CreatedDate, Venu = item.Venu, UserId = item.UserId, UserName = (item.User != null) ? item.User.Name : string.Empty, RequestTypeId = item.RequestTypeId, RequestTypeName = (item.RequestType != null) ? item.RequestType.Name : string.Empty, RequestSubmitId = item.RequestSubmitId, }; RequestCommentBs obj = new RequestCommentBs(); var BoardComments = obj.BoardCommentList(id).ToList(); varList.BoardCommentList = BoardComments; var PannelComments = obj.PanelCommentList(id).ToList(); varList.PanelCommentList = PannelComments; RequestApproveRejectBs obj1 = new RequestApproveRejectBs(); varList.ApprovedList = obj1.ApproveRejectDisplay(id).ToList(); varList.AlreadyExistsInMemberOpinion = varList.ApprovedList == null ? false : varList.ApprovedList.Where(m => m.UserTypeId == userid && m.RequestSubmitId == item.RequestSubmitId).Any(); if (varList.AlreadyExistsInMemberOpinion) { varList.MemberOpinionId = varList.ApprovedList.Where(m => m.UserTypeId == userid && m.RequestSubmitId == item.RequestSubmitId).FirstOrDefault().Id; varList.IsAgreed = varList.ApprovedList.Where(m => m.UserTypeId == userid && m.RequestSubmitId == item.RequestSubmitId).FirstOrDefault().IsApproved; varList.LikeStatus = varList.ApprovedList.Where(m => m.UserTypeId == userid && m.RequestSubmitId == item.RequestSubmitId).FirstOrDefault().LikeStatus; } PanelInvolveBs panelobject = new PanelInvolveBs(); varList.PannelMemberInvolved = panelobject.InvolveList(id).ToList(); return(varList); }
public EventRequest(EventRequestModel item) { Id = item.Id; EventName = item.EventName; Description = item.Description; TotalSpeakers = item.TotalSpeakers; Venu = item.Venu; FromDate = item.FromDate; ToDate = item.ToDate; CreatedDate = item.CreatedDate; UserId = item.UserId; EventType = item.EventTypeId; RequestTypeId = item.RequestTypeId; RequestSubmitId = item.RequestSubmitId; }
public async Task ProcessHttpMessage(HttpMessage message) { if (message.IsRequest) { message.HttpRequestMessage.Properties.Add(RequestTimeName, DateTime.UtcNow); return; } EventRequestModel moesifRequest = new EventRequestModel() { Time = (DateTime)message.HttpRequestMessage.Properties[RequestTimeName], Uri = message.HttpRequestMessage.RequestUri.OriginalString, Verb = message.HttpRequestMessage.Method.ToString(), Headers = ToHeaders(message.HttpRequestMessage.Headers), ApiVersion = _ApiVersion, IpAddress = null, Body = System.Convert.ToBase64String(await message.HttpRequestMessage.Content.ReadAsByteArrayAsync()), TransferEncoding = "base64" }; EventResponseModel moesifResponse = new EventResponseModel() { Time = DateTime.UtcNow, Status = (int)message.HttpResponseMessage.StatusCode, IpAddress = Environment.MachineName, Headers = ToHeaders(message.HttpResponseMessage.Headers), Body = System.Convert.ToBase64String(await message.HttpResponseMessage.Content.ReadAsByteArrayAsync()), TransferEncoding = "base64" }; Dictionary <string, string> metadata = new Dictionary <string, string>(); metadata.Add("ApimMessageId", message.MessageId.ToString()); EventModel moesifEvent = new EventModel() { Request = moesifRequest, Response = moesifResponse, SessionToken = message.HttpRequestMessage.Headers.GetValues(_SessionTokenKey).FirstOrDefault(), Tags = null, UserId = null, Metadata = metadata }; Dictionary <string, string> response = await _MoesifClient.Api.CreateEventAsync(moesifEvent); _Logger.LogDebug("Message forwarded to Moesif"); }
public async Task <EventResponse> EventPostAsync(EventRequestModel model) { var latency = PreInvoke(_clientName, _eventPostAsyncMethodName, model); try { var result = await _systemEventsClient.CreateAsync(model); PostInvokeSuccess(latency, _clientName, _eventPostAsyncMethodName, result); return(result); } catch (Exception ex) { PostInvokeFailure(_clientName, _eventPostAsyncMethodName, ex, model); throw; } }
public ActionResult CreateEvent(int?id) { EventRequestModel model = new EventRequestModel(); if (id != null) { var Varial = _EventRequestBs.GetById(Convert.ToInt32(id)); return(View(Varial)); } else { ViewBag.EventTypeName = new SelectList(_EventRequestBs.GetAllEventMasterList(), "Id", "Name"); } return(View(model)); }
public IHttpActionResult InsertEvent(EventRequestModel model) { try { if (!ModelState.IsValid) { return(Json(_responseProvider.GenerateBadRequestResponse(ModelState))); } _routemanager.InsertEvent(model); ResponseModel responseModel = _responseProvider.GenerateOKResponse(); return(Json(responseModel)); } catch (Exception e) { _logmanager.Log(Tag, "InsertEvent", e.Message); } return(Json(_responseProvider.GenerateUnknownErrorResponse())); }
public async Task <IActionResult> Create([FromBody] EventRequestModel model) { var userId = User.GetUserId(); if (!await _calendarService.CanEditAsync(model.CalendarId, userId)) { return(this.BadRequestError("You don't have any permissions to create event in that calendar.")); } var eventDomain = _mapper.Map <Event>(model); var id = await _eventService.CreateEventAsync(eventDomain, userId); var calendar = await _calendarService.GetCalendarByIdAsync(model.CalendarId, nameof(Calendar.Owner)); if (userId != calendar.Owner.Id) { await _notificationManager.EventInCalendarCreatedAsync(calendar.Owner.Id, User.Identity.Name, model.Name, calendar.Name); } return(Ok(new { Id = id })); }
public override BaseState Run() { var eventNames = BotConstants.sampleEventNames[new Random().Next(6)]; var eventModel = new EventRequestModel { event_datetime = DateTime.Now, event_common = this.eventCommon, event_dic = new Dictionary <string, string>() }; foreach (var eventName in eventNames) { eventModel.event_name = eventName; if (eventName == BotConstants.LOGIN_EVENT) { eventModel.event_dic.Add("user_id", Guid.NewGuid().ToString()); } if (eventName == BotConstants.LOGOUT_EVENT) { eventModel.event_dic.Remove("user_id"); } } var httpRequestModel = new HttpRequestModel { Url = "", HttpMethod = HttpMethod.Post, Headers = new Dictionary <string, string> { { "content-type", "application/json" } }, Body = JsonConvert.SerializeObject(eventModel) }; NetworkUtil.HttpRequestAsync(httpRequestModel).Wait(); return(this); }
public async Task <IActionResult> Update(int id, [FromBody] EventRequestModel model) { var userId = User.GetUserId(); if (!await _eventService.CanEditAsync(id, userId)) { return(this.BadRequestError("You don't have any permissions to edit that event.")); } var eventDomain = await _eventService.GetEventByIdAsync(id, "Period", nameof(Event.Owner)); eventDomain = _mapper.Map(model, eventDomain); eventDomain.Id = id; await _eventService.UpdateEventAsync(eventDomain); if (userId != eventDomain.Owner.Id) { await _notificationManager.EventEditedAsync(eventDomain.Owner.Id, User.Identity.Name, eventDomain.Name, model.Name); } return(Ok()); }
public async Task <ActionResult <EventResponse> > Create([FromBody] EventRequestModel model, CancellationToken cancellationToken) { if (!Validate(model, out string reason)) { return(BadRequest($"Invalid request: {reason}")); } var response = await CreateSystemEvent(model, cancellationToken); if (!response.IsValid) { throw new ArgumentException("System event was not created"); } if (_categorySubscriptionNotifier == null) { return(Ok(new EventResponse { EventId = response.Id })); } // Notify about this event try { var document = await _esClient.GetAsync(response.Id, cancellationToken); await _categorySubscriptionNotifier.OnEventCreated(model.Category, document, cancellationToken); } catch (Exception exception) { // Ignore failure to send notification about system event _logger.LogError(exception, $"Error sending notifications for event with id {response.Id}"); } return(Ok(new EventResponse { EventId = response.Id })); }
private async Task <(EventRequestModel, String)> ToRequest(IOwinRequest request, string transactionId) { // Request headers var reqHeaders = LoggerHelper.ToHeaders(request.Headers, debug); // RequestBody string contentEncoding = ""; string contentLength = ""; int parsedContentLength = 100000; string body = null; reqHeaders.TryGetValue("Content-Encoding", out contentEncoding); reqHeaders.TryGetValue("Content-Length", out contentLength); int.TryParse(contentLength, out parsedContentLength); try { body = await LoggerHelper.GetRequestContents(request, contentEncoding, parsedContentLength, disableStreamOverride); } catch { LoggerHelper.LogDebugMessage(debug, "Cannot read request body."); } var bodyWrapper = LoggerHelper.Serialize(body, request.ContentType); // Add Transaction Id to the Request Header bool disableTransactionId = LoggerHelper.GetConfigBoolValues(moesifOptions, "DisableTransactionId", false); if (!disableTransactionId) { transactionId = LoggerHelper.GetOrCreateTransactionId(reqHeaders, "X-Moesif-Transaction-Id"); reqHeaders = LoggerHelper.AddTransactionId("X-Moesif-Transaction-Id", transactionId, reqHeaders); } string ip = clientIpHelper.GetClientIp(reqHeaders, request); var uri = request.Uri.ToString(); string apiVersion = null; var apiVersion_out = new object(); var getApiVersion = moesifOptions.TryGetValue("ApiVersion", out apiVersion_out); if (getApiVersion) { apiVersion = apiVersion_out.ToString(); } var eventReq = new EventRequestModel() { Time = DateTime.UtcNow, Uri = uri, Verb = request.Method, ApiVersion = apiVersion, IpAddress = ip, Headers = reqHeaders, Body = bodyWrapper.Item1, TransferEncoding = bodyWrapper.Item2 }; return(eventReq, transactionId); }
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); } } }
private async Task <EventRequestModel> FormatRequest(IOwinRequest request) { var body = request.Body; string requestBody = await new StreamReader(request.Body).ReadToEndAsync(); // Read request Body byte[] requestData = Encoding.UTF8.GetBytes(requestBody); request.Body = new MemoryStream(requestData); var reqHeaders = new Dictionary <string, string>(); try { reqHeaders = request.Headers.ToDictionary(k => k.Key, k => k.Value.First(), StringComparer.OrdinalIgnoreCase); } catch (Exception inst) { if (debug) { Console.WriteLine("error encountered while copying request header"); Console.WriteLine(inst); } } // Add Transaction Id to the Request Header var transation_id_out = new Object(); var captureTransactionId = moesifOptions.TryGetValue("DisableTransactionId", out transation_id_out); bool GetCaptureTransactionId = false; if (captureTransactionId) { GetCaptureTransactionId = (bool)(transation_id_out); } if (!GetCaptureTransactionId) { if (reqHeaders.ContainsKey("X-Moesif-Transaction-Id")) { string reqTransId = reqHeaders["X-Moesif-Transaction-Id"]; if (!string.IsNullOrEmpty(reqTransId)) { transactionId = reqTransId; if (string.IsNullOrEmpty(transactionId)) { transactionId = Guid.NewGuid().ToString(); } } else { transactionId = Guid.NewGuid().ToString(); } } else { transactionId = Guid.NewGuid().ToString(); } // Add Transaction Id to the Request Header reqHeaders["X-Moesif-Transaction-Id"] = transactionId; } var reqBody = new object(); reqBody = null; string requestTransferEncoding; requestTransferEncoding = null; if (logBody) { try { reqBody = ApiHelper.JsonDeserialize <object>(requestBody); } catch (Exception inst) { if (debug) { Console.WriteLine("About to parse Request body as Base64 encoding"); } // Get Request Body reqBody = Base64Encode(requestBody); requestTransferEncoding = "base64"; } } string ip = null; try { List <string> proxyHeaders = new List <string> { "X-Client-Ip", "X-Forwarded-For", "Cf-Connecting-Ip", "True-Client-Ip", "X-Real-Ip", "X-Cluster-Client-Ip", "X-Forwarded", "Forwarded-For", "Forwarded" }; if (!proxyHeaders.Intersect(reqHeaders.Keys.ToList(), StringComparer.OrdinalIgnoreCase).Any()) { ip = request.RemoteIpAddress.ToString(); } else { ClientIp helpers = new ClientIp(); ip = helpers.GetClientIp(reqHeaders, request); } } catch (Exception inst) { Console.WriteLine("error encountered while trying to get the client IP address"); Console.WriteLine(inst); } var uri = request.Uri.ToString(); string apiVersion = null; var apiVersion_out = new object(); var getApiVersion = moesifOptions.TryGetValue("ApiVersion", out apiVersion_out); if (getApiVersion) { apiVersion = apiVersion_out.ToString(); } var eventReq = new EventRequestModel() { Time = DateTime.UtcNow, Uri = uri, Verb = request.Method, ApiVersion = apiVersion, IpAddress = ip, Headers = reqHeaders, Body = reqBody, TransferEncoding = requestTransferEncoding }; return(eventReq); }
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); } } }
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); }
/** * 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 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); } } } }
public EventRequestController() { _EventRequestBs = new EventRequestBs(); _EventRequestModel = new EventRequestModel(); }
private bool Validate(EventRequestModel model, out string reason) { if (model == null) { reason = $"{nameof(model)} can not be null"; return(false); } if (string.IsNullOrWhiteSpace(model.Category)) { reason = $"{nameof(model.Category)} can not be null or whitespace"; return(false); } if (string.IsNullOrWhiteSpace(model.TargetKey)) { reason = $"{nameof(model.TargetKey)} can not be null or whitespace"; return(false); } if (string.IsNullOrWhiteSpace(model.Message)) { reason = $"{nameof(model.Message)} can not be null or whitespace"; return(false); } if (string.IsNullOrWhiteSpace(model.Sender)) { reason = $"{nameof(model.Sender)} can not be null or whitespace"; return(false); } model.Category = model.Category.Trim(); model.TargetKey = model.TargetKey.Trim(); model.Sender = model.Sender.Trim(); if (_advanceConfiguration?.Categories == null) { reason = null; return(true); } var allAllowed = _advanceConfiguration.Categories.Any(c => c.Name == "*"); // If Advance Configuration is enabled then only specified categories // from the configuration can be used var category = _advanceConfiguration.Categories.FirstOrDefault( c => c.Name == model.Category); if (!allAllowed && category == null) { reason = $"The provided category `{model.Category}` is not allowed. Check" + "/category/all for a list of allowed categories or contact your system administrator."; return(false); } if (category?.Level != null && category.Level.Value != model.Level) { reason = $"Only events of level `{category.Level.Value}` are allowed for category `{model.Category}`. Check" + "/category/all for a list of allowed categories or contact your system administrator."; return(false); } reason = null; return(true); }
public async Task <ActionResult> SlackInteractiveAction([FromForm] InteractivePayload request, CancellationToken cancellationToken) { var payload = JsonConvert.DeserializeObject <Payload>(request.payload); var values = payload.view.state.values; string category = null; try { if (_configuration.ShowPredefinedCategory) { category = values.event_category_select.category.selected_option.value.Trim(); } } catch { if (!_configuration.ShowCustomCategory) { return(Ok(new { response_action = "errors", errors = new { event_category_select = "Select a category for your event", } })); } } try { if (string.IsNullOrWhiteSpace(category) && _configuration.ShowCustomCategory) { category = values.event_custom_category.custom_category.value.Trim(); } } catch { return(Ok(new { response_action = "errors", errors = new { event_custom_category = "Enter a category for your event", } })); } if (string.IsNullOrWhiteSpace(category)) { return(Ok(new { response_action = "errors", errors = new { event_category_select = "Select a category for your event", event_custom_category = "Enter a category for your event", } })); } var tags = new List <string>(); if (!string.IsNullOrWhiteSpace(values.event_tags.tags.value)) { tags = values.event_tags.tags.value .Split(",") .Select(e => e.Trim()) .Where(e => !string.IsNullOrWhiteSpace(e)) .ToList(); } if (string.IsNullOrWhiteSpace(values?.event_target?.target?.value)) { return(Ok(new { response_action = "errors", errors = new { event_target = "Enter a target for your event" } })); } if (string.IsNullOrWhiteSpace(values?.event_message?.message?.value)) { return(Ok(new { response_action = "errors", errors = new { event_message = "Enter a message for your event" } })); } var model = new EventRequestModel { Category = category, TargetKey = values.event_target.target.value, Level = GetLevel(values.event_level.level.selected_option.value), Message = values.event_message.message.value, Sender = payload.user.username, Tags = new ObservableCollection <string>(tags) }; await _systemEventClient.EventPostAsync(model); return(Ok(new { response_action = "clear" })); }
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); }
private async Task <EventRequestModel> FormatRequest(HttpRequest request) { var body = request.Body; request.EnableRewind(); var buffer = new byte[Convert.ToInt32(request.ContentLength)]; await request.Body.ReadAsync(buffer, 0, buffer.Length); var bodyAsText = Encoding.UTF8.GetString(buffer); request.Body = body; var reqHeaders = new Dictionary <string, string>(); try { reqHeaders = request.Headers.ToDictionary(k => k.Key, k => k.Value.ToString(), StringComparer.OrdinalIgnoreCase); } catch (Exception inst) { if (debug) { Console.WriteLine("error encountered while copying request header"); Console.WriteLine(inst); } } // Add Transaction Id to the Request Header var transation_id_out = new Object(); var captureTransactionId = moesifOptions.TryGetValue("DisableTransactionId", out transation_id_out); bool GetCaptureTransactionId = false; if (captureTransactionId) { GetCaptureTransactionId = (bool)(transation_id_out); } if (!GetCaptureTransactionId) { if (reqHeaders.ContainsKey("X-Moesif-Transaction-Id")) { string reqTransId = reqHeaders["X-Moesif-Transaction-Id"]; if (!string.IsNullOrEmpty(reqTransId)) { transactionId = reqTransId; if (string.IsNullOrEmpty(transactionId)) { transactionId = Guid.NewGuid().ToString(); } } else { transactionId = Guid.NewGuid().ToString(); } } else { transactionId = Guid.NewGuid().ToString(); } // Add Transaction Id to the Request Header reqHeaders["X-Moesif-Transaction-Id"] = transactionId; } var reqBody = new object(); reqBody = null; try { reqBody = ApiHelper.JsonDeserialize <object>(bodyAsText); } catch (Exception inst) { Console.WriteLine("error encountered while trying to serialize request body"); Console.WriteLine(inst); } string ip = null; try { List <string> proxyHeaders = new List <string> { "X-Client-Ip", "X-Forwarded-For", "Cf-Connecting-Ip", "True-Client-Ip", "X-Real-Ip", "X-Cluster-Client-Ip", "X-Forwarded", "Forwarded-For", "Forwarded" }; if (!proxyHeaders.Intersect(reqHeaders.Keys.ToList(), StringComparer.OrdinalIgnoreCase).Any()) { ip = request.HttpContext.Connection.RemoteIpAddress.ToString(); } else { ClientIp helpers = new ClientIp(); ip = helpers.GetClientIp(reqHeaders, request); } } catch (Exception inst) { Console.WriteLine("error encountered while trying to get the client IP address"); Console.WriteLine(inst); } var uri = new Uri(request.GetDisplayUrl()).ToString(); string apiVersion = null; var apiVersion_out = new object(); var getApiVersion = moesifOptions.TryGetValue("ApiVersion", out apiVersion_out); if (getApiVersion) { apiVersion = apiVersion_out.ToString(); } var eventReq = new EventRequestModel() { Time = DateTime.UtcNow, Uri = uri, Verb = request.Method, ApiVersion = apiVersion, IpAddress = ip, Headers = reqHeaders, Body = reqBody }; return(eventReq); }