Exemple #1
0
        public JsonNetResult UpdateName(string firstName, string lastName)
        {
            var response = new DataAccessResponseType();
            var platformManagementServiceClient = new PlatformManagementService.PlatformManagementServiceClient();

            var user = AuthenticationCookieManager.GetAuthenticationCookie();

            try
            {
                platformManagementServiceClient.Open();

                response = platformManagementServiceClient.UpdatePlatformUserFullName(
                    user.Id, firstName,
                    lastName,
                    user.Id,
                    PlatformAdminSite.PlatformManagementService.RequesterType.Exempt, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(platformManagementServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(platformManagementServiceClient, exceptionMessage, currentMethodString);

                // Upate the response object
                response.isSuccess    = false;
                response.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                //response.ErrorMessages[0] = exceptionMessage;

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = response;

            return(jsonNetResult);
        }
        public JsonNetResult AddSalesLeadLabel(string label)
        {
            var response = new ApplicationLeadsService.DataAccessResponseType();
            var applicationLeadsServiceClient = new ApplicationLeadsService.ApplicationLeadsServiceClient();

            var authCookie     = AuthenticationCookieManager.GetAuthenticationCookie();
            var accountNameKey = authCookie.AccountNameKey;
            var userId         = authCookie.Id.ToString();

            try
            {
                applicationLeadsServiceClient.Open();
                response = applicationLeadsServiceClient.CreateLabel(accountNameKey, label,
                                                                     userId,
                                                                     ApplicationLeadsService.RequesterType.AccountUser, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(applicationLeadsServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(applicationLeadsServiceClient, exceptionMessage, currentMethodString);

                // Upate the response object
                response.isSuccess    = false;
                response.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                //response.ErrorMessages[0] = exceptionMessage;

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = response;

            return(jsonNetResult);
        }
Exemple #3
0
        public ActionResult Reset(string passwordClaimKey)
        {
            var email = string.Empty;
            var platformManagementServiceClient = new PlatformManagementService.PlatformManagementServiceClient();

            try
            {
                //Get the password claim email from CoreServices
                platformManagementServiceClient.Open();

                email = platformManagementServiceClient.GetLostPasswordClaim(passwordClaimKey, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(platformManagementServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(platformManagementServiceClient, exceptionMessage, currentMethodString);

                #endregion
            }

            if (String.IsNullOrEmpty(email))
            {
                return(Content("Password claim key does not exist."));
            }
            else
            {
                var resetPassword = new ResetPassword
                {
                    Email            = email,
                    PasswordClaimKey = passwordClaimKey
                };

                return(View(resetPassword));
            }
        }
        public JsonNetResult GetNotifications(string notificationStatus)
        {
            var userId = AuthenticationCookieManager.GetAuthenticationCookie().Id;
            var accountCommunicationServiceClient = new AccountCommunicationService.AccountCommunicationServiceClient();

            try
            {
                accountCommunicationServiceClient.Open();

                //Convert notification status to Enum
                NotificationStatus _convertedNotificationStatus = (NotificationStatus)Enum.Parse(typeof(NotificationStatus), notificationStatus);

                var userNotifications = accountCommunicationServiceClient.GetAccountUserNotifications(_convertedNotificationStatus, userId, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(accountCommunicationServiceClient);

                JsonNetResult jsonNetResult = new JsonNetResult();
                jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
                jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
                jsonNetResult.Data = userNotifications;

                return(jsonNetResult);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(accountCommunicationServiceClient, exceptionMessage, currentMethodString);

                #endregion

                JsonNetResult jsonNetErrorResult = new JsonNetResult();
                jsonNetErrorResult.Formatting = Newtonsoft.Json.Formatting.Indented;
                jsonNetErrorResult.Data       = WCFManager.UserFriendlyExceptionMessage;

                return(jsonNetErrorResult);
            }
        }
Exemple #5
0
        public String PerformanceTest_WCFCache_GetAccountsListNoncached()
        {
            var watch = Stopwatch.StartNew();

            var infrastructureTestsServiceClient = new InfrastructureTestsService.InfrastructureTestsServiceClient();

            infrastructureTestsServiceClient.Open();

            var result = infrastructureTestsServiceClient.PerformanceTest_InternalCaching_GetAccounts(false, Common.SharedClientKey);

            //Close the connection
            WCFManager.CloseConnection(infrastructureTestsServiceClient);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            return("Account List (WCF: No Cache):" + elapsedMs + "ms");
        }
        public AYWCFServPresenter(IMES mes)
        {
            this.mesInteface = mes;
            wcfManager       = new WCFManager();
            wcfManager.AYServ.delegateGetStep            += GetStep;
            wcfManager.AYServ.delegateUpdateStep         += UpdateStep;
            wcfManager.AYServ.delegateGetTrayBindingCell += GetTrayBindingCell;
            wcfManager.AYServ.delegateGetTrayCellLotNO   += GetTrayCellLotNO;
            wcfManager.AYServ.delegateUploadTrayCellInfo += UploadTrayCellInfo;

            //string cels = "{\"Cell1\":\"36AN\",\"Cell2\":\"36AN\",\"Cell3\":\"36AN\",\"Cell4\":\"36AN\"}";
            //string restr = "";
            //UploadTrayCellInfo("TP1234567", "CV", cels, ref restr);
            //string js="";
            //string restr="";
            //int step=0;
            ////GetTrayBindingCell("TP1234567", out js, ref restr);
            ////GetStep("TP1234567", out step, ref restr);
            //GetTrayCellLotNO("TP1234567", out js, ref restr);
        }
Exemple #7
0
        public String PerformanceTest_GetPlansWCF()
        {
            var watch = Stopwatch.StartNew();

            List <AccountPaymentPlanService.PaymentPlan> paymentPlans = null;

            var accountPaymentPlanServiceClient = new AccountPaymentPlanService.AccountPaymentPlanServiceClient();

            accountPaymentPlanServiceClient.Open();

            paymentPlans = accountPaymentPlanServiceClient.GetPaymentPlans(false, true).ToList();

            //Close the connection
            WCFManager.CloseConnection(accountPaymentPlanServiceClient);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            return("GetPlans (WCF): " + elapsedMs + "ms");
        }
        public JsonNetResult GetReport(int sinceHoursAgo)
        {
            #region Get data from WCF


            var PlatformManagementServiceClient = new PlatformManagementService.PlatformManagementServiceClient();
            var billingReport = new BillingReport();

            try
            {
                PlatformManagementServiceClient.Open();
                billingReport = PlatformManagementServiceClient.GetBillingReport(sinceHoursAgo, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(PlatformManagementServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(PlatformManagementServiceClient, exceptionMessage, currentMethodString);

                #endregion
            }

            #endregion

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = billingReport;

            return(jsonNetResult);
        }
        public ActionResult Index()
        {
            //Check if Platform exists
            var platformInitializationServiceClient = new PlatformInitializationService.PlatformInitializationServiceClient();

            platformInitializationServiceClient.Open();
            var isInitialized = platformInitializationServiceClient.IsPlatformInitialized();

            //Close the connection
            WCFManager.CloseConnection(platformInitializationServiceClient);

            CoreServices.Platform.Initialized = isInitialized;

            if (!isInitialized)
            {
                return(View(new RegisterPlatformUserModel()));
            }
            else
            {
                return(RedirectToAction("PlatformExists"));
            }
        }
        public ValidationResponse PostLastNameValidation(LastNameValidator nameValidator)
        {
            var response = new ValidationResponse();

            var accountRegistrationServiceClient = new AccountRegistrationService.AccountRegistrationServiceClient();

            try
            {
                accountRegistrationServiceClient.Open();
                var validationResponse = accountRegistrationServiceClient.ValidateLastName(nameValidator.LastName);

                //Close the connection
                WCFManager.CloseConnection(accountRegistrationServiceClient);


                response.valid   = validationResponse.isValid;
                response.message = validationResponse.validationMessage;
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(accountRegistrationServiceClient, exceptionMessage, currentMethodString);

                // Upate the response object
                response.valid   = false;
                response.message = WCFManager.UserFriendlyExceptionMessage;

                #endregion
            }

            return(response);
        }
        public JsonNetResult GetBalanceTransactionsForSource(string sourceId)
        {
            #region Get data from WCF

            var platformBillingServiceClient = new PlatformBillingService.PlatformBillingServiceClient();
            var sourceBalanceTransactions    = new SourceBalanceTransactions();

            try
            {
                platformBillingServiceClient.Open();
                sourceBalanceTransactions = platformBillingServiceClient.GetBalanceTransactionsForSource(sourceId, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(platformBillingServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(platformBillingServiceClient, exceptionMessage, currentMethodString);

                #endregion
            }

            #endregion

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = sourceBalanceTransactions;

            return(jsonNetResult);
        }
Exemple #12
0
        public ActionResult RefreshPlatformSettings()
        {
            #region Communicate with CoreServices and get updated subset of static settings for this client to work with

            var platformSettingsServiceClient = new PlatformSettingsService.PlatformSettingsServiceClient(); // <-- We only use PlatformSettingsServiceClient in EnviornmentSettings because it is ONLY used at application startup:

            try
            {
                platformSettingsServiceClient.Open();
                var platformSettingsResult = platformSettingsServiceClient.GetCorePlatformSettings(Common.SharedClientKey);

                CoreServices.PlatformSettings = platformSettingsResult;

                //Close the connections
                WCFManager.CloseConnection(platformSettingsServiceClient);

                return(Content("<b style='color:darkgreen'>Settings refreshed!</b>"));
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connections & manage the exceptions
                WCFManager.CloseConnection(platformSettingsServiceClient, exceptionMessage, currentMethodString);

                #endregion

                platformSettingsServiceClient.Close();

                return(Content("<b style='color:red'>" + e.ToString() + "</b>"));
            }

            #endregion
        }
        public static DataAccessResponseType UpdateAccountSettings_Internal(string accountNameKey, AccountSettingsDocumentModel accountSettingsDocumentModel)
        {
            var response = new AccountManagementService.DataAccessResponseType();

            var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();

            try
            {
                accountManagementServiceClient.Open();
                response = accountManagementServiceClient.UpdateAccountSettings(accountNameKey, accountSettingsDocumentModel,
                                                                                AuthenticationCookieManager.GetAuthenticationCookie().Id,
                                                                                AccountAdminSite.AccountManagementService.RequesterType.AccountUser, Common.SharedClientKey);

                //Close the connection
                WCFManager.CloseConnection(accountManagementServiceClient);
            }
            catch (Exception e)
            {
                #region Manage Exception

                string exceptionMessage = e.Message.ToString();

                var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                // Abort the connection & manage the exception
                WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);

                // Upate the response object
                response.isSuccess    = false;
                response.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                //response.ErrorMessages[0] = exceptionMessage;

                #endregion
            }

            return(response);
        }
        // GET: /Dashboard/
        public ActionResult Index()
        {
            //Check if Platform exists
            //TO DO: Move this to a static variable that checks on startup
            var platformInitializationServiceClient = new PlatformInitializationService.PlatformInitializationServiceClient();

            platformInitializationServiceClient.Open();
            var isInitialized = platformInitializationServiceClient.IsPlatformInitialized();

            //Close the connection
            WCFManager.CloseConnection(platformInitializationServiceClient);


            if (!isInitialized)
            {
                //If platform does not exist then rederect to Platform Initialization Controller
                return(RedirectToAction("Index", "Initialization"));
            }



            return(View(GetAccountsSnapshot()));
        }
Exemple #15
0
        public static List <PropertyModel> GetProperties(string accountNameKey, PropertyListType propertyListType, out ExecutionType executionTypeResult)
        {
            List <PropertyModel> properties = null;

            executionTypeResult = ExecutionType.redis_main;


            #region (Plan A) Get data from Redis Cache

            try
            {
                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashMainKey   = accountNameKey + ":properties";
                string hashMainField = propertyListType.ToString().ToLower();

                try
                {
                    var redisValue = cache.HashGet(hashMainKey, hashMainField);

                    if (redisValue.HasValue)
                    {
                        properties          = JsonConvert.DeserializeObject <List <PropertyModel> >(redisValue);
                        executionTypeResult = ExecutionType.redis_main;
                    }
                }
                catch
                {
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for Redis call
            }

            #endregion

            if (properties == null)
            {
                #region (Plan D) Get data from WCF

                var applicationPropertiesServiceClient = new ApplicationPropertiesService.ApplicationPropertiesServiceClient();

                try
                {
                    applicationPropertiesServiceClient.Open();

                    properties = applicationPropertiesServiceClient.GetProperties(accountNameKey, propertyListType, Common.SharedClientKey).ToList();

                    executionTypeResult = ExecutionType.wcf;

                    WCFManager.CloseConnection(applicationPropertiesServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(applicationPropertiesServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            return(properties);
        }
        public static AccountSettingsDocumentModel GetAccountSettings_Internal(string accountNameKey)
        {
            AccountSettingsDocumentModel settingsDocument = null;

            #region From Redis

            try
            {
                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashMainKey   = "account:settings";
                string hashMainField = accountNameKey;

                var redisValue = cache.HashGet(hashMainKey, hashMainField);

                if (redisValue.HasValue)
                {
                    settingsDocument = JsonConvert.DeserializeObject <AccountSettingsDocumentModel>(redisValue);
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for Redis call
            }

            #endregion

            if (settingsDocument == null)
            {
                #region From WCF

                var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();

                try
                {
                    accountManagementServiceClient.Open();

                    settingsDocument = accountManagementServiceClient.GetAccountSettings(accountNameKey, Common.SharedClientKey);
                    WCFManager.CloseConnection(accountManagementServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            #region Instantiate instances of classes that are null

            if (settingsDocument.ContactSettings == null)
            {
                settingsDocument.ContactSettings = new ContactSettingsModel();
            }
            if (settingsDocument.ContactSettings.ContactInfo == null)
            {
                settingsDocument.ContactSettings.ContactInfo = new ContactInfoModel();
            }
            if (settingsDocument.SalesSettings == null)
            {
                settingsDocument.SalesSettings = new SalesSettingsModel();
            }

            #endregion

            return(settingsDocument);
        }
        public JsonNetResult GetNextInvoice(string accountId)
        {
            var     user    = AuthenticationCookieManager.GetAuthenticationCookie();
            Invoice invoice = null;

            #region (Plan A) Get data from Redis Cache

            /*
             * try
             * {
             *  IDatabase cache = CoreServiceSettings.RedisConnectionMultiplexers.AccountManager_Multiplexer.GetDatabase();
             *
             *  string hashKey = "accountbyid:" + accountId.ToString().Replace("-", "");
             *  string hashField = "creditcard";
             *
             *  var redisValue = cache.HashGet(hashKey, hashField);
             *
             *  if (redisValue.HasValue)
             *  {
             *      accountCreditCardInfo = JsonConvert.DeserializeObject<AccountCreditCardInfo>(redisValue);
             *  }
             * }
             * catch (Exception e)
             * {
             *  var error = e.Message;
             *  //TODO: Log: error message for Redis call
             * }*/

            #endregion

            if (invoice == null)
            {
                #region (Plan B) Get data from WCF

                var accountBillingServiceClient = new AccountBillingService.AccountBillingServiceClient();

                try
                {
                    accountBillingServiceClient.Open();
                    invoice = accountBillingServiceClient.GetUpcomingInvoice(
                        accountId, Common.SharedClientKey);//,
                    //user.Id,
                    //PlatformAdminSite.AccountManagementService.RequesterType.PlatformUser);

                    //Close the connection
                    WCFManager.CloseConnection(accountBillingServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountBillingServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = invoice;

            return(jsonNetResult);
        }
        public JsonNetResult GetInvoiceHistory_ByDateRange_Last(int itemLimit, string accountId, string endingBefore, string startDate, string endDate)
        {
            var            user     = AuthenticationCookieManager.GetAuthenticationCookie();
            List <Invoice> invoices = null;

            #region (Plan A) Get data from Redis Cache

            /*
             * try
             * {
             *  IDatabase cache = CoreServiceSettings.RedisConnectionMultiplexers.AccountManager_Multiplexer.GetDatabase();
             *
             *  string hashKey = "accountbyid:" + accountId.ToString().Replace("-", "");
             *  string hashField = "creditcard";
             *
             *  var redisValue = cache.HashGet(hashKey, hashField);
             *
             *  if (redisValue.HasValue)
             *  {
             *      accountCreditCardInfo = JsonConvert.DeserializeObject<AccountCreditCardInfo>(redisValue);
             *  }
             * }
             * catch (Exception e)
             * {
             *  var error = e.Message;
             *  //TODO: Log: error message for Redis call
             * }*/

            #endregion

            if (invoices == null)
            {
                #region (Plan B) Get data from WCF

                var accountBillingServiceClient = new AccountBillingService.AccountBillingServiceClient();

                try
                {
                    accountBillingServiceClient.Open();
                    invoices = accountBillingServiceClient.GetInvoiceHistory_ByDateRange_Last(
                        itemLimit,
                        endingBefore,
                        Convert.ToDateTime(startDate).ToUniversalTime(),          //<-- We must convert to UTC to get accurrate results
                        Convert.ToDateTime(endDate).ToUniversalTime().AddDays(1), //<-- We must convert to UTC to get accurrate results (We add 1 day to end dates to also get resuts from this day and not just up to midnight the night before)
                        accountId, Common.SharedClientKey
                        ).ToList();                                               //,
                    //user.Id,
                    //PlatformAdminSite.AccountManagementService.RequesterType.PlatformUser).ToList();

                    //Close the connection
                    WCFManager.CloseConnection(accountBillingServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountBillingServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = invoices;

            return(jsonNetResult);
        }
        public JsonNetResult GetAvailableCredits(string accountId)
        {
            string creditsAvailableString = String.Empty;

            #region (Plan A) Get data from Redis Cache

            try
            {
                //First we attempt to get the user from the Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashKey   = "credits";
                string hashField = "credits:available:" + accountId;

                var redisValue = cache.HashGet(hashKey, hashField);

                //con.Close();

                if (redisValue.HasValue)
                {
                    creditsAvailableString = JsonConvert.DeserializeObject <String>(redisValue);
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
            }

            #endregion

            if (String.IsNullOrEmpty(creditsAvailableString))
            {
                #region (Plan B) Get data from WCF

                //If a failure occurs, or the redis cache is empty we get the user from the WCF service
                var accountCommerceServiceClient = new AccountCommerceService.AccountCommerceServiceClient();

                try
                {
                    accountCommerceServiceClient.Open();
                    creditsAvailableString = accountCommerceServiceClient.GetCredits(accountId.ToString(), Common.SharedClientKey).ToString();

                    //Close the connection
                    WCFManager.CloseConnection(accountCommerceServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountCommerceServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = creditsAvailableString;

            return(jsonNetResult);
        }
        public JsonNetResult Subsubcategory(string categoryNameKey, string subcategoryNameKey, string subsubcategoryNameKey, bool includeHidden = false, bool includeItems = false)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            SubsubcategoryModel       subsubcategory = null;
            SubsubcategoryDetailsJson subsubcategoryDetailsObjectJson = null;

            string localCacheKey = accountNameKey + ":subsubcategory:" + categoryNameKey + ":" + subcategoryNameKey + ":" + subsubcategoryNameKey + ":includeHidden:" + includeHidden + "includeProducts:" + includeItems;


            #region (Plan A) Get json from local cache

            try
            {
                subsubcategoryDetailsObjectJson = (SubsubcategoryDetailsJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (subsubcategoryDetailsObjectJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        subsubcategoryDetailsObjectJson = JsonConvert.DeserializeObject <SubsubcategoryDetailsJson>(redisApiValue);
                        executionType = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (subsubcategoryDetailsObjectJson == null)
                {
                    #region (Plan C) Get category data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":categories";
                        string hashMainField = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + ":public";

                        if (includeHidden == true)
                        {
                            hashMainField = categoryNameKey + "/" + subcategoryNameKey + "/" + subsubcategoryNameKey + ":private";
                        }

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                subsubcategory = JsonConvert.DeserializeObject <ApplicationCategorizationService.SubsubcategoryModel>(redisValue);
                                executionType  = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (subsubcategory == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationCategorizationServiceClient = new ApplicationCategorizationService.ApplicationCategorizationServiceClient();

                        try
                        {
                            applicationCategorizationServiceClient.Open();

                            subsubcategory = applicationCategorizationServiceClient.GetSubsubcategoryByNames(accountNameKey, categoryNameKey, subcategoryNameKey, subsubcategoryNameKey, includeHidden, Common.SharedClientKey);

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationCategorizationServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationCategorizationServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (subsubcategoryDetailsObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, subsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (subsubcategory != null)
                {
                    //Transform categories into JSON and cache BOTH locally AND into redis
                    subsubcategoryDetailsObjectJson = Transforms.Json.CategorizationTransforms.Subsubcategory(accountNameKey, subsubcategory, includeItems, includeHidden);
                    HttpRuntime.Cache.Insert(localCacheKey, subsubcategoryDetailsObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(subsubcategoryDetailsObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            if (subsubcategoryDetailsObjectJson == null)
            {
                //return empty
                return(new JsonNetResult());
            }

            //Add execution data
            stopWatch.Stop();
            subsubcategoryDetailsObjectJson.executionType = executionType.ToString();
            subsubcategoryDetailsObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = subsubcategoryDetailsObjectJson;

            return(jsonNetResult);
        }
Exemple #21
0
        public JsonNetResult Tags()
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            List <string> tags = null;
            TagsListJson  tagsListObjectJson = null;

            string localCacheKey = accountNameKey + ":tags";


            #region (Plan A) Get json from local cache

            try
            {
                tagsListObjectJson = (TagsListJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (tagsListObjectJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        tagsListObjectJson = JsonConvert.DeserializeObject <TagsListJson>(redisApiValue);
                        executionType      = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }


                #endregion

                if (tagsListObjectJson == null)
                {
                    #region (Plan C) Get data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":tags";
                        string hashMainField = "list";

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                tags          = JsonConvert.DeserializeObject <List <String> >(redisValue);
                                executionType = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (tags == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationTagsServiceClient = new ApplicationTagsService.ApplicationTagsServiceClient();

                        try
                        {
                            applicationTagsServiceClient.Open();

                            tags = applicationTagsServiceClient.GetTags(accountNameKey, Common.SharedClientKey).ToList();

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationTagsServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationTagsServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (tagsListObjectJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, tagsListObjectJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (tags != null)
                {
                    //Transform into JSON and cache BOTH locally AND into redis
                    tagsListObjectJson       = new TagsListJson();
                    tagsListObjectJson.tags  = tags;
                    tagsListObjectJson.count = tags.Count;

                    HttpRuntime.Cache.Insert(localCacheKey, tagsListObjectJson, null, DateTime.Now.AddMinutes(Common.TagsListCacheTimeInMinutes), TimeSpan.Zero);

                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(tagsListObjectJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            //Add execution data
            stopWatch.Stop();
            tagsListObjectJson.executionType = executionType.ToString();
            tagsListObjectJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = tagsListObjectJson;

            return(jsonNetResult);
        }
        public ActionResult Index(RegisterPlatformUserModel registerPlatformUser)
        {
            if (ModelState.IsValid)
            {
                var platformInitializationServiceClient = new PlatformInitializationService.PlatformInitializationServiceClient();
                platformInitializationServiceClient.Open();

                var response = platformInitializationServiceClient.ProvisionPlatform(registerPlatformUser.FirstName, registerPlatformUser.LastName, registerPlatformUser.Email, registerPlatformUser.Password);

                //Close the connection
                WCFManager.CloseConnection(platformInitializationServiceClient);

                //var response = Sahara.Platform.Core.Initialization.PlatformInitializationManager.ProvisionPlatform(user, registerPlatformUser.Password);

                if (response.isSuccess)
                {
                    // Update PlatformStatus to Exists = true
                    //PlatformStatus.Exists = true;

                    //Get Claims based identity for the user
                    //var identity = PlatformUserManager.GetUserClaimsIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //<-- Uses a cookie for the local web application

                    // Sign User In
                    //var currentUtc = new SystemClock().UtcNow;
                    //HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties() { IsPersistent = true, ExpiresUtc = currentUtc.Add(TimeSpan.FromHours(Sahara.Core.EnvironmentSettings.Platform.PlatformUsers.Authentication.WebApplicationCookiePersistence)) }, identity);

                    CoreServices.Platform.Initialized = true;

                    return(RedirectToAction("Success"));

                    /* Or sign in automatically and send to dashboard:
                     * //Attempt to log in
                     * var login = new Login();
                     * login.Email = registerPlatformUser.Email;
                     * login.Password = registerPlatformUser.Password;
                     *
                     * var platformAuthenticationServiceClient = new PlatformAuthenticationService.PlatformAuthenticationServiceClient();
                     * platformAuthenticationServiceClient.Open();
                     * var authResponse = platformAuthenticationServiceClient.Authenticate(login.Email, login.Password);
                     * platformAuthenticationServiceClient.Close();
                     *
                     *
                     * if (authResponse.isSuccess)
                     * {
                     *  // Sign User In
                     *
                     *  var currentUtc = new SystemClock().UtcNow;
                     *  HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                     *  {
                     *      IsPersistent = login.RememberMe,
                     *      ExpiresUtc = currentUtc.Add(TimeSpan.FromHours(6))
                     *  },
                     *      authResponse.ClaimsIdentity);
                     *
                     *  //After user is authenticated send them to the home page:
                     *  return RedirectToAction("Index", "Home");
                     *
                     * }
                     * else
                     * {
                     *  return RedirectToAction("Error", new { message = "Authentication error." });
                     * }*/
                }
                else
                {
                    //return RedirectToAction("InitializationError");
                    return(RedirectToAction("Error", new { message = "Iniialization error." }));
                }
            }
            else
            {
                return(View(registerPlatformUser));
            }
        }
        public JsonNetResult GetPlan(string planName)
        {
            AccountPaymentPlanService.PaymentPlan paymentPlan = null;

            #region (Plan A) Get data from Redis Cache

            try
            {
                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashKey   = "paymentplans";
                string hashField = "plan:" + planName;

                var redisValue = cache.HashGet(hashKey, hashField);

                if (redisValue.HasValue)
                {
                    paymentPlan = JsonConvert.DeserializeObject <AccountPaymentPlanService.PaymentPlan>(redisValue);
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for Redis call
            }

            #endregion

            if (paymentPlan == null)
            {
                #region (Plan B) Get data from WCF

                var accountPaymentPlanServiceClient = new AccountPaymentPlanService.AccountPaymentPlanServiceClient();

                try
                {
                    accountPaymentPlanServiceClient.Open();
                    paymentPlan = accountPaymentPlanServiceClient.GetPaymentPlan(planName);

                    //Close the connection
                    WCFManager.CloseConnection(accountPaymentPlanServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountPaymentPlanServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = paymentPlan;

            return(jsonNetResult);
        }
        public ActionResult Index(string invitationCode)
        {
            //Get the subdomain (if exists) for the site
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(Content("No account specified."));
            }


            if (invitationCode == null)
            {
                return(Content("ERROR: No verification code present."));
            }
            else
            {
                try
                {
                    UserInvitation invitedUser = null;

                    var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();

                    try
                    {
                        accountManagementServiceClient.Open();
                        invitedUser = accountManagementServiceClient.GetAccountUserInvitation(accountNameKey, invitationCode, Common.SharedClientKey);

                        //Close the connection
                        WCFManager.CloseConnection(accountManagementServiceClient);
                    }
                    catch (Exception e)
                    {
                        #region Manage Exception

                        string exceptionMessage = e.Message.ToString();

                        var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                        string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                        // Abort the connection & manage the exception
                        WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);

                        return(Content(WCFManager.UserFriendlyExceptionMessage));

                        #endregion
                    }



                    if (invitedUser == null)
                    {
                        return(Content("Not a valid invitation key, or key has expired"));
                    }
                    else
                    {
                        var creatUser = new CreateUserFromInvitationModel();

                        creatUser.AccountNameKey = accountNameKey;
                        creatUser.InvitationCode = invitedUser.InvitationKey;
                        creatUser.Email          = invitedUser.Email;
                        creatUser.FirstName      = invitedUser.FirstName;
                        creatUser.LastName       = invitedUser.LastName;
                        creatUser.Role           = invitedUser.Role;
                        creatUser.Owner          = invitedUser.Owner;

                        return(View(creatUser));
                    }
                }
                catch (Exception e)
                {
                    return(Content("ERROR: " + e.Message));
                }
            }
        }
Exemple #25
0
        public static List <ImageFormatGroupModel> GetImageFormatsHelper(string accountNameKey, string imageFormatGroupTypeNameKey)
        {
            List <ImageFormatGroupModel> imageGroups = null;

            #region (Plan A) Get data from Redis Cache

            try
            {
                //First we attempt to get tags from the Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string hashKey   = accountNameKey + ":imageformats";
                string hashField = "grouptype:" + imageFormatGroupTypeNameKey + ":all";

                try
                {
                    var redisValue = cache.HashGet(hashKey, hashField);

                    if (redisValue.HasValue)
                    {
                        imageGroups = JsonConvert.DeserializeObject <List <ImageFormatGroupModel> >(redisValue);
                    }
                }
                catch
                {
                }
            }
            catch (Exception e)
            {
                var error = e.Message;
                //Log error message for Redis call
            }

            #endregion

            if (imageGroups == null)
            {
                #region (Plan B) Get data from WCF

                var applicationImageFormatsServiceClient = new ApplicationImageFormatsService.ApplicationImageFormatsServiceClient();

                try
                {
                    applicationImageFormatsServiceClient.Open();
                    imageGroups = applicationImageFormatsServiceClient.GetImageFormats(accountNameKey, imageFormatGroupTypeNameKey).ToList();

                    //Close the connection
                    WCFManager.CloseConnection(applicationImageFormatsServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(applicationImageFormatsServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                #endregion
            }

            return(imageGroups);
        }
Exemple #26
0
        public ActionResult Reset(ResetPassword resetPassword)
        {
            if (ModelState.IsValid)
            {
                //Confirm passwords:
                if (resetPassword.Password != resetPassword.PasswordConfirm)
                {
                    ModelState.AddModelError("CoreServiceError", "Password and confirmation do not match!");
                    return(View(resetPassword));
                }



                var claimResponse = new PlatformManagementService.DataAccessResponseType();
                var platformManagementServiceClient = new PlatformManagementService.PlatformManagementServiceClient();



                try
                {
                    //Attempt to send lost password claim
                    platformManagementServiceClient.Open();
                    claimResponse = platformManagementServiceClient.ResetLostPassword(resetPassword.PasswordClaimKey, resetPassword.Password, Common.SharedClientKey);

                    //Close the connection
                    WCFManager.CloseConnection(platformManagementServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(platformManagementServiceClient, exceptionMessage, currentMethodString);

                    // Upate the response object
                    claimResponse.isSuccess    = false;
                    claimResponse.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                    //claimresponse.ErrorMessages[0] = exceptionMessage;

                    #endregion
                }

                if (claimResponse.isSuccess)
                {
                    return(RedirectToAction("Success", "Password"));
                }
                else
                {
                    //ModelState.AddModelError("", "Invalid username or password.");

                    //foreach (string error in authResponse.ErrorMessages)
                    //{
                    ModelState.AddModelError("CoreServiceError", claimResponse.ErrorMessage);
                    //}

                    return(View(resetPassword));
                }
            }
            else
            {
                return(View(resetPassword));
            }
        }
        public JsonNetResult GetThemes()
        {
            List <ThemeModel> themes = null;

            #region From Redis

            IDatabase platformCache       = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();
            string    themesHashMainKey   = "themes";
            string    themesHashMainField = "list";

            try
            {
                var themesRedis = platformCache.HashGet(themesHashMainKey, themesHashMainField);

                if (themesRedis.HasValue)
                {
                    themes = JsonConvert.DeserializeObject <List <ThemeModel> >(themesRedis);
                }
            }
            catch
            {
            }

            #endregion

            #region From WCF

            if (themes == null)
            {
                var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();

                try
                {
                    accountManagementServiceClient.Open();

                    themes = accountManagementServiceClient.GetThemes(Common.SharedClientKey).ToList();

                    WCFManager.CloseConnection(accountManagementServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }
            }

            #endregion

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = themes;

            return(jsonNetResult);
        }
Exemple #28
0
        public ActionResult Index(Login login, string returnUrl)
        {
            //RememberMe default is true
            login.RememberMe = true;

            //Sign user out (if signed in as another user)
            HttpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            if (ModelState.IsValid)
            {
                var authResponse = new AuthenticationResponse {
                    isSuccess = false
                };

                //Attempt to log in
                var accountAuthenticationServiceClient = new AccountAuthenticationService.AccountAuthenticationServiceClient();

                try
                {
                    //Get the ip address and call origin
                    var ipAddress = Request.UserHostAddress;
                    var origin    = "Web";

                    accountAuthenticationServiceClient.Open();
                    authResponse = accountAuthenticationServiceClient.Authenticate(login.AccountName, login.Email, login.Password, ipAddress, origin, Common.SharedClientKey);

                    //Close the connection
                    WCFManager.CloseConnection(accountAuthenticationServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountAuthenticationServiceClient, exceptionMessage, currentMethodString);

                    // Upate the response object
                    authResponse.isSuccess    = false;
                    authResponse.ErrorMessage = WCFManager.UserFriendlyExceptionMessage;
                    //auth//response.ErrorMessages[0] = exceptionMessage;

                    #endregion
                }


                //ClaimsIdentity[] claimsIdentity = new ClaimsIdentity[0];
                //claimsIdentity[0] = authResponse.ClaimsIdentity;

                if (authResponse.isSuccess)
                {
                    // Sign User In
                    var currentUtc = new SystemClock().UtcNow;
                    HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                    {
                        IsPersistent = login.RememberMe,
                        ExpiresUtc   = currentUtc.Add(TimeSpan.FromHours(6))
                    },
                                                                       authResponse.ClaimsIdentity);

                    //Store the PlatformUser object as a cookie:
                    AuthenticationCookieManager.SaveAuthenticationCookie(authResponse.AccountUser);

                    //-------------------- Uknown Accounts (Removed)-------

                    /*
                     * string subdomain = Common.GetSubDomain(Request.Url);
                     * if (subdomain.ToLower() == "accounts" || subdomain.ToLower() == "account")
                     * {
                     *  //This is the generic login route....
                     *  //Since the user had to provide the account name, redirect to the new URL
                     *  return Redirect("https://" + authResponse.AccountUser.AccountNameKey + "." + CoreServices.PlatformSettings.Urls.AccountManagementDomain + "/inventory");
                     * }
                     * else */

                    if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        //After user is authenticated, send them to the page they were attempting to use,
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        //otherwise, send them to home:
                        return(RedirectToAction("Index", "Inventory"));
                    }
                }
                else
                {
                    //ModelState.AddModelError("", "Invalid username or password.");

                    //foreach (string error in authResponse.ErrorMessages)
                    //{
                    ModelState.AddModelError("CoreServiceError", authResponse.ErrorMessage);
                    //}


                    //Removed

                    /*
                     * string subdomain = Common.GetSubDomain(Request.Url);
                     * if (subdomain.ToLower() == "accounts" || subdomain.ToLower() == "account")
                     * {
                     *  //This is the generic login route, so we remove the account name and force the user to add it.
                     *  login.AccountName = null;
                     * }*/

                    return(View(login));
                }
            }
            else
            {
                return(View(login));
            }
        }
        public JsonNetResult GetCurrentUser()
        {
            //This is used often by the UI to refresh the user, wrap in a Try/Catch in case of intermitent failures:

            try
            {
                var userId = AuthenticationCookieManager.GetAuthenticationCookie().Id;

                if (userId == null)
                {
                    Response.Redirect("/Login");
                }

                AccountUser user = null;

                #region (Plan A) Get data from Redis Cache

                try
                {
                    //First we attempt to get the user from the Redis Cache

                    IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                    string hashKey   = "user:"******"-", "");
                    string hashField = "model";

                    var redisValue = cache.HashGet(hashKey, hashField);

                    //con.Close();

                    if (redisValue.HasValue)
                    {
                        user = JsonConvert.DeserializeObject <AccountUser>(redisValue);
                    }
                }
                catch (Exception e)
                {
                    var error = e.Message;
                }

                #endregion

                if (user == null)
                {
                    #region (Plan B) Get data from WCF

                    //If a failure occurs, or the redis cache is empty we get the user from the WCF service
                    var accountManagementServiceClient = new AccountManagementService.AccountManagementServiceClient();

                    try
                    {
                        accountManagementServiceClient.Open();
                        user = accountManagementServiceClient.GetAccountUser(userId, Common.SharedClientKey);

                        //Close the connection
                        WCFManager.CloseConnection(accountManagementServiceClient);
                    }
                    catch (Exception e)
                    {
                        #region Manage Exception

                        string exceptionMessage = e.Message.ToString();

                        var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                        string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                        // Abort the connection & manage the exception
                        WCFManager.CloseConnection(accountManagementServiceClient, exceptionMessage, currentMethodString);

                        #endregion
                    }

                    #endregion
                }

                //Update the local cookies:
                AuthenticationCookieManager.SaveAuthenticationCookie(user);

                JsonNetResult jsonNetResult = new JsonNetResult();
                jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
                jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
                jsonNetResult.Data = user;

                return(jsonNetResult);
            }
            catch
            {
                // Use cookies instead
                JsonNetResult jsonNetResult = new JsonNetResult();
                jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
                jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
                var accountUser = AuthenticationCookieManager.GetAuthenticationCookie();
                jsonNetResult.Data = accountUser;

                return(jsonNetResult);
            }
        }
        public JsonNetResult GetCreditsToDollarExchangeValue()
        {
            string creditsToDollarExchangeValueString = String.Empty;

            #region (Plan A) Get data from Local Cache (We cache the exchange rate locally for 8 hours to decrease Core Service requests)

            var exchangeRateCacheKey = "CreditsToDollarExchangeValue";
            var cacheMinutes         = 480;

            var localCacheValue = System.Web.HttpRuntime.Cache.Get(exchangeRateCacheKey);

            #endregion


            if (localCacheValue == null)
            {
                //local cache is empty, get rate from Core Services
                #region (Plan B) Get data from WCF

                //If a failure occurs, or the redis cache is empty we get the user from the WCF service
                var accountCommerceServiceClient = new AccountCommerceService.AccountCommerceServiceClient();

                try
                {
                    accountCommerceServiceClient.Open();
                    creditsToDollarExchangeValueString = accountCommerceServiceClient.GetDollarsToCreditsExchangeRate(1, Common.SharedClientKey).ToString();

                    //Close the connection
                    WCFManager.CloseConnection(accountCommerceServiceClient);
                }
                catch (Exception e)
                {
                    #region Manage Exception

                    string exceptionMessage = e.Message.ToString();

                    var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                    string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                    // Abort the connection & manage the exception
                    WCFManager.CloseConnection(accountCommerceServiceClient, exceptionMessage, currentMethodString);

                    #endregion
                }

                //Store data into local cache for 8 hours:
                System.Web.HttpRuntime.Cache.Insert(exchangeRateCacheKey, creditsToDollarExchangeValueString, null, DateTime.Now.AddMinutes(cacheMinutes), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);

                #endregion
            }
            else
            {
                //convert local cache object to return value
                creditsToDollarExchangeValueString = localCacheValue.ToString();
            }


            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = creditsToDollarExchangeValueString;

            return(jsonNetResult);
        }