protected void Page_Load(object sender, EventArgs e) { // Show site selector CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { CurrentMaster.DisplaySiteSelectorPanel = false; return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged); if (!RequestHelper.IsPostBack()) { // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(userId, SiteID) != null) { // Force uniselector to preselect current site siteSelector.Value = SiteID; } // Force to load data siteSelector.Reload(true); } // Get truly selected item SiteID = ValidationHelper.GetInteger(siteSelector.Value, 0); }
/// <summary> /// Returns true if customer is anonymous on current site or has login on current site. /// </summary> /// <param name="customer">Customer object</param> protected bool CheckCustomerSiteID(CustomerInfo customer) { if (customer == null) { return(false); } int currentSiteId = CMSContext.CurrentSiteID; if (customer.CustomerSiteID == currentSiteId) { return(true); } if ((customer.CustomerUserID > 0) && (UserSiteInfoProvider.GetUserSiteInfo(customer.CustomerUserID, currentSiteId) != null)) { return(true); } if (CurrentUser.IsGlobalAdministrator && (customer.CustomerUserID == 0) && (customer.CustomerSiteID == 0)) { return(true); } return(false); }
private bool CustomerIsOnCurrentSite(BaseInfo customerInfo) { var currentSiteID = SiteContext.CurrentSiteID; if (customerInfo.GetIntegerValue("CustomerSiteID", 0) == currentSiteID) { return(true); } var userID = customerInfo.GetIntegerValue("CustomerUserID", 0); return((userID > 0) && (UserSiteInfoProvider.GetUserSiteInfo(userID, currentSiteID) != null)); }
/// <summary> /// Removes user from site. Called when the "Remove user from site" button is pressed. /// Expects the AddUserToSite method to be run first. /// </summary> private bool RemoveUserFromSite() { // Get the user UserInfo removeUser = UserInfoProvider.GetUserInfo("MyNewUser"); if (removeUser != null) { int siteId = CMSContext.CurrentSiteID; // Get the binding UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(removeUser.UserID, siteId); // Delete the binding UserSiteInfoProvider.DeleteUserSiteInfo(userSite); return(true); } return(false); }
/// <summary> /// Page_load event. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Check permissions and UI elements var user = MembershipContext.AuthenticatedUser; if (user != null) { if (!user.IsAuthorizedPerUIElement("CMS.Users", "CmsDesk.Roles")) { RedirectToUIElementAccessDenied("CMS.Users", "CmsDesk.Roles"); } if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Roles", "Read")) { RedirectToAccessDenied("CMS.Roles", "Read"); } } ScriptHelper.RegisterJQuery(Page); // Get user id and site Id from query mUserId = QueryHelper.GetInteger("userid", 0); // Show content placeholder where site selector can be shown CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)) { plcSites.Visible = false; CurrentMaster.DisplaySiteSelectorPanel = false; } if (mUserId > 0) { // Check that only global administrator can edit global administrator's accounts mUserInfo = UserInfoProvider.GetUserInfo(mUserId); CheckUserAvaibleOnSite(mUserInfo); EditedObject = mUserInfo; if (!CheckGlobalAdminEdit(mUserInfo)) { plcTable.Visible = false; ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; // Global roles only for global admin if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { siteSelector.AllowGlobal = true; } // Only sites assigned to user siteSelector.UserId = mUserId; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; if (!RequestHelper.IsPostBack()) { mSiteId = SiteContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(mUserId, mSiteId) != null) { // Force uniselector to preselect current site siteSelector.Value = mSiteId; } // Force to load data siteSelector.Reload(true); } // Get truly selected item mSiteId = ValidationHelper.GetInteger(siteSelector.Value, 0); } usRoles.OnSelectionChanged += usRoles_OnSelectionChanged; string siteIDWhere = (mSiteId <= 0) ? " SiteID IS NULL " : " SiteID =" + mSiteId; usRoles.WhereCondition = siteIDWhere + " AND RoleGroupID IS NULL"; usRoles.SelectItemPageUrl = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx"; usRoles.ListingWhereCondition = siteIDWhere + " AND RoleGroupID IS NULL AND UserID=" + mUserId; usRoles.ReturnColumnName = "RoleID"; usRoles.DynamicColumnName = false; usRoles.GridName = "User_Role_List.xml"; usRoles.AdditionalColumns = "ValidTo"; usRoles.OnAdditionalDataBound += usMemberships_OnAdditionalDataBound; usRoles.DialogWindowHeight = 760; // Exclude generic roles string genericWhere = String.Empty; ArrayList genericRoles = RoleInfoProvider.GetGenericRoles(); if (genericRoles.Count != 0) { foreach (string role in genericRoles) { genericWhere += "'" + SqlHelper.EscapeQuotes(role) + "',"; } genericWhere = genericWhere.TrimEnd(','); usRoles.WhereCondition += " AND ( RoleName NOT IN (" + genericWhere + ") )"; } // Get the active roles for this site var roleIds = new IDQuery <RoleInfo>().Where(siteIDWhere).Column("RoleID"); var data = UserRoleInfoProvider.GetUserRoles().WhereEquals("UserID", mUserId).And().WhereIn("RoleID", roleIds).Columns("RoleID").TypedResult; if (data.Any()) { mCurrentValues = TextHelper.Join(";", data.Select(i => i.RoleID)); } // If not postback or site selection changed if (!RequestHelper.IsPostBack() || (mSiteId != Convert.ToInt32(ViewState["rolesOldSiteId"]))) { // Set values usRoles.Value = mCurrentValues; } // Store selected site id ViewState["rolesOldSiteId"] = mSiteId; string script = "function setNewDateTime(date) {$cmsj('#" + hdnDate.ClientID + "').val(date);}"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "key", ScriptHelper.GetScript(script)); string eventTarget = Request[postEventSourceID]; string eventArgument = Request[postEventArgumentID]; if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Users", "ManageUserRoles")) { RedirectToAccessDenied("CMS.Users", "Manage user roles"); } int id = ValidationHelper.GetInteger(hdnDate.Value, 0); if (id != 0) { DateTime dt = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME); UserRoleInfo uri = UserRoleInfoProvider.GetUserRoleInfo(mUserId, id); if (uri != null) { uri.ValidTo = dt; UserRoleInfoProvider.SetUserRoleInfo(uri); // Invalidate user UserInfoProvider.InvalidateUser(mUserId); ShowChangesSaved(); } } } }
protected void Page_Load(object sender, EventArgs e) { var user = MembershipContext.AuthenticatedUser; // Check UI profile for membership if (!user.IsAuthorizedPerUIElement("CMS.Users", "CmsDesk.Membership")) { RedirectToUIElementAccessDenied("CMS.Users", "CmsDesk.Membership"); } // Check "read" permission if (!user.IsAuthorizedPerResource("CMS.Membership", "Read")) { RedirectToAccessDenied("CMS.Membership", "Read"); } ScriptHelper.RegisterJQuery(Page); ui = UserInfoProvider.GetUserInfo(UserID); CheckUserAvaibleOnSite(ui); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); return; } if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.IsGlobalAdministrator) { CurrentMaster.DisplaySiteSelectorPanel = false; } else { CurrentMaster.DisplaySiteSelectorPanel = true; } var data = MembershipUserInfoProvider.GetMembershipUsers().Where("UserID = " + UserID); if (data.Any()) { currentValues = TextHelper.Join(";", DataHelper.GetStringValues(data.Tables[0], "MembershipID")); } if (!RequestHelper.IsPostBack()) { // Set values usMemberships.Value = currentValues; } // Init uni selector usMemberships.SelectItemPageUrl = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx"; usMemberships.ListingWhereCondition = "UserID=" + UserID; usMemberships.ReturnColumnName = "MembershipID"; usMemberships.DynamicColumnName = false; usMemberships.GridName = "User_Membership_List.xml"; usMemberships.OnAdditionalDataBound += usMemberships_OnAdditionalDataBound; usMemberships.OnSelectionChanged += usMemberships_OnSelectionChanged; usMemberships.AdditionalColumns = "ValidTo"; usMemberships.DialogWindowHeight = 760; // Init int siteID = SiteID; if (CurrentMaster.DisplaySiteSelectorPanel) { // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; siteSelector.AllowGlobal = true; // Only sites assigned to user siteSelector.UserId = UserID; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged); if (!RequestHelper.IsPostBack()) { siteID = SiteContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(UserID, siteID) != null) { // Force uniselector to preselect current site siteSelector.Value = siteID; } } siteID = siteSelector.SiteID; } string siteWhere = (siteID <= 0) ? "MembershipSiteID IS NULL" : "MembershipSiteID =" + siteID; usMemberships.ListingWhereCondition = SqlHelper.AddWhereCondition(usMemberships.ListingWhereCondition, siteWhere); usMemberships.WhereCondition = SqlHelper.AddWhereCondition(usMemberships.WhereCondition, siteWhere); string script = "function setNewDateTime(date) {$cmsj('#" + hdnDate.ClientID + "').val(date);}"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "NewDateUniSelectorScript", ScriptHelper.GetScript(script)); // Manage single item valid to change by calendar string eventTarget = Request[Page.postEventSourceID]; string eventArgument = Request[Page.postEventArgumentID]; if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID) { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Membership", "ManageUserMembership")) { RedirectToAccessDenied("CMS.Membership", "Manage user membership"); } int id = ValidationHelper.GetInteger(hdnDate.Value, 0); if (id != 0) { DateTime dt = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME); MembershipUserInfo mi = MembershipUserInfoProvider.GetMembershipUserInfo(id, UserID); if (mi != null) { mi.ValidTo = dt; MembershipUserInfoProvider.SetMembershipUserInfo(mi); // Invalidate changes if (ui != null) { ui.Generalized.Invalidate(false); } ShowChangesSaved(); } } } }
protected void Page_Load(object sender, EventArgs e) { // Check the license LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.Ecommerce); bool ecommerceOnSite = ResourceSiteInfoProvider.IsResourceOnSite("CMS.Ecommerce", CMSContext.CurrentSiteName); // Check 'ConfigurationRead' permission if (!ecommerceOnSite || !CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Ecommerce", "ConfigurationRead")) { RedirectToAccessDenied("CMS.Ecommerce", "ConfigurationRead"); } // Check 'ConfigurationModify' permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Ecommerce", "ConfigurationModify")) { this.uniSelector.Enabled = false; } userId = QueryHelper.GetInteger("userid", 0); // Show contentplaceholder where site selector can be shown this.CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !CMSContext.CurrentUser.IsGlobalAdministrator) { this.plcSites.Visible = false; this.CurrentMaster.DisplaySiteSelectorPanel = false; } if (userId > 0) { // Check that only global administrator can edit global administrator's accouns UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblError.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblError.Visible = true; return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; // Global departments only for global admin if (CMSContext.CurrentUser.UserSiteManagerAdmin) { siteSelector.AllowGlobal = true; } // Only sites assigned to user siteSelector.UserId = userId; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged); if (!RequestHelper.IsPostBack()) { siteId = CMSContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(userId, siteId) != null) { // Force uniselector to preselect current site siteSelector.Value = siteId; } // Force to load data siteSelector.UpdateWhereCondition(); siteSelector.Reload(true); } // Get truly selected item siteId = ValidationHelper.GetInteger(siteSelector.Value, 0); DataSet ds = DepartmentInfoProvider.GetUserDepartments(userId); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "DepartmentID")); } // If not postback or site selection changed if (!RequestHelper.IsPostBack() || (siteId != Convert.ToInt32(ViewState["departmentsOldSiteId"]))) { // Set values uniSelector.Value = currentValues; } // Store selected site id ViewState["departmentsOldSiteId"] = siteId; } uniSelector.ButtonAddItems.Text = GetString("general.ok"); uniSelector.IconPath = GetImageUrl("Objects/Ecommerce_Department/object.png"); uniSelector.OnSelectionChanged += usSites_OnSelectionChanged; uniSelector.WhereCondition = (siteId <= 0) ? " DepartmentSiteID IS NULL " : " DepartmentSiteID =" + siteId; if (siteId > 0) { string siteName = SiteInfoProvider.GetSiteName(siteId); if (ECommerceSettings.AllowGlobalDepartments(siteName)) { uniSelector.WhereCondition += " OR (DepartmentSiteID IS NULL)"; } } }
protected void Page_Load(object sender, EventArgs e) { CurrentUserInfo user = CMSContext.CurrentUser; // Check UI profile for membership if (!user.IsAuthorizedPerUIElement("CMS.Administration", "Membership")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Administration", "Membership"); } // Check "read" permission if (!user.IsAuthorizedPerResource("CMS.Membership", "Read")) { RedirectToAccessDenied("CMS.Membership", "Read"); } ScriptHelper.RegisterJQuery(Page); ui = UserInfoProvider.GetUserInfo(UserID); CheckUserAvaibleOnSite(ui); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; lblErrorDeskAdmin.Text = GetString("Administration-User_List.ErrorGlobalAdmin"); lblErrorDeskAdmin.Visible = true; return; } DataSet ds = MembershipUserInfoProvider.GetMembershipUsers("UserID = " + UserID, String.Empty); if ((SiteID > 0) && !CMSContext.CurrentUser.IsGlobalAdministrator) { this.CurrentMaster.DisplaySiteSelectorPanel = false; } else { this.CurrentMaster.DisplaySiteSelectorPanel = true; } if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "MembershipID")); } if (!RequestHelper.IsPostBack()) { // Set values usMemberships.Value = currentValues; } // Init uni selector usMemberships.SelectItemPageUrl = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx"; usMemberships.ListingWhereCondition = "UserID=" + UserID; usMemberships.ReturnColumnName = "MembershipID"; usMemberships.DynamicColumnName = false; usMemberships.GridName = "User_Membership_List.xml"; usMemberships.OnAdditionalDataBound += new CMSAdminControls_UI_UniSelector_UniSelector.AdditionalDataBoundEventHandler(usMemberships_OnAdditionalDataBound); usMemberships.OnSelectionChanged += new EventHandler(usMemberships_OnSelectionChanged); usMemberships.AdditionalColumns = "ValidTo"; // Init int siteID = SiteID; if (this.CurrentMaster.DisplaySiteSelectorPanel) { // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; siteSelector.AllowGlobal = true; // Only sites assigned to user siteSelector.UserId = UserID; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged); if (!RequestHelper.IsPostBack()) { siteID = CMSContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(UserID, siteID) != null) { // Force uniselector to preselect current site siteSelector.Value = siteID; } } siteID = siteSelector.SiteID; } if (!String.IsNullOrEmpty(currentValues)) { usMemberships.WhereCondition = "MembershipID NOT IN (" + currentValues.Replace(';', ',') + ")"; } string siteWhere = (siteID <= 0) ? "MembershipSiteID IS NULL" : "MembershipSiteID =" + siteID; usMemberships.ListingWhereCondition = SqlHelperClass.AddWhereCondition(usMemberships.ListingWhereCondition, siteWhere); usMemberships.WhereCondition = SqlHelperClass.AddWhereCondition(usMemberships.WhereCondition, siteWhere); string script = "function setNewDateTime(date) {$j('#" + hdnDate.ClientID + "').val(date);}"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "NewDateUniSelectorScript", ScriptHelper.GetScript(script)); // Manage single item valid to change by calendar string eventTarget = Request["__EVENTTARGET"]; string eventArgument = Request["__EVENTARGUMENT"]; if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID) { // Check "modify" permission if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Membership", "ManageUserMembership")) { RedirectToAccessDenied("CMS.Membership", "Manage user membership"); } int id = ValidationHelper.GetInteger(hdnDate.Value, 0); if (id != 0) { DateTime dt = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME); MembershipUserInfo mi = MembershipUserInfoProvider.GetMembershipUserInfo(id, UserID); if (mi != null) { mi.ValidTo = dt; MembershipUserInfoProvider.SetMembershipUserInfo(mi); // Invalidate changes if (ui != null) { ui.Invalidate(); } this.lblInfo.Visible = true; } } } }
/// <summary> /// Saves data to DB without validation and permissions check. /// </summary> private void SaveData() { // If customer does not already exist, create new one if (Customer == null) { Customer = new CustomerInfo(); Customer.CustomerSiteID = currentSiteId; Customer.CustomerEnabled = true; } Customer.CustomerEmail = txtCustomerEmail.Text.Trim().Truncate(100); Customer.CustomerFax = txtCustomerFax.Text.Trim(); Customer.CustomerLastName = txtCustomerLastName.Text.Trim(); Customer.CustomerPhone = txtCustomerPhone.Text.Trim(); Customer.CustomerFirstName = txtCustomerFirstName.Text.Trim(); Customer.CustomerCompany = txtCustomerCompany.Text.Trim(); Customer.CustomerCountryID = drpCountry.CountryID; Customer.CustomerStateID = drpCountry.StateID; Customer.CustomerOrganizationID = txtOraganizationID.Text.Trim(); Customer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim(); // Set customer's preferences Customer.CustomerPreferredCurrencyID = drpCurrency.CurrencyID; Customer.CustomerPreferredPaymentOptionID = drpPayment.PaymentID; Customer.CustomerPreferredShippingOptionID = drpShipping.ShippingID; if (plcDiscounts.Visible && plcGlobalDiscount.Visible) { Customer.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel; } // Only registered customer can be enabled/disabled if (Customer.CustomerIsRegistered) { Customer.CustomerEnabled = chkCustomerEnabled.Checked; } using (CMSTransactionScope tr = new CMSTransactionScope()) { bool newUserCreated = false; // Create user for customer if (chkHasLogin.Checked) { UserInfo ui = new UserInfo(); ui.UserName = txtUserName.Text.Trim(); ui.FullName = Customer.CustomerFirstName + " " + Customer.CustomerLastName; ui.IsGlobalAdministrator = false; ui.UserEnabled = true; UserInfoProvider.SetPassword(ui, passStrength.Text); UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName); Customer.CustomerEnabled = true; Customer.CustomerUserID = ui.UserID; chkCustomerEnabled.Checked = Customer.CustomerEnabled; newUserCreated = true; // Show fields requiring registered customer pnlEdit.Visible = false; pnlStatic.Visible = true; plcDiscounts.Visible = true; plcPreferences.Visible = true; chkHasLogin.Checked = false; plcSiteDiscount.Visible = true; lblUserNameStaticValue.Text = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName)); if (AllowEditUser) { btnEditUser.OnClientClick = "modalDialog('" + CMSContext.ResolveDialogUrl("~/CMSModules/Membership/Pages/Users/User_Edit_Frameset.aspx") + "?userid=" + Customer.CustomerUserID + "', 'UserEdit', 950, 700); return false;"; btnEditUser.Visible = true; } // Hide global discount level selector when global levels not allowed plcGlobalDiscount.Visible = allowGlobalDiscountLevels; } // Save customer CustomerInfoProvider.SetCustomerInfo(Customer); // Enable/disable corresponding registered user if (Customer.CustomerIsRegistered && !newUserCreated) { UserInfo ui = UserInfoProvider.GetUserInfo(Customer.CustomerUserID); // If the customer already has the record in the CMS_User table, update email if (ui != null) { ui.Email = Customer.CustomerEmail; UserInfoProvider.SetUserInfo(ui); } // Save site specific values UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, currentSiteId); if (userSite != null) { userSite.UserPreferredCurrencyID = drpCurrency.CurrencyID; userSite.UserPreferredPaymentOptionID = drpPayment.PaymentID; userSite.UserPreferredShippingOptionID = drpShipping.ShippingID; userSite.UserDiscountLevelID = drpDiscountLevel.DiscountLevel; UserSiteInfoProvider.SetUserSiteInfo(userSite); } } // Commit transaction tr.Commit(); // Raise OnSaved event RaiseOnSaved(); } }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check module permissions if (!ECommerceContext.IsUserAuthorizedToModifyCustomer()) { RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyCustomers"); } string errorMessage = ""; if ((txtCustomerCompany.Text.Trim() == "") && ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == ""))) { errorMessage = GetString("Customers_Edit.errorInsert"); } else if (ECommerceSettings.RequireCompanyInfo(CMSContext.CurrentSite.SiteName) && (txtCustomerCompany.Text.Trim() != "" || txtOraganizationID.Text.Trim() != "" || txtTaxRegistrationID.Text.Trim() != "")) { errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text.Trim(), GetString("customers_edit.errorcompany")) .NotEmpty(txtOraganizationID.Text.Trim(), GetString("customers_edit.errororganizationid")) .NotEmpty(txtTaxRegistrationID.Text.Trim(), GetString("customers_edit.errortaxregid")).Result; } else if ((txtCustomerEmail.Text.Trim() != "") && !ValidationHelper.IsEmail(txtCustomerEmail.Text)) { errorMessage = GetString("Customers_Edit.errorEmail"); } if (chkHasLogin.Checked) { if (errorMessage == "") { errorMessage = new Validator().NotEmpty(txtUserName.Text.Trim(), GetString("Customer_Edit_Login_Edit.rqvUserName")) .NotEmpty(passStrength.Text, GetString("Customer_Edit_Login_Edit.rqvPassword1")) .NotEmpty(txtPassword2.Text, GetString("Customer_Edit_Login_Edit.rqvPassword2")).Result; } if ((errorMessage == "") && (passStrength.Text != txtPassword2.Text)) { errorMessage = GetString("Customer_Edit_Login_Edit.DifferentPasswords"); } // Check policy if ((errorMessage == "") && !passStrength.IsValid()) { errorMessage = UserInfoProvider.GetPolicyViolationMessage(CMSContext.CurrentSiteName); } // Check if user name is unique if (errorMessage == "") { UserInfo existingUser = UserInfoProvider.GetUserInfo(txtUserName.Text.Trim()); if (existingUser != null) { errorMessage = GetString("Customer_Edit_Login_Edit.UserExist"); } } } if (errorMessage == "") { CustomerInfo customerObj = CustomerInfoProvider.GetCustomerInfo(customerid); // If customer does not already exist, create new one if (customerObj == null) { customerObj = new CustomerInfo(); customerObj.CustomerSiteID = currentSiteId; customerObj.CustomerEnabled = true; } customerObj.CustomerEmail = txtCustomerEmail.Text.Trim(); customerObj.CustomerFax = txtCustomerFax.Text.Trim(); customerObj.CustomerLastName = txtCustomerLastName.Text.Trim(); customerObj.CustomerPhone = txtCustomerPhone.Text.Trim(); customerObj.CustomerFirstName = txtCustomerFirstName.Text.Trim(); customerObj.CustomerCompany = txtCustomerCompany.Text.Trim(); customerObj.CustomerCountryID = drpCountry.CountryID; customerObj.CustomerStateID = drpCountry.StateID; customerObj.CustomerOrganizationID = txtOraganizationID.Text.Trim(); customerObj.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim(); // Set customer's preferences customerObj.CustomerPreferredCurrencyID = drpCurrency.CurrencyID; customerObj.CustomerPreferredPaymentOptionID = drpPayment.PaymentID; customerObj.CustomerPreferredShippingOptionID = drpShipping.ShippingID; if (plcDiscounts.Visible && plcGlobalDiscount.Visible) { customerObj.CustomerDiscountLevelID = drpGlobalDiscountLevel.DiscountLevel; } // Only registered customer can be enabled/diabled if (customerObj.CustomerIsRegistered) { customerObj.CustomerEnabled = chkCustomerEnabled.Checked; } bool refreshHeader = true; using (CMSTransactionScope tr = new CMSTransactionScope()) { // Create user for customer if (chkHasLogin.Checked) { UserInfo ui = new UserInfo(); ui.UserName = txtUserName.Text.Trim(); ui.FullName = customerObj.CustomerFirstName + " " + customerObj.CustomerLastName; ui.IsGlobalAdministrator = false; ui.UserEnabled = true; UserInfoProvider.SetPassword(ui, passStrength.Text); UserInfoProvider.AddUserToSite(ui.UserName, CMSContext.CurrentSiteName); customerObj.CustomerEnabled = true; customerObj.CustomerUserID = ui.UserID; refreshHeader = true; } // Save customer CustomerInfoProvider.SetCustomerInfo(customerObj); // Enable/disable coresponding registered user if (customerObj.CustomerIsRegistered && !chkHasLogin.Checked) { UserInfo ui = UserInfoProvider.GetUserInfo(customerObj.CustomerUserID); // If the customer already has the record in the CMS_User table, update email if (ui != null) { ui.Email = customerObj.CustomerEmail; UserInfoProvider.SetUserInfo(ui); } // Save site specific values UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(customerObj.CustomerUserID, CMSContext.CurrentSiteID); if (userSite != null) { userSite.UserPreferredCurrencyID = drpCurrency.CurrencyID; userSite.UserPreferredPaymentOptionID = drpPayment.PaymentID; userSite.UserPreferredShippingOptionID = drpShipping.ShippingID; userSite.UserDiscountLevelID = drpDiscountLevel.DiscountLevel; UserSiteInfoProvider.SetUserSiteInfo(userSite); } } // Commit transaction tr.Commit(); } URLHelper.Redirect("Customer_Edit_General.aspx?customerid=" + Convert.ToString(customerObj.CustomerID) + "&saved=1&hidebreadcrumbs=" + QueryHelper.GetInteger("hidebreadcrumbs", 0) + "&siteId=" + SiteID + (refreshHeader ? "&refreshHeader=1" : "")); } else { lblError.Visible = true; lblError.Text = errorMessage; } }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { string errorMessage = ""; string siteName = CMSContext.CurrentSiteName; if ((txtCustomerCompany.Text.Trim() == "" || !chkCompanyAccount.Checked) && ((txtCustomerFirstName.Text.Trim() == "") || (txtCustomerLastName.Text.Trim() == ""))) { errorMessage = GetString("Customers_Edit.errorInsert"); } // Check the following items if complete company info is required for company account if (errorMessage == "" && ECommerceSettings.RequireCompanyInfo(siteName) && chkCompanyAccount.Checked) { errorMessage = new Validator().NotEmpty(txtCustomerCompany.Text, GetString("customers_edit.errorCompany")) .NotEmpty(txtOraganizationID.Text, GetString("customers_edit.errorOrganizationID")) .NotEmpty(txtTaxRegistrationID.Text, GetString("customers_edit.errorTaxRegID")).Result; } if (errorMessage == "") { errorMessage = new Validator().IsEmail(txtCustomerEmail.Text.Trim(), GetString("customers_edit.erroremailformat")).Result; } plcCompanyInfo.Visible = chkCompanyAccount.Checked; if (errorMessage == "") { // If customer doesn't already exist, create new one if (mCustomer == null) { mCustomer = new CustomerInfo(); mCustomer.CustomerEnabled = true; mCustomer.CustomerUserID = CMSContext.CurrentUser.UserID; } int currencyId = selectCurrency.CurrencyID; if (ECommerceContext.CurrentShoppingCart != null) { ECommerceContext.CurrentShoppingCart.ShoppingCartCurrencyID = currencyId; } mCustomer.CustomerEmail = txtCustomerEmail.Text.Trim(); mCustomer.CustomerFax = txtCustomerFax.Text.Trim(); mCustomer.CustomerLastName = txtCustomerLastName.Text.Trim(); mCustomer.CustomerPhone = txtCustomerPhone.Text.Trim(); mCustomer.CustomerFirstName = txtCustomerFirstName.Text.Trim(); mCustomer.CustomerCountryID = drpCountry.CountryID; mCustomer.CustomerStateID = drpCountry.StateID; mCustomer.CustomerCreated = DateTime.Now; // Set customers's preferences mCustomer.CustomerPreferredCurrencyID = (currencyId > 0) ? currencyId : 0; mCustomer.CustomerPreferredPaymentOptionID = drpPayment.PaymentID; mCustomer.CustomerPreferredShippingOptionID = drpShipping.ShippingID; // Check if customer is registered if (mCustomer.CustomerIsRegistered) { // Find user-site binding UserSiteInfo userSite = UserSiteInfoProvider.GetUserSiteInfo(Customer.CustomerUserID, CMSContext.CurrentSiteID); if (userSite != null) { // Set user's preferences userSite.UserPreferredCurrencyID = mCustomer.CustomerPreferredCurrencyID; userSite.UserPreferredPaymentOptionID = mCustomer.CustomerPreferredPaymentOptionID; userSite.UserPreferredShippingOptionID = mCustomer.CustomerPreferredShippingOptionID; UserSiteInfoProvider.SetUserSiteInfo(userSite); } } if (chkCompanyAccount.Checked) { mCustomer.CustomerCompany = txtCustomerCompany.Text.Trim(); if (ECommerceSettings.ShowOrganizationID(siteName)) { mCustomer.CustomerOrganizationID = txtOraganizationID.Text.Trim(); } if (ECommerceSettings.ShowTaxRegistrationID(siteName)) { mCustomer.CustomerTaxRegistrationID = txtTaxRegistrationID.Text.Trim(); } } else { mCustomer.CustomerCompany = ""; mCustomer.CustomerOrganizationID = ""; mCustomer.CustomerTaxRegistrationID = ""; } // Update customer data CustomerInfoProvider.SetCustomerInfo(mCustomer); // Update corresponding user email UserInfo user = mCustomer.CustomerUser; if (user != null) { user.Email = mCustomer.CustomerEmail; UserInfoProvider.SetUserInfo(user); } // Update corresponding contact data ModuleCommands.OnlineMarketingUpdateContactFromExternalData(mCustomer, DataClassInfoProvider.GetDataClass(CustomerInfo.TYPEINFO.ObjectClassName).ClassContactOverwriteEnabled, ModuleCommands.OnlineMarketingGetCurrentContactID()); // Let others now that customer was created if (OnCustomerCrated != null) { OnCustomerCrated(); ShowChangesSaved(); } else { URLHelper.Redirect(URLHelper.AddParameterToUrl(URLRewriter.CurrentURL, "saved", "1")); } } else { //Show error ShowError(errorMessage); } }
public void ProcessRequest(HttpContext context) { var authorizationResponse = new AuthorizationResponse(); // If response_type is "code id_token", the authorization endpoint will give us back //4 values. // i) code: used in order to exchange the access token // ii) id_token: contains user's authentication information in an encoded format // iii) scope: the access privileges requested for access token // iv) session_state: allows you to restore the previous state of your application // // If response_type is "code", the authorization endpoint will give us back 2 values: // i) code: used in order to exchange the access token // ii) state: provide by us; allows you to restore the previous state of your application // Begin by determining whether authorization (code) or hybrid flow (code id_token) if (OAuthConfiguration.ResponseType == "CodeIdToken") { authorizationResponse.PopulateFrom(context.Request.Form); } else { authorizationResponse.Code = context.Request.QueryString["code"]; authorizationResponse.State = context.Request.QueryString["state"]; } // Check if authorization code is present in the response. if (string.IsNullOrEmpty(authorizationResponse.Code)) { throw new Exception("Authorization code is not present in the response."); } var tokenEndpoint = OAuthConfiguration.Authority + "/" + OAuthConfiguration.TokenEndpointPath; var userInfoEndpoint = OAuthConfiguration.Authority + "/" + OAuthConfiguration.UserInfoEndpointPath; // Use the authorization code to retrieve access and id tokens. var tokenResponse = Task.Run(() => HttpClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest { Address = tokenEndpoint, ClientId = OAuthConfiguration.ClientId, ClientSecret = OAuthConfiguration.ClientSecret, Code = authorizationResponse.Code, RedirectUri = $"{OAuthConfiguration.Host}/SignInOidc.ashx" })) .ConfigureAwait(false) .GetAwaiter() .GetResult(); if (tokenResponse.IsError) { throw new Exception("There was an error retrieving the access token.", tokenResponse.Exception); } // If using an authorization code flow, we get the id_token from the token endpoint // so we populate it now into the authorizationResponse object if (OAuthConfiguration.ResponseType == "Code") { authorizationResponse.IdToken = tokenResponse.Json["id_token"].ToString(); } // Get user claims by calling the user info endpoint using the access token. var userInfoResponse = Task.Run(() => HttpClient.GetUserInfoAsync(new UserInfoRequest { Address = userInfoEndpoint, Token = tokenResponse.AccessToken })) .ConfigureAwait(false) .GetAwaiter() .GetResult(); //LOGGING// StreamWriter sw5 = new StreamWriter("c:\\docs\\logfile1.txt", append: true); sw5.WriteLine("The token response is: " + tokenResponse.Json); sw5.WriteLine("The endpoint is: " + userInfoEndpoint); sw5.WriteLine("The error is: " + userInfoResponse.Error); sw5.WriteLine("The raw is: " + userInfoResponse.Raw); sw5.Close(); //END LOGGING// if (userInfoResponse.IsError) { throw new Exception("There was an error retrieving user information from authority.", userInfoResponse.Exception); } // It is important to get the email claim and check if the user exists locally. var userClaims = userInfoResponse.Claims; //Commented out from original code //var userName = userClaims.GetValueOrDefault(OAuthConfiguration.UserNameClaim ?? JwtClaimTypes.Name); var userName = userInfoResponse.Json[OAuthConfiguration.UserNameClaim].ToString(); var email = userClaims.GetValueOrDefault(JwtClaimTypes.Email); if (string.IsNullOrEmpty(userName)) { throw new Exception("Username cannot be found in user claims."); } // Check if the user exists in Kentico. UserInfo userInfo = UserInfoProvider.GetUserInfo(userName); // Get admin claim so we can decide if we need to assign a specific role to the user. var isAdmin = userClaims.GetValueOrDefault <bool>(CustomClaimTypes.Admin); // In this case we need to create the user. if (userInfo == null) { var firstName = userClaims.GetValueOrDefault(JwtClaimTypes.GivenName); var lastName = userClaims.GetValueOrDefault(JwtClaimTypes.FamilyName); // Creates a new user object. userInfo = new UserInfo { // Sets the user properties. Email = email, Enabled = true, FirstName = firstName, FullName = $"{firstName} {lastName}", IsExternal = true, LastName = lastName, SiteIndependentPrivilegeLevel = isAdmin ? UserPrivilegeLevelEnum.GlobalAdmin : UserPrivilegeLevelEnum.None, UserCreated = DateTime.UtcNow, UserName = userName, UserIsDomain = true }; // Created user must first be created and saved so we can update other properties in the next steps. UserInfoProvider.SetUserInfo(userInfo); UserSiteInfoProvider.AddUserToSite(userInfo.UserID, SiteContext.CurrentSite.SiteID); var handler = UserCreated; handler?.Invoke(this, new UserCreatedEventArgs { User = userInfo, Claims = userClaims }); } else { // Update existing user's privilege level to reflect a possible change made on IdentityServer. if (isAdmin) { userInfo.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.GlobalAdmin; } userInfo.UserIsDomain = true; var userCurrentSite = UserSiteInfoProvider.GetUserSiteInfo(userInfo.UserID, SiteContext.CurrentSiteID); if (userCurrentSite == null) { UserSiteInfoProvider.AddUserToSite(userInfo.UserID, SiteContext.CurrentSiteID); } UserInfoProvider.SetUserInfo(userInfo); } // Log the user in. AuthenticateUser(userInfo.UserName, true); CookiesHelper.SetValue( name: CookieNames.OAuthCookie, values: new Dictionary <string, string> { { OidcConstants.TokenTypes.AccessToken, tokenResponse.AccessToken }, { OidcConstants.TokenTypes.RefreshToken, tokenResponse.RefreshToken }, { OidcConstants.TokenResponse.ExpiresIn, tokenResponse.ExpiresIn.ToString() }, { OidcConstants.ResponseTypes.IdToken, tokenResponse.IdentityToken } }, expires: DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn) ); // Try to retrieve state in order to navigate the user back to where he initially requested. var returnUrl = "/"; if (!string.IsNullOrEmpty(authorizationResponse.State)) { var stateProvider = new StateProvider <string>(); var state = stateProvider.RetrieveState(authorizationResponse.State); if (state != "") { returnUrl = state; } else { returnUrl = OAuthConfiguration.Host; } } //LOGGING// StreamWriter sw6 = new StreamWriter("c:\\docs\\logfile1.txt", append: true); sw6.WriteLine("The URL is: " + returnUrl); sw6.Close(); //END LOGGING// // Redirect to the requested page. context.Response.Redirect(returnUrl); HttpContext.Current.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Page_load event. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Check permissions and UI elements CurrentUserInfo user = CMSContext.CurrentUser; if (user != null) { if (!user.IsAuthorizedPerUIElement("CMS.Administration", "Roles")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Administration", "Roles"); } if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Roles", "Read")) { RedirectToAccessDenied("CMS.Roles", "Read"); } } ScriptHelper.RegisterJQuery(Page); // Get user id and site Id from query userId = QueryHelper.GetInteger("userid", 0); // Show contentplaceholder where site selector can be shown CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !CMSContext.CurrentUser.IsGlobalAdministrator) { plcSites.Visible = false; CurrentMaster.DisplaySiteSelectorPanel = false; } if (userId > 0) { // Check that only global administrator can edit global administrator's accouns ui = UserInfoProvider.GetUserInfo(userId); CheckUserAvaibleOnSite(ui); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; // Global roles only for global admin if (CMSContext.CurrentUser.UserSiteManagerAdmin) { siteSelector.AllowGlobal = true; } // Only sites assigned to user siteSelector.UserId = userId; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += new EventHandler(UniSelector_OnSelectionChanged); if (!RequestHelper.IsPostBack()) { siteId = CMSContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(userId, siteId) != null) { // Force uniselector to preselect current site siteSelector.Value = siteId; } // Force to load data siteSelector.UpdateWhereCondition(); siteSelector.Reload(true); } // Get truly selected item siteId = ValidationHelper.GetInteger(siteSelector.Value, 0); } usRoles.OnSelectionChanged += new EventHandler(usRoles_OnSelectionChanged); string siteIDWhere = (siteId <= 0) ? " SiteID IS NULL " : " SiteID =" + siteId; usRoles.WhereCondition = siteIDWhere + " AND RoleGroupID IS NULL"; usRoles.SelectItemPageUrl = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx"; usRoles.ListingWhereCondition = siteIDWhere + " AND RoleGroupID IS NULL AND UserID=" + userId; usRoles.ReturnColumnName = "RoleID"; usRoles.DynamicColumnName = false; usRoles.GridName = "User_Role_List.xml"; usRoles.AdditionalColumns = "ValidTo"; usRoles.OnAdditionalDataBound += new CMSAdminControls_UI_UniSelector_UniSelector.AdditionalDataBoundEventHandler(usMemberships_OnAdditionalDataBound); // Exclude generic roles string genericWhere = null; ArrayList genericRoles = RoleInfoProvider.GetGenericRoles(); if (genericRoles.Count != 0) { foreach (string role in genericRoles) { genericWhere += "'" + role.Replace("'", "''") + "',"; } genericWhere = genericWhere.TrimEnd(','); usRoles.WhereCondition += " AND ( RoleName NOT IN (" + genericWhere + ") )"; } // Get the active roles for this site DataSet ds = UserRoleInfoProvider.GetUserRoles("UserID = " + userId + " AND RoleID IN (SELECT RoleID FROM CMS_Role WHERE SiteID IS NULL OR SiteID = " + siteId + ")", null, 0, "RoleID"); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "RoleID")); } // If not postback or site selection changed if (!RequestHelper.IsPostBack() || (siteId != Convert.ToInt32(ViewState["rolesOldSiteId"]))) { // Set values usRoles.Value = currentValues; } // Store selected site id ViewState["rolesOldSiteId"] = siteId; string script = "function setNewDateTime(date) {$j('#" + hdnDate.ClientID + "').val(date);}"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "key", ScriptHelper.GetScript(script)); string eventTarget = Request["__EVENTTARGET"]; string eventArgument = Request["__EVENTARGUMENT"]; if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID) { if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Users", "ManageUserRoles")) { RedirectToAccessDenied("CMS.Users", "Manage user roles"); } int id = ValidationHelper.GetInteger(hdnDate.Value, 0); if (id != 0) { DateTime dt = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME); UserRoleInfo uri = UserRoleInfoProvider.GetUserRoleInfo(userId, id); if (uri != null) { uri.ValidTo = dt; UserRoleInfoProvider.SetUserRoleInfo(uri); // Invalidate user UserInfoProvider.InvalidateUser(userId); ShowChangesSaved(); } } } }
protected void Page_Load(object sender, EventArgs e) { // Check the license LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.Ecommerce); bool ecommerceOnSite = ResourceSiteInfoProvider.IsResourceOnSite(ModuleName.ECOMMERCE, SiteContext.CurrentSiteName); // Check 'ConfigurationRead' permission if (!ecommerceOnSite || !MembershipContext.AuthenticatedUser.IsAuthorizedPerResource(ModuleName.ECOMMERCE, EcommercePermissions.CONFIGURATION_READ)) { RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.CONFIGURATION_READ); } // Check 'ConfigurationModify' permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource(ModuleName.ECOMMERCE, EcommercePermissions.CONFIGURATION_MODIFY)) { uniSelector.Enabled = false; } userId = QueryHelper.GetInteger("userid", 0); // Show contentplaceholder where site selector can be shown CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.IsGlobalAdministrator) { plcSites.Visible = false; CurrentMaster.DisplaySiteSelectorPanel = false; } if (userId > 0) { // Check that only global administrator can edit global administrator's accouns UserInfo ui = UserInfoProvider.GetUserInfo(userId); EditedObject = ui; if (!CheckGlobalAdminEdit(ui)) { plcTable.Visible = false; // Show error message ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; // Global departments only for global admin if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { siteSelector.AllowGlobal = true; } // Only sites assigned to user siteSelector.UserId = userId; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; if (!RequestHelper.IsPostBack()) { siteId = SiteContext.CurrentSiteID; // If user is member of current site if (UserSiteInfoProvider.GetUserSiteInfo(userId, siteId) != null) { // Force uniselector to preselect current site siteSelector.Value = siteId; } // Force to load data siteSelector.Reload(true); } // Get truly selected item siteId = ValidationHelper.GetInteger(siteSelector.Value, 0); DataSet ds = DepartmentInfoProvider.GetUserDepartments(userId); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", DataHelper.GetStringValues(ds.Tables[0], "DepartmentID")); } // If not postback or site selection changed if (!RequestHelper.IsPostBack() || (siteId != Convert.ToInt32(ViewState["departmentsOldSiteId"]))) { // Set values uniSelector.Value = currentValues; } // Store selected site id ViewState["departmentsOldSiteId"] = siteId; } uniSelector.ButtonAddItems.Text = GetString("general.ok"); uniSelector.OnSelectionChanged += usSites_OnSelectionChanged; uniSelector.WhereCondition = (siteId <= 0) ? " DepartmentSiteID IS NULL " : " DepartmentSiteID =" + siteId; if (siteId > 0) { if (ECommerceSettings.AllowGlobalDepartments(siteId)) { uniSelector.WhereCondition += " OR (DepartmentSiteID IS NULL)"; } } }