public async void ProcessNotification(object message)
        {
            try
            {
                Amazon.SQS.Model.Message msg = (Amazon.SQS.Model.Message)message;

                string queMessage = msg.Body;
                //LogInfo.Information("8 - bsubscription is  {" + msg.MessageId + "} object");
                SNSSubscription subscription = JsonConvert.DeserializeObject <SNSSubscription>(queMessage);

                //LogInfo.Information("8 - bsubscription is  {" + subscription.MessageId + "} object");
                NotificationMessage NotMessage = JsonConvert.DeserializeObject <NotificationMessage>(subscription.Message);
                //LogInfo.Information("9 - NotMessage is  {" + NotMessage.Message +" "+ NotMessage.MessageType + "} object");
                // SNSSubscription messageObject= new SNSSubscription {  Message=me};

                //   NotificationMessage notification= JsonConvert.DeserializeObject<NotificationMessage>(messageObject.Message);
                if (NotMessage.MessageType == NotificationMsgType.Email.GetDescription())
                {
                    OutboundEmail _email = new OutboundEmail();

                    ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);

                    DatabaseResponse emailTemplate = await _configAccess.GetEmailNotificationTemplate(NotMessage.Message.messagetemplate.ToString());

                    EmailTemplate template = (EmailTemplate)emailTemplate.Results;

                    var responses = await _email.SendEmail(NotMessage, _iconfiguration, template);


                    foreach (Mandrill.Model.MandrillSendMessageResponse response in responses)
                    {
                        foreach (NotificationParams param in NotMessage.Message.parameters)
                        {
                            if (response.Email == param.emailaddress)
                            {
                                DatabaseResponse notificationLogResponse = await _configAccess.CreateEMailNotificationLog(new NotificationLog {
                                    Status          = response.Status.ToString() == "Sent" ? 1 : 0, Email = response.Email,
                                    EmailTemplateID = template.EmailTemplateID, EmailBody = template.EmailBody,
                                    EmailSubject    = template.EmailSubject, ScheduledOn = subscription.Timestamp, SendOn = DateTime.Now
                                });
                            }
                        }
                    }
                }
                else if (NotMessage.MessageType == NotificationMsgType.SMS.GetDescription())
                {
                    OutboundSMS      _SMS          = new OutboundSMS();
                    TextMessage      smsData       = new TextMessage();
                    ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);

                    DatabaseResponse smsTemplate = await _configAccess.GetSMSNotificationTemplate(NotMessage.Message.messagetemplate.ToString());

                    SMSTemplates template = (SMSTemplates)smsTemplate.Results;

                    foreach (var item in NotMessage.Message.parameters)
                    {
                        smsData.PhoneNumber = item.mobilenumber;

                        smsData.SMSText = template.SMSTemplate.Replace("*|NAME|*", item.name)
                                          .Replace("*|PARAM1|*", item.param1)
                                          .Replace("*|PARAM2|*", item.param2)
                                          .Replace("*|PARAM3|*", item.param3)
                                          .Replace("*|PARAM4|*", item.param4)
                                          .Replace("*|PARAM5|*", item.param5)
                                          .Replace("*|PARAM6|*", item.param6)
                                          .Replace("*|PARAM7|*", item.param7)
                                          .Replace("*|PARAM8|*", item.param8)
                                          .Replace("*|PARAM9|*", item.param9)
                                          .Replace("*|PARAM10|*", item.param10);
                        //LogInfo.Information("10 - SendSMS is  { "+ smsData+ "}");
                        string response = await _SMS.SendSMSNotification(smsData, _iconfiguration);

                        await _configAccess.CreateSMSNotificationLog(new SMSNotificationLog()
                        {
                            Email         = NotMessage.Message.parameters.Select(x => x.emailaddress).FirstOrDefault(),
                            Mobile        = smsData.PhoneNumber,
                            SMSTemplateID = template.SMSTemplateID,
                            SMSText       = smsData.SMSText,
                            Status        = response != "failure" ? 1 : 0,
                            ScheduledOn   = subscription.Timestamp,
                            SendOn        = DateTime.Now
                        });
                    }

                    //LogInfo.Information("10 - SendSMSLog is  { " + NotMessage.Message.parameters.Select(x => x.emailaddress).FirstOrDefault() + " " + smsData.PhoneNumber + " "+ response + "}");
                }
            }

            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
            }
        }
Exemplo n.º 2
0
        private static async void TimerCallback()
        {
            try
            {
                Console.WriteLine("Start timer action: " + DateTime.Now);

                LogInfo.Information("Start timer action: " + DateTime.Now);

                BuddyDataAccess buddyDataAccess = new BuddyDataAccess();

                BuddyHelper buddyHelper = new BuddyHelper(_connectionString);

                DatabaseResponse pendingBuddyResponse = await buddyDataAccess.GetPendingBuddyList(_connectionString);

                //Getting all pending buddy orders and numbers to process buddy
                if (pendingBuddyResponse != null && pendingBuddyResponse.ResponseCode == (int)DbReturnValue.RecordExists)
                {
                    List <PendingBuddy> pendingBuddyList = new List <PendingBuddy>();

                    pendingBuddyList = (List <PendingBuddy>)pendingBuddyResponse.Results;

                    // Taking only order ID

                    List <int> orderList = (from buddy in pendingBuddyList select(buddy.OrderID)).ToList();

                    if (orderList != null && orderList.Count > 0)
                    {
                        foreach (int orderID in orderList)
                        {
                            // taking an order from the list and lock  it for processing if its not already locked
                            DatabaseResponse lockCheckResponse = await buddyDataAccess.CheckBuddyLocked(orderID, _connectionString);

                            if (lockCheckResponse.ResponseCode == (int)DbReturnValue.PendingBuddyUnLocked)
                            {
                                List <PendingBuddy> buddyListToProcess = new List <PendingBuddy>();

                                buddyListToProcess = pendingBuddyList.Where(buddy => buddy.OrderID == orderID).ToList();

                                foreach (PendingBuddy buddy in buddyListToProcess)
                                {
                                    int buddyToProcessCount = buddyListToProcess.Count;

                                    DatabaseResponse customerIDResponse = new DatabaseResponse();

                                    int customerID;

                                    customerIDResponse = await buddyDataAccess.GetCustomerIdFromOrderId(buddy.OrderID, _connectionString);

                                    if (customerIDResponse != null && customerIDResponse.Results != null)
                                    {
                                        customerID = ((OrderCust)customerIDResponse.Results).CustomerID;

                                        BuddyCheckList buddyCheck = new BuddyCheckList {
                                            CustomerID = customerID, OrderID = buddy.OrderID, OrderSubscriberID = buddy.OrderSubscriberID, IsProcessed = buddy.IsProcessed, MobileNumber = buddy.MobileNumber
                                        };

                                        BuddyCheckList afterProcessing = await buddyHelper.ProcessBuddy(buddyCheck);

                                        buddy.IsProcessed = afterProcessing.IsProcessed;
                                    }
                                }

                                List <PendingBuddy> unProcessedBuddies = buddyListToProcess.Where(b => b.IsProcessed == false).ToList();

                                if (unProcessedBuddies != null && unProcessedBuddies.Count > 0)
                                {
                                    List <PendingBuddy> processedBuddies = buddyListToProcess.Where(b => b.IsProcessed == true).ToList();

                                    foreach (PendingBuddy upBuddy in processedBuddies)
                                    {
                                        DatabaseResponse upBuddyCreateResponse = await buddyDataAccess.UpdatePendingBuddyList(_connectionString, upBuddy);
                                    }

                                    DatabaseResponse unlockResponse = await buddyDataAccess.UnLockPendingBuddy(unProcessedBuddies[0].OrderID, _connectionString);
                                }
                                else
                                {
                                    List <PendingBuddy> processedBuddies = buddyListToProcess.Where(b => b.IsProcessed == true).ToList();

                                    foreach (PendingBuddy upBuddy in processedBuddies)
                                    {
                                        DatabaseResponse upBuddyCreateResponse = await buddyDataAccess.UpdatePendingBuddyList(_connectionString, upBuddy);
                                    }

                                    DatabaseResponse removeProcessedResponse = await buddyDataAccess.RemoveProcessedBuddyList(_connectionString, buddyListToProcess[0].OrderID);

                                    DatabaseResponse customerIDResponse = await buddyDataAccess.GetCustomerIdFromOrderId(buddyListToProcess[0].OrderID, _connectionString);

                                    try
                                    {
                                        string emailStatus = await buddyHelper.SendEmailNotification(((OrderCust)customerIDResponse.Results).CustomerID, buddyListToProcess[0].OrderID, Configuration);

                                        LogInfo.Information("Email Send Status : " + emailStatus);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                                    }

                                    try
                                    {
                                        int processed = await buddyHelper.ProcessOrderQueueMessage(buddyListToProcess[0].OrderID);

                                        LogInfo.Information("MQ Send Status : " + processed.ToString());
                                    }
                                    catch (Exception ex)
                                    {
                                        LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                                    }
                                }
                            }
                        }
                    }
                }

                Console.WriteLine("End timer action: " + DateTime.Now);

                LogInfo.Information("End timer action: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> UpdateContentStatus(MoEContentStatus contentUpdate)
        {
            try
            {
                MoECheckDataAccess moeCheckDataAccess = new MoECheckDataAccess(_configuration, _converter);

                DatabaseResponse response = await moeCheckDataAccess.UpdateContentStatus(contentUpdate);

                if (response.ResponseCode == (int)DbReturnValue.Published)
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = true,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.Published),
                        ReturnedObject = response.Results
                    }));
                }
                else if (response.ResponseCode == (int)DbReturnValue.Rejected)
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.Rejected));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = true,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.Rejected),
                        ReturnedObject = response.Results
                    }));
                }
                else if (response.ResponseCode == (int)DbReturnValue.ReviewedByOtherUsers)
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.ReviewedByOtherUsers));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.ReviewedByOtherUsers),
                        ReturnedObject = response.Results
                    }));
                }
                else
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.ActionAlreadyTaken),
                        ReturnedObject = response.Results
                    }));
                }
            }
            catch (Exception ex)
            {
                Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    StatusCode = ((int)ResponseStatus.ServerError).ToString(),
                    IsDomainValidationErrors = false
                }));
            }
        }
Exemplo n.º 4
0
 private void ValidateHeaders(DatabaseResponse cosmosDatabaseResponse)
 {
     // Test emulator is regression and commented out to unblock
     // Assert.IsNotNull(cosmosDatabaseResponse.MaxResourceQuota);
     // Assert.IsNotNull(cosmosDatabaseResponse.CurrentResourceQuotaUsage);
 }
Exemplo n.º 5
0
        public async Task <DatabaseResponse> AuthenticateToken(string token)
        {
            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@Token", SqlDbType.NVarChar)
                };
                parameters[0].Value = token;

                _DataHelper = new DataAccessHelper("Customers_GetAccessTokenDetails", parameters, _configuration);

                DataTable dt = new DataTable();

                int result = await _DataHelper.RunAsync(dt); // 100 /105

                DatabaseResponse response = new DatabaseResponse();

                if (result == 105)
                {
                    AccessToken tokenResponse = new AccessToken();

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        tokenResponse = (from model in dt.AsEnumerable()
                                         select new AccessToken()
                        {
                            CustomerID = model.Field <int>("CustomerID"),
                            AdminUserID = model.Field <int>("AdminUserID"),
                            Token = model.Field <string>("Token")
                        }).FirstOrDefault();
                    }

                    response = new DatabaseResponse {
                        ResponseCode = result, Results = tokenResponse
                    };
                }
                else if (result == 113)
                {
                    //generate new token for the customer
                    var tokenHandler = new JwtSecurityTokenHandler();

                    var key = Encoding.ASCII.GetBytes("stratagile grid customer signin jwt hashing secret");

                    DatabaseResponse configResponse = ConfigHelper.GetValueByKey(ConfigKeys.CustomerTokenExpiryInDays.ToString(), _configuration);

                    int expiry = 0;

                    if (configResponse.ResponseCode == (int)DbReturnValue.RecordExists)
                    {
                        expiry = int.Parse(configResponse.Results.ToString());
                    }

                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject = new ClaimsIdentity(new Claim[]
                        {
                            new Claim(ClaimTypes.Name, dt.Rows[0][0].ToString().Trim())
                        }),
                        Expires            = DateTime.Now.AddDays(expiry), //  need to check with business needs
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                    };

                    var newtoken = tokenHandler.CreateToken(tokenDescriptor);

                    var tokenString = tokenHandler.WriteToken(newtoken);

                    //log the loken agains customer

                    SqlParameter[] tokenparameters =
                    {
                        new SqlParameter("@AccessToken", SqlDbType.NVarChar),
                        new SqlParameter("@Token",       SqlDbType.NVarChar)
                    };
                    tokenparameters[0].Value = token;
                    tokenparameters[1].Value = tokenString;

                    _DataHelper = new DataAccessHelper("Customers_GetAccessNewTokenDetails", tokenparameters, _configuration);

                    dt = new DataTable();

                    result = await _DataHelper.RunAsync(dt); // 100 /105

                    AccessToken tokenResponse = new AccessToken();

                    if (result == 105)
                    {
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            tokenResponse = (from model in dt.AsEnumerable()
                                             select new AccessToken()
                            {
                                CustomerID = model.Field <int>("CustomerID"),
                                AdminUserID = model.Field <int>("AdminUserID"),
                                Token = model.Field <string>("Token")
                            }).FirstOrDefault();
                        }

                        response = new DatabaseResponse {
                            ResponseCode = result, Results = tokenResponse
                        };
                    }
                    else
                    {
                        response = new DatabaseResponse {
                            ResponseCode = result
                        };
                    }
                }
                else
                {
                    response = new DatabaseResponse {
                        ResponseCode = result
                    };
                }

                return(response);
            }

            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                throw (ex);
            }
            finally
            {
                _DataHelper.Dispose();
            }
        }
Exemplo n.º 6
0
 public static async Task InitializeDatabase(CosmosClient cosmosClient, string databaseName)
 {
     DatabaseResponse database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);
 }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Auto Mapper
            var mapperConfig = new MapperConfiguration(config =>
            {
                config.AddProfile <BorneProfile>();
                config.AddProfile <OperationRechargeProfile>();
                config.AddProfile <UsagerProfile>();
                config.AddProfile <IncidentProfile>();
                config.AddProfile <EntretienProfile>();
                config.AddProfile <IncidentMonthlyAverageProfile>();
                config.AddProfile <TopFiveElementsDefectueuxProfile>();
                config.AddProfile <AverageElementFunctionnementProfile>();
            });

            services.AddAutoMapper(typeof(Startup));

            // Configuration CosmosDB
            IConfigurationSection configurationSection = Configuration.GetSection("CosmosDB");
            string nomDB        = configurationSection.GetSection("nomDB").Value;
            string nomContainer = configurationSection.GetSection("nomContainer").Value;
            string compte       = configurationSection.GetSection("compte").Value;
            string cle          = configurationSection.GetSection("cle").Value;

            CosmosClientBuilder clientBuilder = new CosmosClientBuilder(compte, cle);
            CosmosClient        client        = clientBuilder
                                                .WithConnectionModeDirect()
                                                .Build();

            // Création effective de la BDD
            DatabaseResponse db = client.CreateDatabaseIfNotExistsAsync(nomDB).GetAwaiter().GetResult();

            // Création du container
            db.Database.CreateContainerIfNotExistsAsync(nomContainer, "/id").GetAwaiter().GetResult();

            // Création et enregistrement des services par injection de dépendances
            CosmosDBService <Borne> serviceBorne = new CosmosDBService <Borne>(client, nomDB, nomContainer);

            services.AddSingleton <ICosmosDBService <Borne> >(serviceBorne);

            CosmosDBService <OperationRecharge> serviceOperationRecharge = new CosmosDBService <OperationRecharge>(client, nomDB, nomContainer);

            services.AddSingleton <ICosmosDBService <OperationRecharge> >(serviceOperationRecharge);

            CosmosDBService <Usager> serviceUsager = new CosmosDBService <Usager>(client, nomDB, nomContainer);

            services.AddSingleton <ICosmosDBService <Usager> >(serviceUsager);

            CosmosDBService <Incident> serviceIncident = new CosmosDBService <Incident>(client, nomDB, nomContainer);

            services.AddSingleton <ICosmosDBService <Incident> >(serviceIncident);

            CosmosDBService <Entretien> serviceEntretien = new CosmosDBService <Entretien>(client, nomDB, nomContainer);

            services.AddSingleton <ICosmosDBService <Entretien> >(serviceEntretien);

            SpecificsCosmosService <StatElementDefectueux> serviceTopFiveElementsDefectives = new SpecificsCosmosService <StatElementDefectueux>(client, nomDB, nomContainer);

            services.AddSingleton(serviceTopFiveElementsDefectives);

            SpecificsCosmosService <ChangementElements> serviceChangementElements = new SpecificsCosmosService <ChangementElements>(client, nomDB, nomContainer);

            services.AddSingleton(serviceChangementElements);

            SpecificsCosmosService <NombreBorne> serviceNbBornes = new SpecificsCosmosService <NombreBorne>(client, nomDB, nomContainer);

            services.AddSingleton(serviceNbBornes);

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "E-Bis Maintenance API", Version = "v0.0.1"
                });
            });

            // Décommenter pour garnir la bdd
            ServiceDonneesBase.GenererDonneesBase(client, nomDB, nomContainer);
            //ServiceDonneesBaseIncident.GenererDonneesBase(client, nomDB, nomContainer);
        }
Exemplo n.º 8
0
 private async Task DeleteDatabaseAsync(Database database)
 {
     System.Console.WriteLine("Delete database..");
     DatabaseResponse databaseResourceResponse = await database.DeleteAsync();
 }
Exemplo n.º 9
0
        public async Task <DatabaseResponse> GetOrderMessageQueueBody(int orderId, string connectionString)
        {
            DatabaseResponse response = new DatabaseResponse();

            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@OrderID", SqlDbType.Int)
                };

                parameters[0].Value = orderId;

                _DataHelper = new DataAccessHelper("Orders_GetMessageQueueBody", parameters, connectionString);

                DataSet ds = new DataSet();

                int result = await _DataHelper.RunAsync(ds); // 105 /102

                if (result == 105)
                {
                    OrderQM order = new OrderQM();

                    if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        order = (from model in ds.Tables[0].AsEnumerable()
                                 select new OrderQM()
                        {
                            accountID = model.Field <int>("accountID"),
                            customerID = model.Field <int>("customerID"),
                            orderID = model.Field <int>("orderID"),
                            orderNumber = model.Field <string>("orderNumber"),
                            orderDate = model.Field <DateTime>("orderDate"),
                            billingUnit = model.Field <string>("billingUnit"),
                            billingFloor = model.Field <string>("billingFloor"),
                            billingBuildingNumber = model.Field <string>("billingBuildingNumber"),
                            billingBuildingName = model.Field <string>("billingBuildingName"),
                            billingStreetName = model.Field <string>("billingStreetName"),
                            billingPostCode = model.Field <string>("billingPostCode"),
                            billingContactNumber = model.Field <string>("billingContactNumber"),
                            orderReferralCode = model.Field <string>("orderReferralCode"),
                            title = model.Field <string>("title"),
                            name = model.Field <string>("name"),
                            email = model.Field <string>("email"),
                            nationality = model.Field <string>("nationality"),
                            idType = model.Field <string>("idType"),
                            idNumber = model.Field <string>("idNumber"),
                            isSameAsBilling = model.Field <int?>("isSameAsBilling"),
                            shippingUnit = model.Field <string>("shippingUnit"),
                            shippingFloor = model.Field <string>("shippingFloor"),
                            shippingBuildingNumber = model.Field <string>("shippingBuildingNumber"),
                            shippingBuildingName = model.Field <string>("shippingBuildingName"),
                            shippingStreetName = model.Field <string>("shippingStreetName"),
                            shippingPostCode = model.Field <string>("shippingPostCode"),
                            shippingContactNumber = model.Field <string>("shippingContactNumber"),
                            alternateRecipientContact = model.Field <string>("alternateRecipientContact"),
                            alternateRecipientName = model.Field <string>("alternateRecipientName"),
                            alternateRecipientEmail = model.Field <string>("alternateRecipientEmail"),
                            portalSlotID = model.Field <string>("portalSlotID"),
                            slotDate = model.Field <DateTime?>("slotDate"),
                            slotFromTime = model.Field <TimeSpan?>("slotFromTime"),
                            slotToTime = model.Field <TimeSpan?>("slotToTime"),
                            scheduledDate = model.Field <DateTime?>("scheduledDate"),
                            submissionDate = model.Field <DateTime>("submissionDate"),
                            serviceFee = model.Field <double?>("serviceFee"),
                            amountPaid = model.Field <double?>("amountPaid"),
                            paymentMode = model.Field <string>("paymentMode"),
                            MPGSOrderID = model.Field <string>("MPGSOrderID"),
                            MaskedCardNumber = model.Field <string>("MaskedCardNumber"),
                            Token = model.Field <string>("Token"),
                            CardType = model.Field <string>("CardType"),
                            CardHolderName = model.Field <string>("CardHolderName"),
                            ExpiryMonth = model.Field <int?>("ExpiryMonth"),
                            ExpiryYear = model.Field <int?>("ExpiryYear"),
                            CardFundMethod = model.Field <string>("CardFundMethod"),
                            CardBrand = model.Field <string>("CardBrand"),
                            CardIssuer = model.Field <string>("CardIssuer"),
                            DateofBirth = model.Field <DateTime?>("DateofBirth"),
                            ReferralCode = model.Field <string>("ReferralCode"),
                            ProcessedOn = model.Field <DateTime?>("ProcessedOn"),
                            InvoiceNumber = model.Field <string>("InvoiceNumber"),
                            InvoiceUrl = model.Field <string>("InvoiceUrl"),
                            CreatedOn = model.Field <DateTime>("CreatedOn")
                        }).FirstOrDefault();

                        List <OrderSubscriber> Subscribers = new List <OrderSubscriber>();

                        if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
                        {
                            List <OrderSubscriptionQM> Bundles = new List <OrderSubscriptionQM>();

                            if (ds.Tables[2] != null && ds.Tables[2].Rows.Count > 0)
                            {
                                Bundles = (from model in ds.Tables[2].AsEnumerable()
                                           select new OrderSubscriptionQM()
                                {
                                    SubscriberID = model.Field <int>("SubscriberID"),
                                    bundleID = model.Field <int>("bundleID"),
                                    bssPlanCode = model.Field <string>("bssPlanCode"),
                                    bssPlanName = model.Field <string>("bssPlanName"),
                                    planType = model.Field <int>("planType"),
                                    planMarketingName = model.Field <string>("planMarketingName"),
                                    portalDescription = model.Field <string>("portalDescription"),
                                    totalData = model.Field <double?>("totalData"),
                                    totalSMS = model.Field <double?>("totalSMS"),
                                    totalVoice = model.Field <double?>("totalVoice"),
                                    applicableSubscriptionFee = model.Field <double?>("applicableSubscriptionFee")
                                }).ToList();
                            }


                            Subscribers = (from model in ds.Tables[1].AsEnumerable()
                                           select new OrderSubscriber()
                            {
                                OrderID = model.Field <int>("OrderID"),
                                subscriberID = model.Field <int>("subscriberID"),
                                mobileNumber = model.Field <string>("mobileNumber"),
                                displayName = model.Field <string>("displayName"),
                                isPrimaryNumber = model.Field <int>("isPrimaryNumber"),
                                premiumType = model.Field <int?>("premiumType"),
                                isPorted = model.Field <int?>("isPorted"),
                                isOwnNumber = model.Field <int?>("isOwnNumber"),
                                donorProvider = model.Field <string>("donorProvider"),
                                DepositFee = model.Field <double?>("DepositFee"),
                                IsBuddyLine = model.Field <int?>("IsBuddyLine"),
                                LinkedSubscriberID = model.Field <int?>("LinkedSubscriberID"),
                                RefOrderSubscriberID = model.Field <int?>("RefOrderSubscriberID"),
                                portedNumberTransferForm = model.Field <string>("portedNumberTransferForm"),
                                portedNumberOwnedBy = model.Field <string>("portedNumberOwnedBy"),
                                portedNumberOwnerRegistrationID = model.Field <string>("portedNumberOwnerRegistrationID"),
                                Bundles = Bundles != null ? Bundles.Where(b => b.SubscriberID == model.Field <int>("subscriberID")).ToList() : null
                            }).ToList();

                            order.Subscribers = Subscribers;
                        }



                        List <OrderServiceCharge> serviceCharges = new List <OrderServiceCharge>();

                        if (ds.Tables[3] != null && ds.Tables[3].Rows.Count > 0)
                        {
                            serviceCharges = (from model in ds.Tables[3].AsEnumerable()
                                              select new OrderServiceCharge()
                            {
                                OrderID = model.Field <int>("OrderID"),
                                SubscriberID = model.Field <int>("SubscriberID"),
                                AdminServiceID = model.Field <int?>("AdminServiceID"),
                                portalServiceName = model.Field <string>("portalServiceName"),
                                serviceFee = model.Field <double?>("serviceFee"),
                                isRecurring = model.Field <int>("isRecurring"),
                                isGSTIncluded = model.Field <int>("isGSTIncluded"),
                            }).ToList();

                            order.Charges = serviceCharges;
                        }
                    }

                    response = new DatabaseResponse {
                        ResponseCode = result, Results = order
                    };
                }

                else
                {
                    response = new DatabaseResponse {
                        ResponseCode = result
                    };
                }

                return(response);
            }

            catch (Exception ex)
            {
                Log.Error("Critical exceptiion occured while getting MQ body");
                Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(response);
            }
            finally
            {
                _DataHelper.Dispose();
            }
        }
Exemplo n.º 10
0
        public async void ProcessPayment(WebhookNotificationModel notification)
        {
            try
            {
                string json = JsonConvert.SerializeObject(notification);

                LogInfo.Information($"Webhooks notification model {json}");

                WebhookDataAccess _webhookAccess = new WebhookDataAccess(_iconfiguration);

                DatabaseResponse webhookLogUpdatedatabaseResponse = _webhookAccess.UpdateMPGSWebhookNotification(notification);

                // epoch


                System.IO.File.WriteAllText($@"{GatewayApiConfig.WEBHOOKS_NOTIFICATION_FOLDER}/WebHookNotifications_{notification.Timestamp}.json", json);


                CheckOutResponseUpdate updateRequest = new CheckOutResponseUpdate {
                    MPGSOrderID = notification.Order.Id, Result = notification.Order.Status
                };

                OrderDataAccess _orderAccess = new OrderDataAccess(_iconfiguration);

                //update checkout details

                // DatabaseResponse updateCheckoutDetailsResponse = await _orderAccess.UpdateCheckOutResponse(updateRequest);

                // retrieve transaction details from MPGS

                DatabaseResponse configResponse = await _orderAccess.GetConfiguration(ConfiType.MPGS.ToString());

                PaymentHelper gatewayHelper = new PaymentHelper();

                GridMPGSConfig gatewayConfig = gatewayHelper.GetGridMPGSConfig((List <Dictionary <string, string> >)configResponse.Results);

                //Direct capture MID config

                DatabaseResponse configDirectResponse = await _orderAccess.GetConfiguration(ConfiType.MPGSDirect.ToString());

                GridMPGSDirectMIDConfig gatewayDirectConfig = gatewayHelper.GetGridMPGSDirectMerchant((List <Dictionary <string, string> >)configDirectResponse.Results);

                gatewayConfig = gatewayHelper.GetGridMPGSCombinedConfig(gatewayConfig, gatewayDirectConfig);

                // Direct capture MID config end

                TransactionRetrieveResponseOperation transactionResponse = new TransactionRetrieveResponseOperation();

                string receipt = gatewayHelper.RetrieveCheckOutTransaction(gatewayConfig, updateRequest);

                transactionResponse = gatewayHelper.GetPaymentTransaction(receipt);

                if (webhookLogUpdatedatabaseResponse != null && webhookLogUpdatedatabaseResponse.Results != null)
                {
                    DatabaseResponse paymentMethodResponse = await _orderAccess.GetPaymentMethodToken((int)webhookLogUpdatedatabaseResponse.Results);

                    PaymentMethod paymentMethod = new PaymentMethod();

                    paymentMethod = (PaymentMethod)paymentMethodResponse.Results;

                    transactionResponse.TrasactionResponse.CardType = paymentMethod.CardType;

                    transactionResponse.TrasactionResponse.CardHolderName = paymentMethod.CardHolderName;

                    transactionResponse.TrasactionResponse.Token = paymentMethod.Token;
                }

                DatabaseResponse paymentProcessingRespose = new DatabaseResponse();

                paymentProcessingRespose = await _orderAccess.UpdateCheckOutReceipt(transactionResponse.TrasactionResponse);

                DatabaseResponse updatePaymentResponse = await _orderAccess.UpdatePaymentResponse(updateRequest.MPGSOrderID, receipt);

                if (paymentProcessingRespose.ResponseCode == (int)DbReturnValue.TransactionSuccess)
                {
                    LogInfo.Information(EnumExtensions.GetDescription(DbReturnValue.TransactionSuccess));

                    QMHelper qMHelper = new QMHelper(_iconfiguration, _messageQueueDataAccess);

                    int processResult = await qMHelper.ProcessSuccessTransaction(updateRequest);

                    if (processResult == 1)
                    {
                        LogInfo.Information(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed));
                    }
                    else if (processResult == 2)
                    {
                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed));
                    }
                    else if (processResult == 3)
                    {
                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed) + ". " + EnumExtensions.GetDescription(CommonErrors.MQSent));
                    }

                    else if (processResult == 4)
                    {
                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed) + ". But while processing Buddy/MQ/EML/SMS " + EnumExtensions.GetDescription(CommonErrors.SourceTypeNotFound) + " for MPGSOrderID" + updateRequest.MPGSOrderID);
                    }

                    else if (processResult == 5)
                    {
                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed) + ". But while processing Buddy/MQ/EML/SMS " + EnumExtensions.GetDescription(CommonErrors.InvalidCheckoutType) + " for MPGSOrderID" + updateRequest.MPGSOrderID);
                    }

                    else
                    {
                        // entry for exceptions from QM Helper, but need to send payment success message to UI as payment already processed
                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.PaymentProcessed) + ". But while processing MQ/EML/SMS " + EnumExtensions.GetDescription(CommonErrors.SystemExceptionAfterPayment) + " for MPGSOrderID" + updateRequest.MPGSOrderID);
                    }
                }

                else
                {
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TransactionFailed));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
            }
        }
Exemplo n.º 11
0
        public async Task <int> HandleRollbackOnAdditionalBuddyProcessingFailure(int customerID, int orderID, List <AdditionalBuddy> additionalBuddies)
        {
            try
            {
                OrderDataAccess _orderAccess = new OrderDataAccess(_iconfiguration);

                BSSAPIHelper bsshelper = new BSSAPIHelper();

                DatabaseResponse configResponse = await _orderAccess.GetConfiguration(ConfiType.BSS.ToString());

                GridBSSConfi config = bsshelper.GetGridConfig((List <Dictionary <string, string> >)configResponse.Results);

                DatabaseResponse serviceCAF = await _orderAccess.GetBSSServiceCategoryAndFee(ServiceTypes.Free.ToString());

                //unblock all subscribers for the order

                foreach (AdditionalBuddy buddy in additionalBuddies)
                {
                    // unblock mainline subscriber - not ported
                    if (buddy.IsPorted == 0)
                    {
                        DatabaseResponse requestIdToUnblockSubscribers = await _orderAccess.GetBssApiRequestId(GridMicroservices.Order.ToString(), BSSApis.UpdateAssetStatus.ToString(), customerID, (int)BSSCalls.ExistingSession, buddy.MobileNumber);

                        BSSUpdateResponseObject bssUpdateAdditionalBuddyMainlineUnblockResponse = new BSSUpdateResponseObject();

                        try
                        {
                            bssUpdateAdditionalBuddyMainlineUnblockResponse = await bsshelper.UpdateAssetBlockNumber(config, (BSSAssetRequest)requestIdToUnblockSubscribers.Results, buddy.MobileNumber, true);

                            if (bsshelper.GetResponseCode(bssUpdateAdditionalBuddyMainlineUnblockResponse) != "0")
                            {
                                //failed to unblock subscriber number add it to buddy removal table

                                DatabaseResponse logUnblockFailedSubscriber = await _orderAccess.LogUnblockFailedMainline(orderID, buddy);

                                if (logUnblockFailedSubscriber.ResponseCode != (int)DbReturnValue.CreateSuccess)
                                {
                                    LogInfo.Warning("Unlocking failed subscriber loging to BuddyRemoval table failed for OrderID:" + orderID + ", MobileNumber:" + buddy.MobileNumber);
                                }
                            }
                        }
                        catch
                        {
                            //failed to unblock subscriber number add it to buddy removal table
                            DatabaseResponse logUnblockFailedSubscriber = await _orderAccess.LogUnblockFailedMainline(orderID, buddy);

                            if (logUnblockFailedSubscriber.ResponseCode != (int)DbReturnValue.CreateSuccess)
                            {
                                LogInfo.Warning("Unlocking failed subscriber loging to BuddyRemoval table failed for OrderID:" + orderID + ", MobileNumber:" + buddy.MobileNumber);
                            }
                        }
                    }
                }

                //remove additional buddy for the order from additional buddy table
                DatabaseResponse removeAdditionalBuddyRes = await _orderAccess.RemoveAdditionalBuddyOnRollBackOrder(orderID);

                //rollback order
                DatabaseResponse rollbackResponse = await _orderAccess.RollBackOrder(orderID, "Rollback while processing additional buddy line");

                return(1);
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                return(0);
            }
        }
Exemplo n.º 12
0
        public async Task <int> AddRemoveBuddyHandler(int orderID, int customerID)
        {
            try
            {
                OrderDataAccess _orderAccess = new OrderDataAccess(_iconfiguration);

                // call remove buddy handler here

                int isRemoved = await RemoveBuddyHandler(orderID, customerID);

                DatabaseResponse checkAdditionalBuddyResponse = await _orderAccess.CheckAdditionalBuddy(orderID);

                // check additional Buddy

                if (checkAdditionalBuddyResponse.ResponseCode == (int)DbReturnValue.RecordExists && checkAdditionalBuddyResponse.Results != null)
                {
                    List <AdditionalBuddy> additionalBuddies = (List <AdditionalBuddy>)checkAdditionalBuddyResponse.Results;

                    foreach (AdditionalBuddy buddy in additionalBuddies)
                    {
                        if (buddy.OrderAdditionalBuddyID > 0 && buddy.IsProcessed == 0)
                        {
                            BSSAPIHelper bsshelper = new BSSAPIHelper();

                            DatabaseResponse configResponse = await _orderAccess.GetConfiguration(ConfiType.BSS.ToString());

                            GridBSSConfi config = bsshelper.GetGridConfig((List <Dictionary <string, string> >)configResponse.Results);

                            DatabaseResponse serviceCAF = await _orderAccess.GetBSSServiceCategoryAndFee(ServiceTypes.Free.ToString());

                            DatabaseResponse requestIdToGetAdditionalBuddy = await _orderAccess.GetBssApiRequestId(GridMicroservices.Order.ToString(), BSSApis.GetAssets.ToString(), customerID, (int)BSSCalls.NewSession, "");

                            ResponseObject res = new ResponseObject();

                            BSSNumbers numbers = new BSSNumbers();
                            //get a free number for additional buddy
                            try
                            {
                                res = await bsshelper.GetAssetInventory(config, (((List <ServiceFees>)serviceCAF.Results)).FirstOrDefault().ServiceCode, (BSSAssetRequest)requestIdToGetAdditionalBuddy.Results);
                            }

                            catch (Exception ex)
                            {
                                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical) + EnumExtensions.GetDescription(CommonErrors.BSSConnectionFailed));
                                // need to unblock all subscribers for the order and roll back the order  and return
                                int buddyRollback = await HandleRollbackOnAdditionalBuddyProcessingFailure(customerID, orderID, additionalBuddies);

                                // rollback on bss failure
                                return(3);
                            }

                            if (res != null && res.Response != null && res.Response.asset_details != null && (int.Parse(res.Response.asset_details.total_record_count) > 0))
                            {
                                numbers.FreeNumbers = bsshelper.GetFreeNumbers(res);

                                //insert these number into database
                                string json = bsshelper.GetJsonString(numbers.FreeNumbers); // json insert

                                DatabaseResponse updateBssCallFeeNumbers = await _orderAccess.UpdateBSSCallNumbers(json, ((BSSAssetRequest)requestIdToGetAdditionalBuddy.Results).userid, ((BSSAssetRequest)requestIdToGetAdditionalBuddy.Results).BSSCallLogID);

                                DatabaseResponse requestIdToUpdateAdditionalBuddyRes = await _orderAccess.GetBssApiRequestId(GridMicroservices.Order.ToString(), BSSApis.UpdateAssetStatus.ToString(), customerID, (int)BSSCalls.ExistingSession, numbers.FreeNumbers[0].MobileNumber);

                                BSSUpdateResponseObject bssUpdateAdditionalBuddyResponse = new BSSUpdateResponseObject();
                                // block the number for additional buddy
                                try
                                {
                                    bssUpdateAdditionalBuddyResponse = await bsshelper.UpdateAssetBlockNumber(config, (BSSAssetRequest)requestIdToUpdateAdditionalBuddyRes.Results, numbers.FreeNumbers[0].MobileNumber, false);

                                    // create buddy subscriber with blocked number and the existing main line

                                    if (bsshelper.GetResponseCode(bssUpdateAdditionalBuddyResponse) == "0")
                                    {
                                        CreateBuddySubscriber additinalBuddySubscriberToCreate = new CreateBuddySubscriber {
                                            OrderID = orderID, MobileNumber = numbers.FreeNumbers[0].MobileNumber, MainLineMobileNumber = buddy.MobileNumber, UserId = ((BSSAssetRequest)requestIdToUpdateAdditionalBuddyRes.Results).userid
                                        };

                                        DatabaseResponse createAdditionalBuddySubscriberResponse = await _orderAccess.CreateBuddySubscriber(additinalBuddySubscriberToCreate);

                                        // update
                                        if (createAdditionalBuddySubscriberResponse.ResponseCode == (int)DbReturnValue.CreateSuccess)
                                        {
                                            DatabaseResponse updateBuddyProcessedResponse = await _orderAccess.UpdateAdditionalBuddyProcessing(buddy.OrderAdditionalBuddyID);
                                        }
                                    }
                                }

                                catch (Exception ex)
                                {
                                    LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical) + EnumExtensions.GetDescription(CommonErrors.BuddyRemovalFailed) + " for Order : " + orderID);
                                }
                            }
                            else
                            {     // rollback on no assets retunred
                                int buddyRollback = await HandleRollbackOnAdditionalBuddyProcessingFailure(customerID, orderID, additionalBuddies);

                                return(2);
                            }
                        }
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(0);
            }
        }
        public async Task <IActionResult> ProcessSnsNotifications([FromHeader(Name = "x-amz-sns-message-type")] string snsMessageType, [FromHeader(Name = "x-amz-sns-rawdelivery")] bool isRawDelivery, string id = "")
        {
            try
            {
                //LogInfo.Information("1 - ProcessSnsNotification started with {"+ snsMessageType + "} object");

                if (string.IsNullOrEmpty(snsMessageType))
                {
                    LogInfo.Information(SNSNotification.EmptySNSTypeHeader.ToString());

                    return(BadRequest());
                }

                //if (isRawDelivery)
                //{
                //    string msg = "message is raw"; // for testing pupose,
                //}

                SNSSubscription notification = new SNSSubscription();

                string requestBody = "";

                using (var reader = new StreamReader(Request.Body))
                {
                    requestBody = reader.ReadToEndAsync().Result;
                }
                //LogInfo.Information("2 - Now fetching Body with {" + requestBody + "} object");
                var requestMessage = Amazon.SimpleNotificationService.Util.Message.ParseMessage(requestBody);
                //LogInfo.Information("3 - Parsing messages with {" + requestMessage + "} object");
                if (!requestMessage.IsMessageSignatureValid())
                {
                    LogInfo.Information(SNSNotification.InvalidSignature.ToString());

                    return(BadRequest());
                }

                //temporary storage for testing
                string path = ConfigHelper.GetValueByKey("SNSNotificationPath", _iconfiguration).Results.ToString();
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                System.IO.File.WriteAllText(path + $@"/notifications_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json", requestBody);

                // end temp

                if (string.IsNullOrEmpty(snsMessageType))
                {
                    //LogInfo.Information("4 - snsMessageType is  {" + snsMessageType + "} object");
                    return(BadRequest());
                }

                if (snsMessageType == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_SUBSCRIPTION_CONFIRMATION && requestMessage.IsSubscriptionType)
                {
                    Subscriber subscriber = new Subscriber(_iconfiguration);

                    var client = subscriber.GetAmazonSimpleNotificationServiceClient();
                    //LogInfo.Information("5 - before snsMessageType is  {" + client + "} object");
                    Amazon.SimpleNotificationService.Model.ConfirmSubscriptionResponse confirmSubscriptionResponse = await client.ConfirmSubscriptionAsync(requestMessage.TopicArn, requestMessage.Token);

                    if (confirmSubscriptionResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        LogInfo.Information(SNSNotification.SubscriptionConfirmed.ToString());
                    }
                    //LogInfo.Information("5.1 - before snsMessageType is  {" + client + "} object");
                    return(Ok());
                }

                else if (snsMessageType == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_UNSUBSCRIPTION_CONFIRMATION && requestMessage.IsUnsubscriptionType)
                {
                    Subscriber subscriber = new Subscriber(_iconfiguration);

                    var client = subscriber.GetAmazonSimpleNotificationServiceClient();

                    Amazon.SimpleNotificationService.Model.UnsubscribeResponse confirmUnSubscriptionResponse = await client.UnsubscribeAsync(notification.TopicArn);

                    //LogInfo.Information("6 - before snsMessageType is  {" + snsMessageType + "} object");
                    return(Ok());
                }

                else if (snsMessageType == Amazon.SimpleNotificationService.Util.Message.MESSAGE_TYPE_NOTIFICATION && requestMessage.IsNotificationType)
                {
                    //LogInfo.Information("7 - before snsMessageType is  {" + snsMessageType + "} object");
                    ConfigDataAccess _configAccess = new ConfigDataAccess(_iconfiguration);

                    MiscHelper helper = new MiscHelper();

                    DatabaseResponse notificationConfigResponse = await _configAccess.GetConfiguration(ConfiType.Notification.ToString());

                    NotificationConfig snsConfig = helper.GetNotificationConfig((List <Dictionary <string, string> >)notificationConfigResponse.Results);

                    Subscriber subscriber = new Subscriber(_iconfiguration, snsConfig.SNSTopic, snsConfig.SQS);

                    var client = subscriber.GetAmazonSimpleNotificationServiceClient();

                    Action <object> notificationSqsProcessor = ProcessNotification;

                    await subscriber.ListenAsync(notificationSqsProcessor);

                    return(Ok());
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok());
            }
        }
Exemplo n.º 14
0
 protected virtual void OnSuccessfulDatabaseResponseContentMaterializer(HttpResponseMessage response, DatabaseResponse result) { }
Exemplo n.º 15
0
        public async Task <IActionResult> ValidatePostcode([FromHeader(Name = "Grid-Authorization-Token")] string token, [FromRoute] string postcode)
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        Message = EnumExtensions.GetDescription(CommonErrors.TokenEmpty)
                    }));
                }

                AuthHelper helper = new AuthHelper(_iconfiguration);

                DatabaseResponse tokenAuthResponse = await helper.AuthenticateCustomerToken(token);

                if (tokenAuthResponse.ResponseCode == (int)DbReturnValue.AuthSuccess)
                {
                    if (!((AuthTokenResponse)tokenAuthResponse.Results).IsExpired)
                    {
                        if (postcode.Length == 0)
                        {
                            LogInfo.Warning(StatusMessages.MissingRequiredFields);
                            return(Ok(new OperationResponse
                            {
                                HasSucceeded = false,
                                Message = StatusMessages.MissingRequiredFields,
                                IsDomainValidationErrors = true
                            }));
                        }

                        ValidationDataAccess _validateDataAccess = new ValidationDataAccess(_iconfiguration);

                        return(Ok(new ServerResponse
                        {
                            HasSucceeded = true,
                            Message = StatusMessages.SuccessMessage,
                            Result = await _validateDataAccess.ValidatePostcode(postcode)
                        }));
                    }

                    else
                    {
                        //Token expired

                        LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.ExpiredToken));

                        return(Ok(new OperationResponse
                        {
                            HasSucceeded = false,
                            Message = EnumExtensions.GetDescription(DbReturnValue.TokenExpired),
                            IsDomainValidationErrors = true
                        }));
                    }
                }
                else
                {
                    // token auth failure
                    LogInfo.Warning(EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = false
                    }));
                }
            }
            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    IsDomainValidationErrors = false
                }));
            }
        }
Exemplo n.º 16
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            await Console.Out.WriteLineAsync($"Start Time:\t{DateTime.Now.ToShortTimeString()}");

            using (CosmosClient client = new CosmosClient(_endpointUri, _primaryKey))
            {
                DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("EntertainmentDatabase");

                Database targetDatabase = databaseResponse.Database;
                await Console.Out.WriteLineAsync($"Database Id:\t{targetDatabase.Id}");

                IndexingPolicy indexingPolicy = new IndexingPolicy
                {
                    IndexingMode  = IndexingMode.Consistent,
                    Automatic     = true,
                    IncludedPaths =
                    {
                        new IncludedPath
                        {
                            Path = "/*"
                        }
                    }
                };

                var containerProperties = new ContainerProperties("CustomCollection", "/medium")
                {
                    IndexingPolicy = indexingPolicy
                };

                var containerResponse = await targetDatabase.CreateContainerIfNotExistsAsync(containerProperties, 10000);

                var customContainer = containerResponse.Container;
                await Console.Out.WriteLineAsync($"Custom Container Id:\t{customContainer.Id}");

                var foodInteractions = new Bogus.Faker <PurchaseFoodOrBeverage>()
                                       .RuleFor(i => i.Id, (fake) => Guid.NewGuid().ToString())
                                       .RuleFor(i => i.medium, (fake) => nameof(PurchaseFoodOrBeverage))
                                       .RuleFor(i => i.unitPrice, (fake) => Math.Round(fake.Random.Decimal(1.99m, 15.99m), 2))
                                       .RuleFor(i => i.dayOfWeek, (fake) => fake.PickRandom(new List <string> {
                    "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
                }))
                                       .RuleFor(i => i.quantity, (fake) => fake.Random.Number(1, 5))
                                       .RuleFor(i => i.totalPrice, (fake, user) => Math.Round(user.unitPrice * user.quantity, 2))
                                       .Generate(500);
                foreach (var interaction in foodInteractions)
                {
                    var itemResponse = await customContainer.CreateItemAsync(interaction);

                    var customItem = itemResponse.Resource;
                    await Console.Out.WriteLineAsync($"Item Id:\t{customItem.Id}");
                }

                var tvInteractions = new Bogus.Faker <WatchLiveTelevisionChannel>()
                                     .RuleFor(i => i.Id, (fake) => Guid.NewGuid().ToString())
                                     .RuleFor(i => i.medium, (fake) => nameof(WatchLiveTelevisionChannel))
                                     .RuleFor(i => i.minutesViewed, (fake) => fake.Random.Number(1, 45))
                                     .RuleFor(i => i.channelName, (fake) => fake.PickRandom(new List <string> {
                    "NEWS-6", "DRAMA-15", "ACTION-12", "DOCUMENTARY-4", "SPORTS-8"
                }))
                                     .RuleFor(i => i.dayOfWeek, (fake) => fake.PickRandom(new List <string> {
                    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
                }))
                                     .Generate(500);
                foreach (var interaction in tvInteractions)
                {
                    var itemResponse = await customContainer.CreateItemAsync(interaction);

                    var customItem = itemResponse.Resource;
                    await Console.Out.WriteLineAsync($"Item Id:\t{customItem.Id}");
                }
            }
            await Console.Out.WriteLineAsync($"End Time:\t{DateTime.Now.ToShortTimeString()}");
        }
Exemplo n.º 17
0
        public IActionResult EmailValidation([FromHeader(Name = "Grid-General-Token")] string Token, [FromRoute] string emailid)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    LogInfo.Error(StatusMessages.DomainValidationError);
                    new OperationResponse
                    {
                        HasSucceeded             = false,
                        IsDomainValidationErrors = true,
                        Message = string.Join("; ", ModelState.Values
                                              .SelectMany(x => x.Errors)
                                              .Select(x => x.ErrorMessage))
                    };
                }
                TokenValidationHelper tokenValidationHelper = new TokenValidationHelper();
                if (!tokenValidationHelper.ValidateGenericToken(Token, _iconfiguration))
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.TokenAuthFailed),
                        IsDomainValidationErrors = true
                    }));
                }
                DatabaseResponse configResponseEmail = ConfigHelper.GetValue("EmailValidate", _iconfiguration);

                List <Dictionary <string, string> > _result = ((List <Dictionary <string, string> >)configResponseEmail.Results);
                string email1 = emailid;
                if (_result.Single(x => x["key"] == "AllowPlusSignEmailAddress")["value"] == "1")
                {
                    //Remove the Plus sign part from email before sending to neverbounce
                    Regex emailregx = new Regex("(\\+)(.*?)(\\@)"); //Replace the part after the plus "+) sign
                    email1 = emailregx.Replace(emailid, "$3");      //$3 to putback the @symbol
                }

                EmailValidationHelper emailhelper    = new EmailValidationHelper();
                EmailConfig           objEmailConfig = new EmailConfig();
                objEmailConfig.key         = _result.Single(x => x["key"] == "NeverbouceKey")["value"];
                objEmailConfig.Email       = email1;
                objEmailConfig.EmailAPIUrl = _result.Single(x => x["key"] == "Emailurl")["value"];

                string configResponse             = emailhelper.EmailValidation(objEmailConfig);
                EmailValidationResponse _response = new EmailValidationResponse();
                _response.Status = configResponse;
                if (configResponse.ToLower().Trim() != "invalid")
                {
                    _response.IsValid = true;
                    return(Ok(new ServerResponse
                    {
                        HasSucceeded = true,
                        Message = StatusMessages.ValidMessage,
                        Result = _response
                    }));
                }
                else
                {
                    //Invalid email
                    _response.IsValid = false;

                    LogInfo.Warning(EnumExtensions.GetDescription(CommonErrors.InvalidEmail));

                    return(Ok(new ServerResponse
                    {
                        HasSucceeded = true,
                        Message = StatusMessages.InvalidMessage,
                        Result = _response
                    }));
                }
            }
            catch (Exception ex)
            {
                EmailValidationResponse _response = new EmailValidationResponse();
                _response.Status  = "api Error";
                _response.IsValid = true;
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));
                return(Ok(new ServerResponse
                {
                    HasSucceeded = true,
                    Message = StatusMessages.ValidMessage,
                    Result = _response
                }));
            }
        }
 private void ValidateHeaders(DatabaseResponse cosmosDatabaseResponse)
 {
     Assert.IsNotNull(cosmosDatabaseResponse.MaxResourceQuota);
     Assert.IsNotNull(cosmosDatabaseResponse.CurrentResourceQuotaUsage);
 }
Exemplo n.º 19
0
 protected virtual void OnSuccessfulResponse(DatabaseResponse result, HttpResponseMessage response) { }
Exemplo n.º 20
0
        public async Task <DatabaseResponse> LogCustomerToken(int customerId, string token)
        {
            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@CustomerID", SqlDbType.Int),
                    new SqlParameter("@Token",      SqlDbType.NVarChar)
                };
                parameters[0].Value = customerId;
                parameters[1].Value = token;

                _DataHelper = new DataAccessHelper("Customer_CreateToken", parameters, _configuration);

                DataTable dt = new DataTable();

                int result = await _DataHelper.RunAsync(dt); // 100 /105

                DatabaseResponse response = new DatabaseResponse();

                if (result == 111)
                {
                    AuthTokenResponse tokenResponse = new AuthTokenResponse();

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        tokenResponse = (from model in dt.AsEnumerable()
                                         select new AuthTokenResponse()
                        {
                            CustomerID = model.Field <int>("CustomerID"),

                            CreatedOn = model.Field <DateTime>("CreatedOn")
                        }).FirstOrDefault();
                    }

                    response = new DatabaseResponse {
                        ResponseCode = result, Results = tokenResponse
                    };
                }

                else
                {
                    response = new DatabaseResponse {
                        ResponseCode = result
                    };
                }

                return(response);
            }

            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                throw (ex);
            }
            finally
            {
                _DataHelper.Dispose();
            }
        }
Exemplo n.º 21
0
        // Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
        // <Main>
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile("appSettings.json")
                                               .Build();

            string endpoint = configuration["EndPointUrl"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json");
            }

            string authKey = configuration["AuthorizationKey"];

            if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
            {
                throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json");
            }

            // Connecting to Emulator. Change if you want a live account
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey);

            // Declare a JSON schema to use with the schema validation handler
            var myContainerSchema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type': 'string'}
  },
  'required': ['name']
}");

            cosmosClientBuilder.AddCustomHandlers(
                new LoggingHandler(),
                new ConcurrencyHandler(),
                new ThrottlingHandler(),
                new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema))
                );

            CosmosClient client = cosmosClientBuilder.Build();

            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");

            Database database = databaseResponse.Database;

            ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");

            Container container = containerResponse.Container;

            Item item = new Item()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = "Test Item",
                Description = "Some random test item",
                Completed   = false
            };

            // Create
            await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id));

            item.Completed = true;

            // Replace
            await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id));

            // Querying
            FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions()
            {
                MaxConcurrency = 1
            });
            List <Item> results = new List <Item>();

            while (query.HasMoreResults)
            {
                FeedResponse <Item> response = await query.ReadNextAsync();

                results.AddRange(response.ToList());
            }

            // Read Item

            ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
            {
                IfMatchEtag = cosmosItemResponse.ETag
            };

            // Concurrency

            List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > >
            {
                UpdateItemForConcurrency(container, itemRequestOptions, item),
                UpdateItemForConcurrency(container, itemRequestOptions, item)
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (CosmosException ex)
            {
                // Verify that our custom handler caught the scenario
                Debug.Assert(999.Equals(ex.SubStatusCode));
            }

            // Delete
            await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            // Schema validation

            containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll2", "/id");

            container = containerResponse.Container;

            // Insert an item with invalid schema
            var writeSucceeded = true;

            try
            {
                await container.CreateItemAsync(new { id = "12345" });
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Insert an item with valid schema
            try
            {
                await container.CreateItemAsync(new { id = "12345", name = "Youri" });

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);

            // Update an item with invalid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Update an item with valid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345", name = "Vladimir" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);
        }
Exemplo n.º 22
0
 public static async Task InitializeContainer(DatabaseResponse database, string containerName, string partitionKeyPath)
 {
     await database.Database.CreateContainerIfNotExistsAsync(containerName, partitionKeyPath);
 }
Exemplo n.º 23
0
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = true,
                        StatusCode = ((int)ResponseStatus.BadRequest).ToString(),
                        Message = string.Join("; ", ModelState.Values
                                              .SelectMany(x => x.Errors)
                                              .Select(x => x.ErrorMessage))
                    }));
                }
                EducationDataAccess _educationAccess = new EducationDataAccess(_iconfiguration);

                DatabaseResponse response = await _educationAccess.DeleteEducation(id);

                if (response.ResponseCode == (int)DbReturnValue.DeleteSuccess)
                {
                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = true,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.DeleteSuccess),
                        ReturnedObject = response.Results
                    }));
                }
                else if (response.ResponseCode == (int)DbReturnValue.ActiveTryNotDelete)
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.ActiveTryNotDelete));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.ActiveTryNotDelete),
                        ReturnedObject = response.Results
                    }));
                }
                else
                {
                    Log.Error(EnumExtensions.GetDescription(DbReturnValue.NotExists));

                    return(Ok(new OperationResponse
                    {
                        HasSucceeded = false,
                        IsDomainValidationErrors = false,
                        Message = EnumExtensions.GetDescription(DbReturnValue.NotExists),
                        ReturnedObject = response.Results
                    }));
                }
            }
            catch (Exception ex)
            {
                Log.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                return(Ok(new OperationResponse
                {
                    HasSucceeded = false,
                    Message = StatusMessages.ServerError,
                    StatusCode = ((int)ResponseStatus.ServerError).ToString(),
                    IsDomainValidationErrors = false
                }));
            }
        }
Exemplo n.º 24
0
        public async Task ReadReplaceThroughputResponseTests()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            CosmosSerializerHelper mockJsonSerializer = new CosmosSerializerHelper(
                null,
                (x) => fromStreamCount++,
                (x) => toStreamCount++);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosClient client = TestCommon.CreateCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.WithCustomSerializer(mockJsonSerializer));

            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await client.CreateDatabaseAsync(databaseId, throughput, null);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database    cosmosDatabase         = createResponse;
            ThroughputResponse readThroughputResponse = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(readThroughputResponse);
            Assert.IsNotNull(readThroughputResponse.Resource);
            Assert.IsNotNull(readThroughputResponse.MinThroughput);
            Assert.IsNotNull(readThroughputResponse.Resource.Throughput);
            Assert.AreEqual(throughput, readThroughputResponse.Resource.Throughput.Value);

            // Implicit
            ThroughputProperties throughputProperties = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(throughputProperties);
            Assert.AreEqual(throughput, throughputProperties.Throughput);

            // Simple API
            int?readThroughput = await cosmosDatabase.ReadThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            // Database must have a container before it can be scaled
            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath, throughput : null);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            ThroughputResponse replaceThroughputResponse = await cosmosDatabase.ReplaceThroughputAsync(readThroughputResponse.Resource.Throughput.Value + 1000);

            Assert.IsNotNull(replaceThroughputResponse);
            Assert.IsNotNull(replaceThroughputResponse.Resource);
            Assert.AreEqual(readThroughputResponse.Resource.Throughput.Value + 1000, replaceThroughputResponse.Resource.Throughput.Value);

            await cosmosDatabase.DeleteAsync();

            Database databaseNoThroughput = await client.CreateDatabaseAsync(Guid.NewGuid().ToString(), throughput : null);

            try
            {
                ThroughputResponse throughputResponse = await databaseNoThroughput.ReadThroughputAsync(new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            try
            {
                ThroughputResponse throughputResponse = await databaseNoThroughput.ReplaceThroughputAsync(2000, new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            int?dbThroughput = await databaseNoThroughput.ReadThroughputAsync();

            Assert.IsNull(dbThroughput);

            Assert.AreEqual(0, toStreamCount, "Custom serializer to stream should not be used for offer operations");
            Assert.AreEqual(0, fromStreamCount, "Custom serializer from stream should not be used for offer operations");
            await databaseNoThroughput.DeleteAsync();
        }
Exemplo n.º 25
0
 protected virtual void OnSuccessfulResponse(DatabaseResponse result, HttpResponseMessage response)
 {
 }
Exemplo n.º 26
0
        public async Task DeleteDemoAsync()
        {
            DatabaseResponse dbResponse = await database.DeleteAsync();

            cosmosClient.Dispose();
        }
        public async Task <DatabaseResponse> CreateDatabase(CustomerEntity systemTenant)
        {
            DatabaseResponse response = await _cosmosDbManager.CreateDatabaseAsync(systemTenant);

            return(response);
        }