Exemple #1
0
        private void LoadSettings()
        {
            PageSubheader.Visible  = true;
            ModuleNameLiteral.Text = ModuleName;
            YaHelp.Visible         = (ModuleName == "YandexMarket");

            if (IsPostBack)
            {
                return;
            }

            CurrencyListBox.Items.Clear();
            var currencies = CurrencyService.GetAllCurrencies();

            if (ModuleName == "YandexMarket")
            {
                currencies = currencies.Where(item => ExportFeedModuleYandex.AvailableCurrencies.Contains(item.Iso3)).ToList();
            }

            foreach (var item in currencies)
            {
                CurrencyListBox.Items.Add(new ListItem {
                    Text = item.Name, Value = item.Iso3
                });
            }

            LoadModuleSettings();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var curentCustomer = CustomerContext.CurrentCustomer;

            aLogin.Visible = aRegister.Visible = !curentCustomer.RegistredUser;
            aRegister.HRef = UrlService.GetAbsoluteLink("registration.aspx");
            aLogin.HRef = UrlService.GetAbsoluteLink("login.aspx");
            lbLogOut.Visible = aMyAccount.Visible = curentCustomer.RegistredUser;
            aMyAccount.HRef = UrlService.GetAbsoluteLink("myaccount.aspx");
            pnlAdmin.Visible = (curentCustomer.CustomerRole == Role.Administrator || curentCustomer.CustomerRole == Role.Moderator || TrialService.IsTrialEnabled);
            pnlAdmin.HRef = UrlService.GetAbsoluteLink("admin/default.aspx");

            aCreateTrial.Visible = Demo.IsDemoEnabled;

            pnlCurrency.Visible = SettingsCatalog.AllowToChangeCurrency;
            foreach (Currency row in CurrencyService.GetAllCurrencies(true))
            {
                ddlCurrency.Items.Add(new ListItem(row.Name, row.Iso3));
            }
            ddlCurrency.SelectedValue = CurrencyService.CurrentCurrency.Iso3;

            pnlCity.Visible = SettingsDesign.DisplayCityInTopPanel;

            int wishCount = ShoppingCartService.CurrentWishlist.Count;
            WishlistCount = string.Format("{0} {1}", wishCount == 0 ? "" : wishCount.ToString(CultureInfo.InvariantCulture),
                                          Strings.Numerals(wishCount, Resources.Resource.Client_MasterPage_WishList_Empty,
                                                           Resources.Resource.Client_MasterPage_WishList_1Product,
                                                           Resources.Resource.Client_MasterPage_WishList_2Products,
                                                           Resources.Resource.Client_MasterPage_WishList_5Products));

            pnlWishList.Visible = SettingsDesign.WishListVisibility && !pnlCity.Visible;

        }
Exemple #3
0
        public async Task <IActionResult> GetAllCurrencies()
        {
            // Reponse
            var response = await _currencyService.GetAllCurrencies();

            // Return
            return(Ok(response));
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            btnUpdateCurrencies.Visible = CurrencyService.GetAllCurrencies(true).Find(c => c.Iso3 == "RUB" && c.Value == 1) != null;

            if (grid.UpdatedRow != null && grid.UpdatedRow["CurrencyValue"].TryParseDecimal() > 0)
            {
                var id    = SQLDataHelper.GetInt(grid.UpdatedRow["ID"]);
                var upCur = CurrencyService.GetCurrency(id);
                upCur.Name         = grid.UpdatedRow["Name"];
                upCur.Symbol       = grid.UpdatedRow["Code"];
                upCur.Value        = grid.UpdatedRow["CurrencyValue"].TryParseFloat();
                upCur.Iso3         = grid.UpdatedRow["CurrencyISO3"];
                upCur.NumIso3      = grid.UpdatedRow["CurrencyNumIso3"].TryParseInt();
                upCur.IsCodeBefore = SQLDataHelper.GetBoolean(grid.UpdatedRow["IsCodeBefore"]);
                upCur.PriceFormat  = grid.UpdatedRow["PriceFormat"];
                CurrencyService.UpdateCurrency(upCur);
                CurrencyService.RefreshCurrency();
            }

            DataTable data = _paging.PageItems;

            while (data.Rows.Count < 1 && _paging.CurrentPageIndex > 1)
            {
                _paging.CurrentPageIndex--;
                data = _paging.PageItems;
            }

            var clmn = new DataColumn("IsSelected", typeof(bool))
            {
                DefaultValue = _inverseSelection
            };

            data.Columns.Add(clmn);
            if ((_selectionFilter != null) && (_selectionFilter.Values != null))
            {
                for (int i = 0; i <= data.Rows.Count - 1; i++)
                {
                    int intIndex = i;
                    if (Array.Exists(_selectionFilter.Values, c => c == data.Rows[intIndex]["ID"].ToString()))
                    {
                        data.Rows[i]["IsSelected"] = !_inverseSelection;
                    }
                }
            }

            if (data.Rows.Count < 1)
            {
                goToPage.Visible = false;
            }

            grid.DataSource = data;
            grid.DataBind();

            pageNumberer.PageCount = _paging.PageCount;
            lblFound.Text          = _paging.TotalRowsCount.ToString();
        }
        public ActionResult Index([Bind(Prefix = "id")] string username)
        {
            _dbContext = new ApplicationDbContext();
            //Update the User Profile Details
            UserAccountService userAccountService = new UserAccountService(_dbContext);

            UserProfileVM userProfileVM = null;

            if (!string.IsNullOrEmpty(username))
            {
                userProfileVM = userAccountService.GetUserProfile(username);
            }

            string currentUserId = "";

            if (User.Identity.IsAuthenticated)
            {
                currentUserId = User.Identity.GetUserId();
            }

            if (userProfileVM == null && User.Identity.IsAuthenticated)
            {
                userProfileVM = userAccountService.GetUserProfileById(currentUserId);
            }

            if (userProfileVM == null)
            {
                return(HttpNotFound());
            }

            //Check whether the User is seeing his/her own Profile
            //If it is his/her ownn profile, return Edit Profile Page.
            //else return the Public Profile View
            ViewBag.HasUserFollowed = false;
            if (currentUserId.Equals(userProfileVM.Id))
            {
                ViewBag.YearsOfBirth  = UtilityExtension.GetYearsList();
                ViewBag.LanguagesList = UtilityExtension.GetLanguagesList();

                CurrencyService currencyService = new CurrencyService(_dbContext);
                ViewBag.CurrencyList = currencyService.GetAllCurrencies();

                userProfileVM.ProfileImageData = userAccountService.GetUserProfileImageData(userProfileVM.Id);

                return(View("UpdateProfile", userProfileVM));
            }
            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    ViewBag.HasUserFollowed = userAccountService.GetUserFollower(currentUserId, userProfileVM.Id) != null;
                }
                return(View("PublicProfile", userProfileVM));
            }
        }
 private void LoadSettings()
 {
     PageSubheader.Visible  = true;
     ModuleNameLiteral.Text = ModuleName;
     if (IsPostBack)
     {
         return;
     }
     CurrencyListBox.Items.Clear();
     foreach (var item in CurrencyService.GetAllCurrencies())
     {
         CurrencyListBox.Items.Add(new ListItem {
             Text = item.Name, Value = item.Iso3
         });
     }
     LoadModuleSettings();
 }
        public ActionResult Step2()
        {
            ViewBag.DisableEmailTextbox   = true;
            ViewBag.ShowResendEmailButton = false;
            _dbContext = new ApplicationDbContext();

            //Get Current User's Profile
            string             currentUserId      = User.Identity.GetUserId();
            UserAccountService userAccountService = new UserAccountService(_dbContext);
            UserProfileVM      userProfileVM      = userAccountService.GetUserProfileById(currentUserId);

            if (userProfileVM == null)
            {
                return(HttpNotFound());
            }
            if (string.IsNullOrEmpty(userProfileVM.UrlUsername))
            {
                userProfileVM.UrlUsername = User.Identity.GetExternalProviderUsername();
            }

            if (string.IsNullOrEmpty(userProfileVM.Email) || userProfileVM.EmailConfirmed == false)
            {
                ViewBag.DisableEmailTextbox = false;
            }
            if (!string.IsNullOrEmpty(userProfileVM.Email))
            {
                ViewBag.ShowResendEmailButton = true;
            }

            ViewBag.YearsOfBirth  = UtilityExtension.GetYearsList();
            ViewBag.LanguagesList = UtilityExtension.GetLanguagesList();

            CurrencyService currencyService = new CurrencyService(_dbContext);

            ViewBag.CurrencyList = currencyService.GetAllCurrencies();


            return(View(userProfileVM));
        }
Exemple #8
0
        // POST /order/accept
        protected static void Accept(string json)
        {
            var yaOrder = JsonConvert.DeserializeObject <YaMarketOrderRequest>(json);

            if (yaOrder == null || yaOrder.order == null)
            {
                return;
            }

            Order order = null;

            try
            {
                var adminComment = "";

                adminComment = "Заказ номер: " + yaOrder.order.id + (yaOrder.order.fake ? "(тестовый)" : "") + "\r\n";

                if (yaOrder.order.paymentType.IsNotEmpty())
                {
                    adminComment += "Тип оплаты заказа: " +
                                    (yaOrder.order.paymentType == "PREPAID"
                                        ? "предоплата"
                                        : "постоплата при получении заказа") + "\r\n";
                }

                if (yaOrder.order.paymentMethod.IsNotEmpty())
                {
                    adminComment += "Способ оплаты заказа: ";
                    switch (yaOrder.order.paymentMethod)
                    {
                    case "YANDEX":
                        adminComment += "оплата при оформлении";
                        break;

                    case "SHOP_PREPAID":
                        adminComment += "предоплата напрямую магазину (только для Украины)";
                        break;

                    case "CASH_ON_DELIVERY":
                        adminComment += "наличный расчет при получении заказа";
                        break;

                    case "CARD_ON_DELIVERY":
                        adminComment += "оплата банковской картой при получении заказа";
                        break;
                    }
                }

                adminComment += "\r\n";

                var orderContact       = new OrderContact();
                var shippingCost       = 0f;
                var shippingMethodName = "";

                if (yaOrder.order.delivery != null)
                {
                    adminComment += string.Format("Доставка: {0}, стоимость доставки: {1}, даты: {2} до {3}\r\n",
                                                  yaOrder.order.delivery.serviceName, yaOrder.order.delivery.price ?? 0,
                                                  yaOrder.order.delivery.dates.fromDate, yaOrder.order.delivery.dates.toDate);

                    orderContact = new OrderContact
                    {
                        Address =
                            yaOrder.order.delivery.address.street + " " + yaOrder.order.delivery.address.house + " " +
                            yaOrder.order.delivery.address.subway + " " + yaOrder.order.delivery.address.block + " " +
                            yaOrder.order.delivery.address.floor,
                        City    = yaOrder.order.delivery.address.city,
                        Country = yaOrder.order.delivery.address.country,
                        Name    = string.Empty,
                        Zip     = yaOrder.order.delivery.address.postcode ?? string.Empty,
                        Zone    = string.Empty
                    };

                    if (yaOrder.order.delivery.price != null)
                    {
                        shippingCost = (float)yaOrder.order.delivery.price;
                    }

                    shippingMethodName = yaOrder.order.delivery.serviceName;
                }

                var orderItems = (from item in yaOrder.order.items
                                  let offer = OfferService.GetOffer(Convert.ToInt32(item.offerId))
                                              where offer != null
                                              let product = offer.Product
                                                            select new OrderItem()
                {
                    Name = product.Name,
                    Price = item.price,
                    Amount = item.count,
                    SupplyPrice = product.Offers[0].SupplyPrice,
                    ProductID = product.ProductId,
                    ArtNo = product.ArtNo,
                    IsCouponApplied = false,
                    Weight = product.Weight
                }).ToList();

                var orderCurrency = yaOrder.order.currency == "RUR"
                    ? (CurrencyService.GetAllCurrencies(true)
                       .FirstOrDefault(x => x.Iso3 == yaOrder.order.currency || x.Iso3 == "RUB") ??
                       CurrencyService.GetAllCurrencies(true).FirstOrDefault())
                    : (CurrencyService.GetAllCurrencies(true).FirstOrDefault(x => x.Iso3 == yaOrder.order.currency) ??
                       CurrencyService.GetAllCurrencies(true).FirstOrDefault());

                order = new Order()
                {
                    AdminOrderComment = adminComment,
                    CustomerComment   = yaOrder.order.notes,
                    OrderCustomer     = new OrderCustomer()
                    {
                        Email      = "*****@*****.**",
                        CustomerIP = "127.0.0.1"
                    },
                    OrderItems           = orderItems,
                    OrderCurrency        = orderCurrency,
                    ShippingContact      = orderContact,
                    BillingContact       = orderContact,
                    ShippingCost         = shippingCost,
                    ArchivedShippingName = shippingMethodName,
                    OrderStatusId        = OrderService.DefaultOrderStatus,
                    OrderDate            = DateTime.Now,
                    Number = OrderService.GenerateNumber(1),
                };

                order.OrderID = OrderService.AddOrder(order);
                order.Number  = OrderService.GenerateNumber(order.OrderID);
                OrderService.UpdateNumber(order.OrderID, order.Number);
                OrderService.ChangeOrderStatus(order.OrderID, OrderService.DefaultOrderStatus);


                if (order.OrderID != 0)
                {
                    YaMarketByuingService.AddOrder(new YaOrder()
                    {
                        MarketOrderId = yaOrder.order.id.TryParseInt(),
                        OrderId       = order.OrderID,
                        Status        = string.Format("[{0}] Создан заказ {1}", DateTime.Now.ToString("g"), order.OrderID)
                    });

                    try
                    {
                        var orderTable = OrderService.GenerateHtmlOrderTable(order.OrderItems, order.OrderCurrency,
                                                                             orderItems.Sum(x => x.Price * x.Amount), 0, null, null, 0, 0, 0, 0, 0, 0);

                        var mailTemplate = new BuyInOneClickMailTemplate(order.OrderID.ToString(), "", "", "", orderTable);
                        mailTemplate.BuildMail();

                        SendMail.SendMailNow(SettingsMail.EmailForOrders, "Заказ через Яндекс.Маркет", mailTemplate.Body,
                                             true);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }

            /*
             * Если магазин считает запрос, поступающий от Яндекс.Маркета, некорректным,
             * магазин должен вернуть статус ответа 400 с описанием причины ошибки в теле ответа.
             * Такие ответы будут анализироваться на предмет нарушений и недоработок API со стороны Яндекс.Маркета.
             *
             */
            var orderResponse = new YaMarketOrderResponse()
            {
                order = new YaMarketOrderAccept()
                {
                    accepted = order != null && order.OrderID != 0,
                    id       = yaOrder.order.id
                }
            };

            var context = HttpContext.Current;

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(orderResponse));
            context.Response.End();
        }
        public static void InitBaseSessionSettings()
        {
            HttpContext.Current.Session.Add("IsAdmin", false);

            //Desing

            if (CurrencyService.Currency(SettingsCatalog.DefaultCurrencyIso3) == null)
            {
                CurrencyService.RefreshCurrency();
            }

            CurrencyService.CurrentCurrency = CurrencyService.Currency(SettingsCatalog.DefaultCurrencyIso3) ?? CurrencyService.GetAllCurrencies().First();

            // Internal Settings

            HttpContext.Current.Session.Add("isDebug", false);
            HttpContext.Current.Session.Add("isAuthorize", false);
            HttpContext.Current.Session.Add("errOnAsax", false);
            HttpContext.Current.Session.Add("errMessage", "");
        }
        private string RenderBasketHtml(Customer customer, ShoppingCart shoppingCart)
        {
            if (!shoppingCart.HasItems)
            {
                return(string.Empty);
            }

            var sb = new StringBuilder();

            sb.Append("<table style=\'width:100%;\' cellspacing=\'0\' cellpadding=\'2\'>");
            sb.Append("<tr>");
            sb.AppendFormat("<td style=\'width:100px; text-align: center;\'>&nbsp;</td>");
            sb.AppendFormat("<td>{0}</td>", Resource.Client_OrderConfirmation_Name);
            sb.AppendFormat("<td style=\'width:90px; text-align:center;\'>{0}</td>", Resource.Client_OrderConfirmation_Price);
            sb.AppendFormat("<td style=\'width:80px; text-align: center;\' >{0}</td>", Resource.Client_OrderConfirmation_Count);
            sb.AppendFormat("<td style=\'width:90px; text-align:center;\'>{0}</td>", Resource.Client_OrderConfirmation_Cost);
            sb.Append("</tr>");

            var      allCurrencies = CurrencyService.GetAllCurrencies(true);
            Currency currency;

            try
            {
                currency = allCurrencies.FirstOrDefault(x => x.Iso3 == SettingsCatalog.DefaultCurrencyIso3) ?? allCurrencies.FirstOrDefault();
            }
            catch (Exception)
            {
                currency = allCurrencies.FirstOrDefault();
            }

            foreach (var item in shoppingCart)
            {
                if (item.Offer != null && item.Offer.Product != null)
                {
                    var photo = item.Offer.Photo;
                    var price = CatalogService.CalculateProductPrice(item.Offer.Price, item.Offer.Product.CalculableDiscount,
                                                                     customer.CustomerGroup, CustomOptionsService.DeserializeFromXml(item.AttributesXml));

                    sb.Append("<tr>");
                    if (photo != null)
                    {
                        sb.AppendFormat("<td style=\'text-align: center;\'><img src='{0}' /></td>",
                                        SettingsMain.SiteUrl.Trim('/') + '/' + FoldersHelper.GetImageProductPath(ProductImageType.XSmall, photo.PhotoName, false));
                    }
                    else
                    {
                        sb.AppendFormat("<td>&nbsp;</td>");
                    }
                    sb.AppendFormat("<td style=\' \'>{0}{1}{2}</td>", item.Offer.Product.Name,
                                    item.Offer.Color != null ? "<div>" + SettingsCatalog.ColorsHeader + ": " + item.Offer.Color.ColorName + "</div>" : "",
                                    item.Offer.Size != null  ? "<div>" + SettingsCatalog.SizesHeader + ": " + item.Offer.Size.SizeName + "</div>" : "");

                    sb.AppendFormat("<td style=\'text-align: center;\'>{0}</td>", CatalogService.GetStringPrice(price, currency));
                    sb.AppendFormat("<td style=\'text-align: center;\'>{0}</td>", item.Amount);
                    sb.AppendFormat("<td style=\'text-align: center;\'>{0}</td>", CatalogService.GetStringPrice(price * item.Amount, currency));
                    sb.Append("</tr>");
                }
            }
            sb.Append("</table>");

            return(sb.ToString());
        }
Exemple #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        form.Action = Request.RawUrl;

        if (SaasDataService.IsSaasEnabled && !SaasDataService.CurrentSaasData.IsWorkingNow)
        {
            Response.Redirect(UrlService.GetAbsoluteLink("/app_offline.html"));
        }

        Customer curentCustomer = CustomerSession.CurrentCustomer;

        //Added  by Evgeni
        //if (curentCustomer.EMail != string.Empty)
        //{
        //    lblEnteredAs.Text = Resources.Resource.Client_MasterPage_EnteredAs + curentCustomer.EMail;
        //}
        pnlLogin.Visible       = !curentCustomer.RegistredUser;
        pnlmyAccount.Visible   = curentCustomer.RegistredUser;
        pnlConstructor.Visible = curentCustomer.CustomerRole == Role.Administrator || Demo.IsDemoEnabled || Trial.IsTrialEnabled;

        pnlAdmin.Visible       = (curentCustomer.CustomerRole == Role.Administrator || curentCustomer.CustomerRole == Role.Moderator) && !Demo.IsDemoEnabled && !Trial.IsTrialEnabled;
        lbLoginAsAdmin.Visible = Trial.IsTrialEnabled;

        pnlCurrency.Visible  = SettingsDesign.CurrencyVisibility;
        pnlWishList.Visible  = SettingsDesign.WishListVisibility;
        shoppingCart.Visible = SettingsDesign.ShoppingCartVisibility;

        searchBlock.Visible  = (SettingsDesign.SearchBlockLocation == SettingsDesign.eSearchBlockLocation.TopMenu && SettingsDesign.MainPageMode == SettingsDesign.eMainPageMode.Default);
        demoFeedBack.Visible = true; //Changed by Evgeni Demo.IsDemoEnabled || Trial.IsTrialEnabled;

        //Changed by Evgeni to Change logo on the fly
        if (LogoImagePath == string.Empty)
        {
            Logo.ImgSource = FoldersHelper.GetPath(FolderType.Pictures, SettingsMain.LogoImageName, false);
        }
        else
        {
            Logo.ImgSource = FoldersHelper.GetPath(FolderType.Pictures, LogoImagePath, false);
        }
        ///

        SettingsDesign.eMainPageMode currentMode = !Demo.IsDemoEnabled || !CommonHelper.GetCookieString("structure").IsNotEmpty()
                              ? SettingsDesign.MainPageMode
                              : (SettingsDesign.eMainPageMode)Enum.Parse(typeof(SettingsDesign.eMainPageMode), CommonHelper.GetCookieString("structure"));

        if (currentMode == SettingsDesign.eMainPageMode.Default)
        {
            menuTop.Visible         = true;
            searchBig.Visible       = false;
            menuCatalog.Visible     = true;
            menuTopMainPage.Visible = false;

            liViewCss.Text = @"<link rel=""stylesheet"" href=""css/views/default.css"" >";
        }
        else if (currentMode == SettingsDesign.eMainPageMode.TwoColumns)
        {
            menuTop.Visible         = false;
            searchBig.Visible       = (SettingsDesign.SearchBlockLocation == SettingsDesign.eSearchBlockLocation.TopMenu);
            menuCatalog.Visible     = false;
            menuTopMainPage.Visible = true;

            liViewCss.Text = @"<link rel=""stylesheet"" href=""css/views/twocolumns.css"" >";
        }
        else if (currentMode == SettingsDesign.eMainPageMode.ThreeColumns)
        {
            menuTop.Visible         = false;
            searchBig.Visible       = (SettingsDesign.SearchBlockLocation == SettingsDesign.eSearchBlockLocation.TopMenu);
            menuCatalog.Visible     = false;
            menuTopMainPage.Visible = true;

            liViewCss.Text = @"<link rel=""stylesheet"" href=""css/views/threecolumns.css"" >";
        }


        foreach (Currency row in CurrencyService.GetAllCurrencies(true))
        {
            ddlCurrency.Items.Add(new ListItem {
                Text = row.Name, Value = row.Iso3
            });
        }

        ddlCurrency.SelectedValue = CurrencyService.CurrentCurrency.Iso3;
    }
        public ActionResult UpdateProfile(UserProfileVM userProfileVM)
        {
            //If User does not exists, just update the UserData
            try
            {
                _dbContext = new ApplicationDbContext();
                if (!ModelState.IsValid)
                {
                    goto FormValidationFailed_GetData;
                }

                //Update the User Profile Details
                UserAccountService userAccountService = new UserAccountService(_dbContext);

                //Update the User
                userProfileVM.Id = User.Identity.GetUserId();
                var userUpdateResponse = userAccountService.UpdateUserProfile(userProfileVM, false);
                if (userUpdateResponse.Success == false)
                {
                    if (userUpdateResponse.MessageCode == ResponseResultMessageCode.EmailExists)
                    {
                        ModelState.AddModelError("Email", "A user already exists with the same email address. Please choose a different one.");
                        ViewBag.DisableEmailTextbox = false;
                    }
                    else if (userUpdateResponse.MessageCode == ResponseResultMessageCode.UserNameExists)
                    {
                        ModelState.AddModelError("UrlUsername", "A user already exists with the same username. Please choose a different one.");
                    }
                    else
                    {
                        ModelState.AddModelError("", ResponseResultMessageCode.GetMessageFromCode(userUpdateResponse.MessageCode));
                    }
                    goto FormValidationFailed_GetData;
                }

                //If User is Updated Successfully, Change UrlUserName Claim Also
                if (userUpdateResponse.SuccessCode == ResponseResultMessageCode.UserNameUpdated)
                {
                    var owinContext = HttpContext.GetOwinContext();
                    var UserManager = owinContext.GetUserManager <ApplicationUserManager>();

                    //New Claims List, for current Identity
                    List <Claim> newClaimsList = new List <Claim>();

                    Claim UserNameClaim = User.Identity.GetClaim(_ClaimTypes.UrlUserName);
                    if (UserNameClaim != null)
                    {
                        //If the Username is changed, only then update the Claim
                        if (!UserNameClaim.Value.ToLower().Equals(userProfileVM.UrlUsername.ToLower()))
                        {
                            UserManager.RemoveClaim(userProfileVM.Id, UserNameClaim);
                            UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));

                            newClaimsList.Add(new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));
                        }
                    }
                    else
                    {
                        UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));

                        newClaimsList.Add(new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));
                    }

                    //Update preferred language code if changed
                    var preferredLangClaim = User.Identity.GetClaim(_ClaimTypes.PreferredLanguage);
                    if (!preferredLangClaim.Value.ToLower().Equals(userProfileVM.PreferredLanguage))
                    {
                        UserManager.RemoveClaim(userProfileVM.Id, preferredLangClaim);
                        UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.PreferredLanguage, userProfileVM.PreferredLanguage));
                        newClaimsList.Add(new Claim(_ClaimTypes.PreferredLanguage, userProfileVM.PreferredLanguage));
                    }

                    //Update Current Identity Claim and Login User Again
                    if (newClaimsList.Count > 0)
                    {
                        User.Identity.AddOrUpdateClaims(newClaimsList, owinContext.Authentication);
                    }
                }

                //User update was successfull
                #region Set user preferred language
                string userPreferredLanguageCode = "en";
                if (User != null && User.Identity != null && User.Identity.GetClaim("PreferredLanguage") != null)
                {
                    userPreferredLanguageCode = User.Identity.GetClaim("PreferredLanguage").Value;
                }
                #endregion

                //Now Check If Next button is clicked, goto Step 3
                //If Back button is clicked, goto Step 1
                return(RedirectToAction("Index", new { id = User.Identity.GetUrlUserName(), lang = userPreferredLanguageCode }));
            }
            catch (Exception err)
            {
                ModelState.AddModelError("", err);
                goto FormValidationFailed_GetData;
            }

            //Goto Statement If form validation is failed, goto View but first get the required data for View
FormValidationFailed_GetData:
            ViewBag.YearsOfBirth  = UtilityExtension.GetYearsList();
            ViewBag.LanguagesList = UtilityExtension.GetLanguagesList();

            CurrencyService currencyService = new CurrencyService(_dbContext);
            ViewBag.CurrencyList = currencyService.GetAllCurrencies();
            return(View(userProfileVM));
        }
        public async Task <ActionResult> Step2(UserProfileVM userProfileVM, string SubmitAction = "")
        {
            //If User does no exists, just update the UserData
            try
            {
                ViewBag.DisableEmailTextbox   = true;
                ViewBag.ShowResendEmailButton = false;
                _dbContext = new ApplicationDbContext();
                bool skipValidation = false;

                //If Next Button is clicked, perform the Form Validation, otherwise do not perform Validations
                if (!SubmitAction.ToLower().Equals("back"))
                {
                    if (!ModelState.IsValid)
                    {
                        goto FormValidationFailed_GetData;
                    }
                }
                else
                {
                    skipValidation = true;
                }

                //Update the User Profile Details
                UserAccountService userAccountService = new UserAccountService(_dbContext);

                //Check If the Username is unique
                userProfileVM.Id = User.Identity.GetUserId();

                //Update the User
                var userUpdateResponse = userAccountService.UpdateUserProfile(userProfileVM, skipValidation);
                if (userUpdateResponse.Success == false)
                {
                    if (userUpdateResponse.MessageCode == ResponseResultMessageCode.EmailExists)
                    {
                        ModelState.AddModelError("Email", "A user already exists with the same email address. Please choose a different one.");
                        ViewBag.DisableEmailTextbox = false;
                    }

                    /*else if (userUpdateResponse.MessageCode == ResponseResultMessageCode.EmailNotConfirmed)
                     * {
                     *  ModelState.AddModelError("Email", "You have not confirm your email address. Please confirm your email address to continue. Click on the \"Send Confirmation\" to send the confirmation link again.");
                     *  ViewBag.DisableEmailTextbox = false;
                     * }*/
                    else if (userUpdateResponse.MessageCode == ResponseResultMessageCode.UserNameExists)
                    {
                        ModelState.AddModelError("UrlUsername", "A user already exists with the same username. Please choose a different one.");
                    }
                    else
                    {
                        ModelState.AddModelError("", ResponseResultMessageCode.GetMessageFromCode(userUpdateResponse.MessageCode));
                    }
                    goto FormValidationFailed_GetData;
                }

                //If User is Updated Successfully, Change UrlUserName Claim Also
                var owinContext = HttpContext.GetOwinContext();
                var UserManager = owinContext.GetUserManager <ApplicationUserManager>();

                //New Claims List, for current Identity
                List <Claim> newClaimsList = new List <Claim>();

                Claim UserNameClaim = User.Identity.GetClaim(_ClaimTypes.UrlUserName);
                if (UserNameClaim != null)
                {
                    //If the Username is changed, only then update the Claim
                    if (!UserNameClaim.Value.ToLower().Equals(userProfileVM.UrlUsername.ToLower()))
                    {
                        UserManager.RemoveClaim(userProfileVM.Id, UserNameClaim);
                        UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));

                        newClaimsList.Add(new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));
                    }
                }
                else
                {
                    UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));

                    newClaimsList.Add(new Claim(_ClaimTypes.UrlUserName, userProfileVM.UrlUsername));
                }


                //If User is Updated then the Wizard is Completed, Change HasCompletedProfileWizard Claim Also
                Claim HasCompletedProfileWizardClaim = User.Identity.GetClaim(_ClaimTypes.HasCompletedProfileWizard);
                if (HasCompletedProfileWizardClaim != null)
                {
                    UserManager.RemoveClaim(userProfileVM.Id, HasCompletedProfileWizardClaim);
                }

                UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.HasCompletedProfileWizard, true.ToString()));
                UserManager.AddClaim(userProfileVM.Id, new Claim(_ClaimTypes.PreferredLanguage, userProfileVM.PreferredLanguage));

                newClaimsList.Add(new Claim(_ClaimTypes.HasCompletedProfileWizard, true.ToString()));
                newClaimsList.Add(new Claim(_ClaimTypes.PreferredLanguage, userProfileVM.PreferredLanguage));


                //Update Current Identity Claim and Login User Again
                if (newClaimsList.Count > 0)
                {
                    User.Identity.AddOrUpdateClaims(newClaimsList, owinContext.Authentication);
                }

                //User update was successfull
                //Now Check If Next button is clicked, goto Step 3
                //If Back button is clicked, goto Step 1
                if (SubmitAction.ToLower().Equals("back"))
                {
                    return(RedirectToAction("Step1"));
                }
                else
                {
                    //Before Redirecting to Step 3, send out an email confirmation link mail.
                    if (userProfileVM.EmailConfirmed == false)
                    {
                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(userProfileVM.Id);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userProfileVM.Id, code = code }, protocol: Request.Url.Scheme);

                        string langCode = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
                        bool   isSent   = new EmailHelperService().SendEmailConfirmationTokenMail(userProfileVM.Email, callbackUrl, Strings.ConfirmationEmailSubject, langCode);

                        TempData["ResponseResult"] = new ResponseResult <object>
                        {
                            Message = Strings.Step3_EmailConfirmationLinkText,
                            Success = true
                        };
                    }


                    #region Set user preferred language
                    string userPreferredLanguageCode = "en";
                    if (User != null && User.Identity != null && User.Identity.GetClaim("PreferredLanguage") != null)
                    {
                        userPreferredLanguageCode = User.Identity.GetClaim("PreferredLanguage").Value;
                    }
                    #endregion

                    return(RedirectToAction("Step3", "Profile", new { lang = userPreferredLanguageCode }));
                }
            }
            catch (Exception err)
            {
                ModelState.AddModelError("", err);
                goto FormValidationFailed_GetData;
            }

            //Goto Statement If form validation is failed, goto View but first get the required data for View
FormValidationFailed_GetData:
            ViewBag.YearsOfBirth  = UtilityExtension.GetYearsList();
            ViewBag.LanguagesList = UtilityExtension.GetLanguagesList();

            CurrencyService currencyService = new CurrencyService(_dbContext);
            ViewBag.CurrencyList = currencyService.GetAllCurrencies();
            return(View(userProfileVM));
        }