/// <summary> /// AfterDataLoad event handler of UIForm. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event argument</param> private void Control_OnAfterDataLoad(object sender, EventArgs e) { // Store edited site object in local variable siteInfo = Control.EditedObject as SiteInfo; // Set SiteID of SiteCultureSelector in order to offer only cultures assigned to the edited site. FormEngineUserControl visitorCultureControl = Control.FieldControls["SiteDefaultVisitorCulture"]; if (visitorCultureControl != null) { visitorCultureControl.SetValue("SiteID", siteInfo.SiteID); } // Set "(none)" special item value for Site default stylesheet field EditingFormControl efc = Control.FieldEditingControls["SiteDefaultStylesheetID"]; if (efc != null) { UniSelector uniSelector = ControlsHelper.GetChildControl(efc, typeof(UniSelector)) as UniSelector; if (uniSelector != null) { uniSelector.NoneRecordValue = "-1"; } } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblContentAfter.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtContentAfter.NestedControl.Controls); lblContentBefore.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtContentBefore.NestedControl.Controls); }
void UIFormControl_OnBeforeDataRetrieval(object sender, EventArgs e) { // Set site id and other data if the room is new if ((UIContext.EditedObject == null) || (((ChatRoomInfo)UIContext.EditedObject).ChatRoomID <= 0)) { IDataContainer data = UIFormControl.Data; data["ChatRoomCreatedByChatUserID"] = ChatUserHelper.GetChatUserFromCMSUser().ChatUserID; data["ChatRoomCreatedWhen"] = DateTime.Now; // GETDATE() will be used on SQL Server side data["ChatRoomSiteID"] = SiteID; Guid guid = Guid.NewGuid(); data["ChatRoomGUID"] = guid; EditingFormControl passwordEditingControl = UIFormControl.FieldEditingControls["chatroompassword"]; string password = passwordEditingControl.Value.ToString(); passwordEditingControl.Value = ChatRoomHelper.GetRoomPasswordHash(password, guid); } else { ChatRoomInfo room = UIContext.EditedObject as ChatRoomInfo; EditingFormControl enabledControl = UIFormControl.FieldEditingControls["chatroomenabled"]; bool enabled = (bool)enabledControl.Value; if (room.ChatRoomEnabled != enabled) { if (enabled) { ChatRoomHelper.EnableChatRoom(room.ChatRoomID); } else { ChatRoomHelper.DisableChatRoom(room.ChatRoomID); } } } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblFieldCaption.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtFieldCaption.NestedControl.Controls); lblFieldDescription.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtDescription.NestedControl.Controls); lblExplanationText.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtExplanationText.NestedControl.Controls); lblField.AssociatedControlClientID = drpControl.InputClientID; // Check if the form control is allowed for selected data type var control = FormUserControlInfoProvider.GetFormUserControlInfo(drpControl.Value.ToString()); string dataTypeColumn = FormHelper.GetDataTypeColumn(AttributeType); if ((control != null) && !String.IsNullOrEmpty(dataTypeColumn)) { bool allowType = ValidationHelper.GetBoolean(control[dataTypeColumn], false); if (!allowType) { var warning = HTMLHelper.HTMLEncode(String.Format(GetString("fieldeditor.controlnotallowedfordatatype"), control.UserControlDisplayName)); ShowWarning(warning); } } }
/// <summary> /// Handles the OnAfterDataLoad event of the formElem control. /// </summary> private void formElem_OnAfterDataLoad(object sender, EventArgs e) { if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.Dashboard)) { FormEngineUserControl typeCtrl = formElem.FieldControls["WidgetZoneType"]; if (typeCtrl != null) { typeCtrl.SetValue("IsDashboard", true); } } else { // Disable WidgetZoneType if the zone is a zone variant or has variants if ((ZoneVariantID > 0) || IsNewVariant || ((webPartZone != null) && (webPartZone.HasVariants))) { EditingFormControl editingCtrl = formElem.FieldEditingControls["WidgetZoneType"]; if (editingCtrl != null) { editingCtrl.Enabled = false; } } } }
protected void Page_Load(object sender, EventArgs e) { UIFormControl.OnBeforeDataRetrieval += UIFormControl_OnBeforeDataRetrieval; UIFormControl.OnAfterSave += UIFormControl_OnAfterSave; UIFormControl.OnCheckPermissions += UIFormControl_OnCheckPermissions; UIFormControl.OnItemValidation += UiFormControlOnOnItemValidation; string urlAfterCreate = UIContextHelper.GetElementUrl("CMS.Chat", "EditChatRoom"); urlAfterCreate = URLHelper.AddParameterToUrl(urlAfterCreate, "roomId", "{%EditedObject.ID%}"); urlAfterCreate = URLHelper.AddParameterToUrl(urlAfterCreate, "objectid", "{%EditedObject.ID%}"); urlAfterCreate = URLHelper.AddParameterToUrl(urlAfterCreate, "siteid", "{?siteid?}"); urlAfterCreate = URLHelper.AddParameterToUrl(urlAfterCreate, "saved", "1"); urlAfterCreate = URLHelper.AddParameterToUrl(urlAfterCreate, "displaytitle", "false"); UIFormControl.RedirectUrlAfterCreate = urlAfterCreate; // Allow an empty password EditingFormControl passwordEditingControl = UIFormControl.FieldEditingControls["chatroompassword"]; var passwordStrengthControl = passwordEditingControl.NestedControl as CMSModules_Membership_FormControls_Passwords_PasswordStrength; if (passwordStrengthControl != null) { passwordStrengthControl.AllowEmpty = true; } }
/// <summary> /// Show default value control and required control according to attribute type. /// </summary> public void ShowDefaultControl() { plcDefaultValue.Visible = true; SetFieldForTranslations(); SetReferenceToField(); var dataType = DataTypeManager.GetDataType(TypeEnum.Field, AttributeType); HandleRequiredVisibility(dataType); // Hide all default value controls first txtDefaultValue.Visible = false; chkDefaultValue.Visible = false; rbDefaultValue.Visible = false; txtLargeDefaultValue.Visible = false; datetimeDefaultValue.Visible = false; if ((dataType != null) && dataType.HasConfigurableDefaultValue) { var systemType = dataType.Type; // Date and time types if (systemType == typeof(DateTime)) { // Use date time picker for date and time types datetimeDefaultValue.Visible = true; var calendarControl = ((FormEngineUserControl)datetimeDefaultValue.NestedControl); lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(calendarControl.Controls); } else if (systemType == typeof(bool)) { // Use checkbox or radio button for boolean types chkDefaultValue.Visible = !AllowEmpty; rbDefaultValue.Visible = AllowEmpty; lblDefaultValue.AssociatedControlClientID = AllowEmpty ? EditingFormControl.GetInputClientID(rbDefaultValue.NestedControl.Controls) : EditingFormControl.GetInputClientID(chkDefaultValue.NestedControl.Controls); } else if (AttributeType == FieldDataType.LongText) { // Special case for long text to provide rich editor txtLargeDefaultValue.Visible = true; lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtLargeDefaultValue.NestedControl.Controls); } else { // Use textbox for other types txtDefaultValue.Visible = true; lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtDefaultValue.NestedControl.Controls); } } else { // Hide default value for types without default value plcDefaultValue.Visible = false; } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblCategoryCaption.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCategoryCaption.NestedControl.Controls); lblCollapsible.AssociatedControlClientID = EditingFormControl.GetInputClientID(chkCollapsible.NestedControl.Controls); lblCollapsedByDefault.AssociatedControlClientID = EditingFormControl.GetInputClientID(chkCollapsedByDefault.NestedControl.Controls); lblVisible.AssociatedControlClientID = EditingFormControl.GetInputClientID(chkVisible.NestedControl.Controls); }
private static bool TrySetMacroDefaultValue(bool isMacro, string defaultValue, EditingFormControl control) { if (isMacro || MacroProcessor.ContainsMacro(defaultValue)) { control.SetValue(defaultValue, isMacro); return(true); } return(false); }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblFieldCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtFieldCssClass.NestedControl.Controls); lblCaptionCellCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionCellCssClass.NestedControl.Controls); lblCaptionCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionCssClass.NestedControl.Controls); lblCaptionStyle.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtCaptionStyle.NestedControl.Controls); lblControlCellCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtControlCellCssClass.NestedControl.Controls); lblControlCssClass.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtControlCssClass.NestedControl.Controls); lblInputStyle.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtInputStyle.NestedControl.Controls); }
/// <summary> /// Returns new instance of resolver for given class (includes all fields, etc.). /// </summary> /// <param name="formInfo">FormInfo</param> private static ContextResolver GetFormResolver(FormInfo formInfo) { ContextResolver mContextResolver = GetDefaultResolver(); var controlPlaceholder = new EditingFormControl(); foreach (var fieldInfo in formInfo.ItemsList.OfType <FormFieldInfo>()) { mContextResolver.SetNamedSourceData(fieldInfo.Name, controlPlaceholder); } return(mContextResolver); }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // Alter username according to GetFormattedUserName function if ((formElem != null) && (formElem.FieldEditingControls != null)) { EditingFormControl userControl = formElem.FieldEditingControls["UserName"] as EditingFormControl; if (userControl != null) { string userName = ValidationHelper.GetString(userControl.Value, String.Empty); // Set back formatted username userControl.Value = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true)); } } }
/// <summary> /// Handles OnLoad event of the UI form. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event argument</param> private void Control_Load(object sender, EventArgs e) { // Store edited site object in local variable siteInfo = Control.EditedObject as SiteInfo; // Set "(none)" special item value for Site default stylesheet field EditingFormControl efc = Control.FieldEditingControls["SiteDefaultStylesheetID"]; if (efc != null) { UniSelector uniSelector = ControlsHelper.GetChildControl(efc, typeof(UniSelector)) as UniSelector; if (uniSelector != null) { uniSelector.NoneRecordValue = "-1"; } } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (DefaultValueControlName.EqualsCSafe(TEXTAREA, StringComparison.InvariantCultureIgnoreCase)) { // Disable Tab key for large text area defaultValue.SetValue("enabletabkey", false); } // Set associated control IDs lblLabel.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtLabel.Controls); lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(defaultValue.Controls); lblExplanationText.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtExplanationText.Controls); lblTooltip.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtTooltip.Controls); RegisterStartupScripts(); }
/// <summary> /// PreRender. /// </summary> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ControlsHelper.RegisterPostbackControl(editProfileForm.SubmitButton); // Alter username according to GetFormattedUserName function if ((editProfileForm != null) && (editProfileForm.FieldEditingControls != null)) { EditingFormControl userControl = editProfileForm.FieldEditingControls["UserName"]; if (userControl != null) { string userName = ValidationHelper.GetString(userControl.Value, String.Empty); // Set back formatted username userControl.Value = HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, IsLiveSite)); } } }
/// <summary> /// Handles PreRender event of the UI form. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event argument</param> protected void EditForm_PreRender(object sender, EventArgs e) { // Disable text area of the code preview if (codePreviewDisplayed) { // If UseCheckinCheckout is enabled there needs to run EnableByLockState before disabling code preview if (SynchronizationHelper.UseCheckinCheckout) { EditForm.EnableByLockState(); EditForm.EnabledByLockState = false; } EditingFormControl efc = EditForm.FieldEditingControls["StylesheetText"]; if (efc != null) { efc.Enabled = false; } } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); lblErrorMessage.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtErrorMessage.NestedControl.Controls); }
/// <summary> /// Save subscriber. /// </summary> /// <returns>Subscriber info object</returns> private SubscriberInfo SaveSubscriber() { string emailValue = null; int currentSiteId = SiteContext.CurrentSiteID; // Check if a subscriber exists first SubscriberInfo sb = null; if (AllowUserSubscribers && isAuthenticated) { // Try to get user subscriber sb = SubscriberInfoProvider.GetSubscriberInfo(UserInfo.OBJECT_TYPE, CurrentUser.UserID, currentSiteId); } else { EditingFormControl txtEmail = formElem.FieldEditingControls["SubscriberEmail"] as EditingFormControl; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } if (!string.IsNullOrEmpty(emailValue)) { // Try to get subscriber by email address sb = SubscriberInfoProvider.GetSubscriberInfo(emailValue, currentSiteId); } } if ((sb == null) || (chooseMode)) { // Create subscriber if (sb == null) { if (formElem.Visible) { int formSiteId = formElem.Data.GetValue("SubscriberSiteID").ToInteger(0); if (formSiteId == 0) { // Specify SiteID for the new subscriber formElem.Data.SetValue("SubscriberSiteID", currentSiteId); } // Save form with new subscriber data if (!formElem.Save()) { return(null); } // Get subscriber info from form sb = (SubscriberInfo)formElem.Info; } else { sb = new SubscriberInfo(); } } // Handle authenticated user if (AllowUserSubscribers && isAuthenticated) { // Get user info and copy first name, last name or full name to new subscriber // if these properties were not set UserInfo ui = UserInfoProvider.GetUserInfo(CurrentUser.UserID); if (ui != null) { if (!DataHelper.IsEmpty(ui.FirstName) && !DataHelper.IsEmpty(ui.LastName)) { if (string.IsNullOrEmpty(sb.SubscriberFirstName)) { sb.SubscriberFirstName = ui.FirstName; } if (string.IsNullOrEmpty(sb.SubscriberLastName)) { sb.SubscriberLastName = ui.LastName; } } else { if (string.IsNullOrEmpty(sb.SubscriberFirstName)) { sb.SubscriberFirstName = ui.FullName; } } // Full name consists of "user " and user full name sb.SubscriberFullName = new SubscriberFullNameFormater().GetUserSubscriberName(ui.FullName); if (!string.IsNullOrEmpty(sb.SubscriberEmail) && string.IsNullOrEmpty(ui.Email)) { // Update user email if it was not set ui.Email = sb.SubscriberEmail; UserInfoProvider.SetUserInfo(ui); // Reset email for user subscriber sb.SubscriberEmail = null; } } else { return(null); } sb.SubscriberType = UserInfo.OBJECT_TYPE; sb.SubscriberRelatedID = ui.UserID; } // Work with non-authenticated user else { if (string.IsNullOrEmpty(sb.SubscriberFullName)) { // Fill full name if it was not set via the form sb.SubscriberFullName = (sb.SubscriberFirstName + " " + sb.SubscriberLastName).Trim(); } } // Set site ID sb.SubscriberSiteID = SiteContext.CurrentSiteID; // Insert or update subscriber info SubscriberInfoProvider.SetSubscriberInfo(sb); // Check subscriber limits if (!SubscriberInfoProvider.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Subscribers, ObjectActionEnum.Insert)) { // Remove created subscriber and display error message SubscriberInfoProvider.DeleteSubscriberInfo(sb); lblError.Visible = true; lblError.Text = GetString("LicenseVersionCheck.Subscribers"); return(null); } } if (sb != null) { // Create membership between current contact and subscriber ModuleCommands.OnlineMarketingCreateRelation(sb.SubscriberID, MembershipType.NEWSLETTER_SUBSCRIBER, ModuleCommands.OnlineMarketingGetCurrentContactID()); } // Return subscriber info object return(sb); }
/// <summary> /// Show default value control and required control according to attribute type. /// </summary> public void ShowDefaultControl() { plcDefaultValue.Visible = true; SetFieldForTranslations(); SetReferenceToField(); HandleRequiredVisiblity(); switch (AttributeType) { case FieldDataType.DateTime: case FieldDataType.Date: { datetimeDefaultValue.Visible = true; chkDefaultValue.Visible = false; rbDefaultValue.Visible = false; txtLargeDefaultValue.Visible = false; txtDefaultValue.Visible = false; var calendarControl = ((FormEngineUserControl)datetimeDefaultValue.NestedControl); lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(calendarControl.Controls); } break; case FieldDataType.Boolean: { bool showRb = (AllowEmpty && SystemContext.DevelopmentMode); chkDefaultValue.Visible = !showRb; rbDefaultValue.Visible = showRb; txtLargeDefaultValue.Visible = false; txtDefaultValue.Visible = false; datetimeDefaultValue.Visible = false; lblDefaultValue.AssociatedControlClientID = showRb ? EditingFormControl.GetInputClientID(rbDefaultValue.NestedControl.Controls) : EditingFormControl.GetInputClientID(chkDefaultValue.NestedControl.Controls); } break; case FieldDataType.LongText: { txtLargeDefaultValue.Visible = true; chkDefaultValue.Visible = false; rbDefaultValue.Visible = false; txtDefaultValue.Visible = false; datetimeDefaultValue.Visible = false; lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtLargeDefaultValue.NestedControl.Controls); } break; case FieldDataType.Binary: plcDefaultValue.Visible = false; break; case FieldDataType.File: case FieldDataType.DocAttachments: // Hide default value for File and Document attachment fields within Document types if ((Mode == FieldEditorModeEnum.ClassFormDefinition) || (Mode == FieldEditorModeEnum.AlternativeClassFormDefinition)) { plcDefaultValue.Visible = false; } // Display textbox otherwise else { txtDefaultValue.Visible = true; chkDefaultValue.Visible = false; rbDefaultValue.Visible = false; txtLargeDefaultValue.Visible = false; datetimeDefaultValue.Visible = false; lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtDefaultValue.NestedControl.Controls); } break; default: { txtDefaultValue.Visible = true; chkDefaultValue.Visible = false; rbDefaultValue.Visible = false; txtLargeDefaultValue.Visible = false; datetimeDefaultValue.Visible = false; lblDefaultValue.AssociatedControlClientID = EditingFormControl.GetInputClientID(txtDefaultValue.NestedControl.Controls); } break; } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> private void btnRegister_Click(object sender, EventArgs e) { if ((PageManager.ViewMode == ViewModeEnum.Design) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.Registration)) { lblError.Visible = true; lblError.Text = GetString("banip.ipisbannedregistration"); return; } // Check if captcha is required if (DisplayCaptcha) { // Verify captcha text if (!captchaElem.IsValid()) { // Display error message if captcha text is not valid lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.captchaError"); return; } else { // Generate new code and clear captcha textbox if cpatcha code is valid captchaElem.GenerateNew(); } } string userName = String.Empty; string nickName = String.Empty; string firstName = String.Empty; string lastName = String.Empty; string emailValue = String.Empty; // Check duplicate user // 1. Find appropriate control and get its value (i.e. user name) // 2. Try to find user info EditingFormControl txtUserName = formUser.BasicForm.FieldEditingControls["UserName"] as EditingFormControl; if (txtUserName != null) { userName = ValidationHelper.GetString(txtUserName.Value, String.Empty); } EditingFormControl txtEmail = formUser.BasicForm.FieldEditingControls["Email"] as EditingFormControl; if (txtEmail != null) { emailValue = ValidationHelper.GetString(txtEmail.Value, String.Empty); } // If user name and e-mail aren't filled stop processing and display error. if (string.IsNullOrEmpty(userName)) { userName = emailValue; if (String.IsNullOrEmpty(emailValue)) { formUser.StopProcessing = true; lblError.Visible = true; lblError.Text = GetString("customregistrationform.usernameandemail"); return; } else { formUser.BasicForm.Data.SetValue("UserName", userName); } } EditingFormControl txtNickName = formUser.BasicForm.FieldEditingControls["UserNickName"] as EditingFormControl; if (txtNickName != null) { nickName = ValidationHelper.GetString(txtNickName.Value, String.Empty); } EditingFormControl txtFirstName = formUser.BasicForm.FieldEditingControls["FirstName"] as EditingFormControl; if (txtFirstName != null) { firstName = ValidationHelper.GetString(txtFirstName.Value, String.Empty); } EditingFormControl txtLastName = formUser.BasicForm.FieldEditingControls["LastName"] as EditingFormControl; if (txtLastName != null) { lastName = ValidationHelper.GetString(txtLastName.Value, String.Empty); } // Test if "global" or "site" user exists. SiteInfo si = CMSContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, si)); if ((UserInfoProvider.GetUserInfo(userName) != null) || (siteui != null)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, userName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(userName, true))); return; } if (UserInfoProvider.NameIsReserved(CMSContext.CurrentSiteName, nickName)) { lblError.Visible = true; lblError.Text = GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(nickName)); return; } // Check limitations for site members if (!UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.SiteMembers, VersionActionEnum.Insert, false)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedSiteMember"); return; } // Check whether email is unique if it is required string checkSites = (String.IsNullOrEmpty(AssignToSites)) ? CMSContext.CurrentSiteName : AssignToSites; if (!UserInfoProvider.IsEmailUnique(emailValue, checkSites, 0)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } // Validate and save form with new user data if (!formUser.Save()) { // Return if saving failed return; } // Get user info from form UserInfo ui = (UserInfo)formUser.Info; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(userName, si); } ui.PreferredCultureCode = ""; ui.Enabled = EnableUserAfterRegistration; ui.IsEditor = false; ui.IsGlobalAdministrator = false; ui.UserURLReferrer = CMSContext.CurrentUser.URLReferrer; ui.UserCampaign = CMSContext.Campaign; // Fill optionally full user name if (String.IsNullOrEmpty(ui.FullName)) { ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName); } // Ensure nick name if (ui.UserNickName.Trim() == "") { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = HTTPHelper.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowSplashScreen = true; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSRegistrationAdministratorApproval"); if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is reqiures if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overrided by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = CMSContext.ResolveCurrentPath(StartingAliasPath); } // Get user password and save it in apropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); // Prepare macro data source for email resolver UserInfo userForMail = ui.Clone(); userForMail.SetValue("UserPassword", string.Empty); object[] data = new object[1]; data[0] = userForMail; // Prepare resolver for notification and welcome emails ContextResolver resolver = CMSContext.CurrentResolver; resolver.SourceData = data; #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EventLogProvider ev = new EventLogProvider(); EmailTemplateInfo template = null; // Prepare macro replacements string[,] replacements = new string[6, 2]; replacements[0, 0] = "confirmaddress"; replacements[0, 1] = (ApprovalPage != String.Empty) ? URLHelper.GetAbsoluteUrl(ApprovalPage) + "?userguid=" + ui.UserGUID : URLHelper.GetAbsoluteUrl("~/CMSPages/Dialogs/UserRegistration.aspx") + "?userguid=" + ui.UserGUID; replacements[1, 0] = "username"; replacements[1, 1] = userName; replacements[2, 0] = "password"; replacements[2, 1] = password; replacements[3, 0] = "Email"; replacements[3, 1] = emailValue; replacements[4, 0] = "FirstName"; replacements[4, 1] = firstName; replacements[5, 0] = "LastName"; replacements[5, 1] = lastName; // Set resolver resolver.SourceParameters = replacements; // Email message EmailMessage emailMessage = new EmailMessage(); emailMessage.EmailFormat = EmailFormatEnum.Default; emailMessage.Recipients = ui.Email; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationConfirmationEmailSubject"); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationWaitingForApprovalSubject"); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", CMSContext.CurrentSiteName); emailMessage.Subject = GetString("RegistrationForm.RegistrationSubject"); } } if (template != null) { emailMessage.From = EmailHelper.GetSender(template, SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSNoreplyEmailAddress")); // Enable macro encoding for body resolver.EncodeResolvedValues = true; emailMessage.Body = resolver.ResolveMacros(template.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; emailMessage.PlainTextBody = resolver.ResolveMacros(template.TemplatePlainText); emailMessage.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(template, emailMessage.Subject)); emailMessage.CcRecipients = template.TemplateCc; emailMessage.BccRecipients = template.TemplateBcc; try { MetaFileInfoProvider.ResolveMetaFileImages(emailMessage, template.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); // Send the e-mail immediately EmailSender.SendEmail(CMSContext.CurrentSiteName, emailMessage, true); } catch (Exception ex) { ev.LogEvent("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { lblError.Visible = true; lblError.Text = GetString("RegistrationForm.UserWasNotCreated"); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and email confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate = null; if (requiresAdminApprove) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", CMSContext.CurrentSiteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", CMSContext.CurrentSiteName); } if (mEmailTemplate == null) { ev.LogEvent("E", DateTime.Now, "RegistrationForm", "GetEmailTemplate", HTTPHelper.GetAbsoluteUri()); } //email template ok else { replacements = new string[4, 2]; replacements[0, 0] = "firstname"; replacements[0, 1] = ui.FirstName; replacements[1, 0] = "lastname"; replacements[1, 1] = ui.LastName; replacements[2, 0] = "email"; replacements[2, 1] = ui.Email; replacements[3, 0] = "username"; replacements[3, 1] = userName; // Set resolver resolver.SourceParameters = replacements; // Enable macro encoding for body resolver.EncodeResolvedValues = true; EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Body = resolver.ResolveMacros(mEmailTemplate.TemplateText); // Disable macro encoding for plaintext body and subject resolver.EncodeResolvedValues = false; message.Subject = resolver.ResolveMacros(EmailHelper.GetSubject(mEmailTemplate, GetString("RegistrationForm.EmailSubject"))); message.PlainTextBody = resolver.ResolveMacros(mEmailTemplate.TemplatePlainText); message.CcRecipients = mEmailTemplate.TemplateCc; message.BccRecipients = mEmailTemplate.TemplateBcc; try { // Attach template meta-files to e-mail MetaFileInfoProvider.ResolveMetaFileImages(message, mEmailTemplate.TemplateID, EmailObjectType.EMAILTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE); EmailSender.SendEmail(CMSContext.CurrentSiteName, message); } catch { ev.LogEvent("E", DateTime.Now, "Membership", "RegistrationEmail", CMSContext.CurrentSite.SiteID); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { string siteName = CMSContext.CurrentSiteName; if (AnalyticsHelper.AnalyticsEnabled(siteName) && AnalyticsHelper.TrackConversionsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, HTTPHelper.UserHostAddress)) { HitLogProvider.LogConversions(siteName, CMSContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(CMSContext.CurrentSiteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { Activity activity = new ActivityRegistration(ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); if (activity.Data != null) { activity.Data.ContactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); activity.Log(); } // Log login activity if (ui.Enabled) { // Log activity int contactID = ModuleCommands.OnlineMarketingGetUserLoginContactID(ui); Activity activityLogin = new ActivityUserLogin(contactID, ui, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); activityLogin.Log(); } } #endregion #region "Site and roles addition and authentication" string[] roleList = AssignRoles.Split(';'); string[] siteList; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } else // If not set user current site { siteList = new string[] { CMSContext.CurrentSiteName }; } foreach (string siteName in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, siteName); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String sn = roleName.StartsWithCSafe(".") ? "" : siteName; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, sn)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, sn); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlRegForm.Visible = false; lblInfo.Visible = true; lblInfo.Text = DisplayMessage; } else { if (ui.Enabled) { CMSContext.AuthenticateUser(ui.UserName, true); } string returnUrl = QueryHelper.GetString("ReturnURL", ""); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWithCSafe("~") || returnUrl.StartsWithCSafe("/") || QueryHelper.ValidateHash("hash"))) { URLHelper.Redirect(HttpUtility.UrlDecode(returnUrl)); } else if (RedirectToURL != String.Empty) { URLHelper.Redirect(RedirectToURL); } } #endregion lblError.Visible = false; } }
/// <summary> /// Returns new instance of resolver for given class (includes all fields, etc.). /// </summary> /// <param name="formInfo">FormInfo</param> private static ContextResolver GetFormResolver(FormInfo formInfo) { ContextResolver mContextResolver = GetDefaultResolver(); var controlPlaceholder = new EditingFormControl(); foreach (var fieldInfo in formInfo.ItemsList.OfType<FormFieldInfo>()) { mContextResolver.SetNamedSourceData(fieldInfo.Name, controlPlaceholder); } return mContextResolver; }