public bool ValidateRequestPayloadSize(List <DispatchRequest> batchRequest, EventLogList eventLogList)
        {
            dispatchArr = new List <string>();
            double totalRecords = 0;

            for (int iter = 0; iter < batchRequest.Count(); iter++)
            {
                totalRecords += batchRequest[iter].PreFill.Count();
                if (!dispatchArr.Contains(batchRequest[iter].DispatchID))
                {
                    dispatchArr.Add(batchRequest[iter].DispatchID);
                }
            }

            int MaxPayload  = int.Parse(_config["MaxPayloadSize"]);
            int MaxDispatch = int.Parse(_config["MaxDispatchIDCount"]);

            if (totalRecords > MaxPayload)
            {
                eventLogList.AddEventByLevel(2, $"{SharedSettings.GetMaxRecordSizeExceedeed(MaxPayload)} - {totalRecords}", null, null);
                return(false);
            }
            else if (dispatchArr.Count > MaxDispatch)
            {
                eventLogList.AddEventByLevel(2, $"{SharedSettings.GetMaxDispatchNumberExceeded(MaxDispatch)} - {dispatchArr.Count}", null, null);
                return(false);
            }
            return(true);
        }
Пример #2
0
        /// <summary>
        /// To send async api request
        /// </summary>
        /// <param name="url">API url</param>
        /// <param name="bearerToken">Token for authorization</param>
        /// <param name="jsonBody">Json body to be send in request.</param>
        /// <returns>API response</returns>
        internal async Task <string> SendAsync(string url, string bearerToken, string jsonBody = null)
        {
            try
            {
                //To check whether url is not null or empty
                if (string.IsNullOrEmpty(url))
                {
                    throw new Exception("API url is either null or empty");
                }
                if (string.IsNullOrEmpty(bearerToken))
                {
                    throw new Exception("Authorization Token is either null or empty");
                }
                //Varible declarations.
                string responseBody = string.Empty;
#pragma warning disable IDE0067 // Dispose objects before losing scope
                HttpClient httpClient = new HttpClient();
#pragma warning restore IDE0067 // Dispose objects before losing scope
                HttpRequestMessage  requestMessage;
                HttpResponseMessage responseMessage;

                //To check whether the request is Post or Get
                if (!string.IsNullOrEmpty(jsonBody))
                {
                    requestMessage = new HttpRequestMessage(HttpMethod.Post, url)
                    {
                        Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
                    };
                }
                else
                {
                    requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
                }

                requestMessage.Headers.Add("Authorization", bearerToken);

                //Sending api request to CC.
                responseMessage = await httpClient.SendAsync(requestMessage);

                //Check whether the request is successfull.
                if (responseMessage != null)
                {
                    responseBody = await responseMessage.Content.ReadAsStringAsync();

                    if (responseMessage.IsSuccessStatusCode)
                    {
                        return(responseBody);
                    }
                    else if (responseMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        //Throw exception in case of authorization denied
                        InvitationsMemoryCache.GetInstance().RemoveFromMemoryCache(bearerToken);
                        throw new Exception(SharedSettings.AuthorizationDenied);
                    }
                    else
                    {
                        if (_EventLogList != null)
                        {
                            _EventLogList.AddEventByLevel(2, $"StatusCode: {responseMessage.StatusCode} " +
                                                          $"ResponseMessage: {responseBody} Url: {url}", _batchID);
                        }
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                if (_EventLogList != null)
                {
                    _EventLogList.AddExceptionEvent(ex, null, null, null, null, "HTTP Send failed for HTTPWrapper sendAsync");
                    return(null);
                }
                else
                {
                    throw ex;
                }
            }
        }
        public bool GetAllInfoForDispatch()
        {
            try
            {
                DispatchData     = InvitationsMemoryCache.GetInstance().GetDispatchDataFromMemoryCache(FinalToken, hTTPWrapper);
                DeliveryPlanData = InvitationsMemoryCache.GetInstance().GetDeliveryPlanFromMemoryCache(FinalToken, hTTPWrapper);
                ActiveQuestions  = InvitationsMemoryCache.GetInstance().GetActiveQuestionsFromMemoryCache(FinalToken, hTTPWrapper);
                DispatchSettings = InvitationsMemoryCache.GetInstance().GetSettingsFromMemoryCache(FinalToken, hTTPWrapper);

                if (DispatchData == null)
                {
                    EventLogList.AddEventByLevel(2, SharedSettings.NoDispatchFound, BatchId);
                    return(false);
                }

                if (DeliveryPlanData == null)
                {
                    EventLogList.AddEventByLevel(2, SharedSettings.NoDeliveryPlanFound, BatchId);
                    return(false);
                }

                if (ActiveQuestions == null)
                {
                    EventLogList.AddEventByLevel(2, SharedSettings.NoActiveQuestionsFound, BatchId);
                    return(false);
                }

                if (DispatchSettings == null)
                {
                    EventLogList.AddEventByLevel(2, SharedSettings.NoSettingsFound, BatchId);
                    return(false);
                }
                else
                {
                    Settings settingsRes = JsonConvert.DeserializeObject <Settings>(DispatchSettings);
                    if (settingsRes.locationDataMigrated)
                    {
                        SurverQuestionnaires = InvitationsMemoryCache.GetInstance().GetQuestionnaireFromMemoryCache(FinalToken, hTTPWrapper);
                        if (string.IsNullOrEmpty(SurverQuestionnaires))
                        {
                            EventLogList.AddEventByLevel(2, SharedSettings.NoSurveyQuestionnaireFound, BatchId);
                            return(false);
                        }
                        islocationMigrated = true;
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                EventLogList.AddExceptionEvent(ex, null, null, null, null, "Getting API details from MemoryCache failed");
                return(false);
            }
        }
Пример #4
0
        public async Task ReadQueue(CancellationToken cancellationToken)
        {
            EventLogList eventLog = new EventLogList();

            try
            {
                DateTime stopTime = DateTime.Now.AddSeconds(30);

                Dictionary <string, RequestBulkToken> finalBulkStorage = new
                                                                         Dictionary <string, RequestBulkToken>();

                while (DateTime.Now < stopTime)
                {
                    RequestBulkToken requestBulkToken;
                    if (!SingletonConcurrentQueue <RequestBulkToken> .Instance.TryPeek(out requestBulkToken))
                    {
                        break;
                    }
                    else if (SingletonConcurrentQueue <RequestBulkToken> .Instance.TryDequeue(out requestBulkToken))
                    {
                        if (finalBulkStorage.ContainsKey(requestBulkToken.DispatchId))
                        {
                            finalBulkStorage[requestBulkToken.DispatchId].PrefillReponse.AddRange(requestBulkToken.PrefillReponse);
                        }
                        else
                        {
                            finalBulkStorage.Add(requestBulkToken.DispatchId, new RequestBulkToken()
                            {
                                DispatchId     = requestBulkToken.DispatchId,
                                UUID           = requestBulkToken.UUID,
                                Batchid        = requestBulkToken.Batchid,
                                PrefillReponse = requestBulkToken.PrefillReponse
                            });
                        }
                    }
                }


                if (finalBulkStorage.Count != 0)
                {
                    HTTPWrapper hTTPWrapper = new HTTPWrapper(string.Empty, eventLog);
                    string      authToken   = InvitationsMemoryCache.GetInstance().GetFromMemoryCache("AuthToken");
                    if (authToken == null)
                    {
                        AccountConfiguration accountConfiguration;
                        string accountConfigurationCache = InvitationsMemoryCache.GetInstance().GetFromMemoryCache("accountconfig");
                        if (accountConfigurationCache == null)
                        {
                            accountConfiguration = await viaMongoDB.GetAccountConfiguration();
                        }
                        else
                        {
                            accountConfiguration = Newtonsoft.Json.JsonConvert.DeserializeObject <AccountConfiguration>(accountConfigurationCache);
                        }
                        string username     = accountConfiguration.WXMAdminUser;
                        string apikey       = accountConfiguration.WXMAPIKey;
                        string responseBody = await hTTPWrapper.GetLoginToken(username, apikey);

                        if (!string.IsNullOrEmpty(responseBody))
                        {
                            BearerToken loginToken = Newtonsoft.Json.JsonConvert.DeserializeObject <BearerToken>(responseBody);
                            authToken = "Bearer " + loginToken.AccessToken;
                            var Expirationtime = loginToken.ExpiresIn - 300;  // Expire 5 min before for uninterrupted token creation
                            InvitationsMemoryCache.GetInstance().SetBulkTokenAuthToMemoryCache("AuthToken", authToken, Expirationtime);
                        }
                        else
                        {
                            //when login token api failed.
                            eventLog.AddEventByLevel(1, SharedSettings.BearerTokenNotGenerated, null);
                            await eventLog.AddEventLogs(viaMongoDB);
                        }
                    }

                    // Calling bulk token api sequentially
                    if (!string.IsNullOrWhiteSpace(authToken))
                    {
                        List <(string, List <BulkTokenResult>)> status = new List <(string, List <BulkTokenResult>)>();

                        foreach (var request in finalBulkStorage)
                        {
                            var response = await hTTPWrapper.BulkTokenAPI(authToken, request.Value);

                            status.Add(response);
                            Thread.Sleep(1000);  // Sleep for 1 second before making another call
                        }


                        /*
                         * var bulkTokenAPITasks = finalBulkStorage.Values.ToList().Select(v =>
                         * {
                         *  return hTTPWrapper.BulkTokenAPI(authToken, v);
                         * });
                         *
                         * (string, List<BulkTokenResult>)[] status = await Task.WhenAll(bulkTokenAPITasks);
                         *
                         */


                        Dictionary <LogEvent, InvitationLogEvent> events = new Dictionary <LogEvent, InvitationLogEvent>();
                        DateTime utcNow = DateTime.UtcNow;

                        //Update tokens in DB
                        foreach (var item in status)
                        {
                            if (item.Item2 != null)
                            {
                                foreach (var perinvite in item.Item2)
                                {
                                    var logEvent = new LogEvent()
                                    {
                                        DispatchId   = item.Item1,
                                        BatchId      = perinvite.Batchid,
                                        Updated      = utcNow,
                                        TokenId      = perinvite.Token,
                                        TargetHashed = perinvite.UUID
                                    };

                                    var invitationEvent = new InvitationLogEvent()
                                    {
                                        Action    = InvitationLogEvent.EventAction.TokenCreated,
                                        Channel   = InvitationLogEvent.EventChannel.DispatchAPI,
                                        TimeStamp = utcNow,
                                        TargetId  = perinvite.UUID
                                    };
                                    events.Add(logEvent, invitationEvent);
                                }
                            }
                        }

                        if (events.Count() > 0)
                        {
                            await viaMongoDB.UpdateBulkEventLog(events);
                        }

                        eventLog.AddEventByLevel(5, $"{SharedSettings.DBUpdateCompleted} {events.Count()}", null);
                        await eventLog.AddEventLogs(viaMongoDB);
                    }
                }
            }
            catch (Exception ex)
            {
                eventLog.AddExceptionEvent(ex, null, null, null, null, SharedSettings.BulkTokenException);
                await eventLog.AddEventLogs(viaMongoDB);

                return;
            }
        }