Esempio n. 1
0
 public string ReplaceTokens(string s)
 {
     var tokenizer = new TokenReplace();
     tokenizer.AccessingUser = UserController.GetCurrentUserInfo();
     tokenizer.DebugMessages = false;
     return (tokenizer.ReplaceEnvironmentTokens(s));
 }
Esempio n. 2
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string strText = ShowText;
			
			//load resources
            if (!String.IsNullOrEmpty(ResourceKey))
            {
				//localization
                string strFile = Path.GetFileName(Server.MapPath(PortalSettings.ActiveTab.SkinSrc));
                strFile = PortalSettings.ActiveTab.SkinPath + Localization.LocalResourceDirectory + "/" + strFile;
                string strLocalization = Localization.GetString(ResourceKey, strFile);
                if (!String.IsNullOrEmpty(strLocalization))
                {
                    strText = strLocalization;
                }
            }
			
            //If no value is found then use the value set the the Text attribute
            if (string.IsNullOrEmpty(strText))
            {
                strText = ShowText;
            }
			
			//token replace
            if (ReplaceTokens)
            {
                var tr = new TokenReplace();
                tr.AccessingUser = PortalSettings.UserInfo;
                strText = tr.ReplaceEnvironmentTokens(strText);
            }
            lblText.Text = strText;
            if (!String.IsNullOrEmpty(CssClass))
            {
                lblText.CssClass = CssClass;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Display a preview of the message to be sent out
        /// </summary>
        /// <param name="sender">ignored</param>
        /// <param name="e">ignores</param>
        protected void OnPreviewClick(object sender, EventArgs e)
        {
            try
            {
                if (String.IsNullOrEmpty(txtSubject.Text) || String.IsNullOrEmpty(teMessage.Text))
                {
                    //no subject or message
                    var strResult = Localization.GetString("MessageValidation", LocalResourceFile);
                    const ModuleMessage.ModuleMessageType msgResult = ModuleMessage.ModuleMessageType.YellowWarning;
                    UI.Skins.Skin.AddModuleMessage(this, strResult, msgResult);
                    ((CDefault)Page).ScrollToControl(Page.Form);
                    return;
                }

                //convert links to absolute
                var strBody = ConvertToAbsoluteUrls(teMessage.Text);

                if (chkReplaceTokens.Checked)
                {
                    var objTr = new TokenReplace();
                    if (cboSendMethod.SelectedItem.Value == "TO")
                    {
                        objTr.User = UserInfo;
                        objTr.AccessingUser = UserInfo;
                        objTr.DebugMessages = true;
                    }
                    lblPreviewSubject.Text = objTr.ReplaceEnvironmentTokens(txtSubject.Text);
                    lblPreviewBody.Text = objTr.ReplaceEnvironmentTokens(strBody);
                }
                else
                {
                    lblPreviewSubject.Text = txtSubject.Text;
                    lblPreviewBody.Text = strBody;
                }
                pnlPreview.Visible = true;
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
Esempio n. 4
0
		/// -----------------------------------------------------------------------------
		/// <summary>
		///   FormatHtmlText formats HtmlText content for display in the browser
		/// </summary>
		/// <remarks>
		/// </remarks>
		/// <param name="moduleId">The ModuleID</param>
		/// <param name = "content">The HtmlText Content</param>
		/// <param name = "settings">A Hashtable of Module Settings</param>
		/// <param name="portalSettings">The Portal Settings.</param>
		/// <history>
		/// </history>
		/// -----------------------------------------------------------------------------
		public static string FormatHtmlText(int moduleId, string content, Hashtable settings, PortalSettings portalSettings)
		{
			// token replace
			bool blnReplaceTokens = false;
			if (!string.IsNullOrEmpty(Convert.ToString(settings["HtmlText_ReplaceTokens"])))
			{
				blnReplaceTokens = Convert.ToBoolean(settings["HtmlText_ReplaceTokens"]);
			}
			if (blnReplaceTokens)
			{
				var tr = new TokenReplace();
				tr.AccessingUser = UserController.GetCurrentUserInfo();
				tr.DebugMessages = portalSettings.UserMode != PortalSettings.Mode.View;
				tr.ModuleId = moduleId;
				tr.PortalSettings = portalSettings;
				content = tr.ReplaceEnvironmentTokens(content);
			}

			// Html decode content
			content = HttpUtility.HtmlDecode(content);

			// manage relative paths
			content = ManageRelativePaths(content, portalSettings.HomeDirectory, "src", portalSettings.PortalId);
			content = ManageRelativePaths(content, portalSettings.HomeDirectory, "background", portalSettings.PortalId);

			return content;
		}
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// Gets a SystemMessage passing extra custom parameters to personalize.
 /// </summary>
 /// <param name="strLanguage">A specific language to get the SystemMessage for.</param>
 /// <param name="portalSettings">The portal settings for the portal to which the message will affect.</param>
 /// <param name="messageName">The message tag which identifies the SystemMessage.</param>
 /// <param name="userInfo">Reference to the user used to personalize the message.</param>
 /// <param name="resourceFile">The root name of the Resource File where the localized
 ///   text can be found</param>
 /// <param name="customArray">An ArrayList with replacements for custom tags.</param>
 /// <param name="customDictionary">An IDictionary with replacements for custom tags.</param>
 /// <param name="customCaption">prefix for custom tags</param>
 /// <param name="accessingUserID">UserID of the user accessing the system message</param>
 /// <returns>The message body with all tags replaced.</returns>
 /// <remarks>
 /// Custom tags are of the form <b>[Custom:n]</b>, where <b>n</b> is the zero based index which 
 /// will be used to find the replacement value in <b>Custom</b> parameter.
 /// </remarks>
 /// <history>
 ///     [cnurse]    09/09/2009  created
 /// </history>
 /// -----------------------------------------------------------------------------
 public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList customArray,
                                       IDictionary customDictionary, string customCaption, int accessingUserID)
 {
     string strMessageValue = GetString(messageName, resourceFile, portalSettings, strLanguage);
     if (!String.IsNullOrEmpty(strMessageValue))
     {
         if (String.IsNullOrEmpty(customCaption))
         {
             customCaption = "Custom";
         }
         var objTokenReplace = new TokenReplace(Scope.SystemMessages, strLanguage, portalSettings, userInfo);
         if ((accessingUserID != -1) && (userInfo != null))
         {
             if (userInfo.UserID != accessingUserID)
             {
                 objTokenReplace.AccessingUser = UserController.Instance.GetUser(portalSettings.PortalId, accessingUserID);
             }
         }
         if (customArray != null)
         {
             strMessageValue = objTokenReplace.ReplaceEnvironmentTokens(strMessageValue, customArray, customCaption);
         }
         else
         {
             strMessageValue = objTokenReplace.ReplaceEnvironmentTokens(strMessageValue, customDictionary, customCaption);
         }
     }
     return strMessageValue;
 }
        protected override void Render(HtmlTextWriter writer)
        {
            if (ItemTemplate == "") return;

            writer.Write(HeaderTemplate);

            // Filters
            if (Filters == null) Filters = new Dictionary<string, string>();
            var additionalFilters = new Dictionary<string, string>();
            additionalFilters.Add("Records", PageSize.ToString());
            additionalFilters.Add("PageIndex", PageIndex.ToString());
            additionalFilters.Add("Rowsize", RowSize.ToString());
            additionalFilters.Add("SortBy", SortBy);
            additionalFilters.Add("SortAscending", SortAscending.ToString());

            // Currently Not Used by the SPROC
            var filterUser = Filters.ContainsKey("UserId") && Filters["UserId"] != null ? new UserInfo() { UserID = int.Parse(Filters["UserId"]) } : new UserInfo() { PortalID = _currentUser.PortalID };
            var role = Filters.ContainsKey("RoleId") && Filters["RoleId"] != null ? new UserRoleInfo() { RoleID = int.Parse(Filters["RoleId"]) } : null;
            var relationship = Filters.ContainsKey("RelationshipTypeId") && Filters["RelationshipTypeId"] != null ? new RelationshipType() { RelationshipTypeId = int.Parse(Filters["RelationshipTypeId"]) } : null;
            
            foreach (var filter in Filters.Where(filter => !additionalFilters.ContainsKey(filter.Key)))
            {
                additionalFilters.Add(filter.Key, filter.Value);
            }

            var row = 0;
            var users = new DataTable();

            //users.Load(_relationshipController.GetUsersAdvancedSearch(_currentUser, filterUser, role, relationship, Filters, additionalFilters));

            if (users.Rows.Count > 0)
            {
                foreach (DataRow user in users.Rows)
                {
                    //Row Header
                    writer.Write(string.IsNullOrEmpty(AlternatingRowHeaderTemplate) || row%2 == 0 ? RowHeaderTemplate : AlternatingRowHeaderTemplate);

                    var tokenReplace = new TokenReplace();
                    var tokenKeyValues = new Dictionary<string, string>();

                    foreach (var col in user.Table.Columns.Cast<DataColumn>().Where(col => !tokenKeyValues.ContainsKey(col.ColumnName)))
                    {
                        tokenKeyValues.Add(col.ColumnName, user[col.ColumnName].ToString());
                    }

                    var listItem = string.IsNullOrEmpty(AlternatingItemTemplate) || row%2 == 0 ? ItemTemplate : AlternatingItemTemplate;
                    listItem = tokenReplace.ReplaceEnvironmentTokens(listItem, tokenKeyValues, "Member");
                    writer.Write(listItem);

                    //Row Footer
                    writer.Write(string.IsNullOrEmpty(AlternatingRowFooterTemplate) || row%2 == 0 ? RowFooterTemplate : AlternatingRowFooterTemplate);

                    row++;
                }
            }

            writer.Write(FooterTemplate);
        }
Esempio n. 7
0
		/// <summary>
		///   Page_Load runs when the control is loaded
		/// </summary>
		/// <remarks>
		/// </remarks>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			try
			{
                if(Null.IsNull(ProfileUserId))
                {
                    Visible = false;
                    return;
                }

                var template = Convert.ToString(ModuleContext.Settings["ProfileTemplate"]);
                if(string.IsNullOrEmpty(template))
                {
                    template = Localization.GetString("DefaultTemplate", LocalResourceFile);
                }
			    var editUrl = Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=1");
                var profileUrl = Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=2");

                if (template.Contains("[BUTTON:EDITPROFILE]"))
                {
                    if (IncludeButton && IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnPrimaryAction\">{1}</a>", profileUrl, LocalizeString("Edit"));
                        template = template.Replace("[BUTTON:EDITPROFILE]", editHyperLink);
                    }
                    buttonPanel.Visible = false;
                }
                else
                {
                    buttonPanel.Visible = IncludeButton;
                    editLink.NavigateUrl = editUrl;
                }
                if (template.Contains("[HYPERLINK:EDITPROFILE]"))
                {
                    if (IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", profileUrl, LocalizeString("Edit"));
                        template = template.Replace("[HYPERLINK:EDITPROFILE]", editHyperLink);
                    }
                }
                if (template.Contains("[HYPERLINK:MYACCOUNT]"))
                {
                    if (IsUser)
                    {
                        string editHyperLink = String.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", editUrl, LocalizeString("MyAccount"));
                        template = template.Replace("[HYPERLINK:MYACCOUNT]", editHyperLink);
                    }
                    buttonPanel.Visible = false;
                }

                if (!IsUser && buttonPanel.Visible)
                {
                    buttonPanel.Visible = false;
                }

			    if (ProfileUser.Profile.ProfileProperties.Cast<ProfilePropertyDefinition>().Count(profProperty => profProperty.Visible) == 0)
                {
                    noPropertiesLabel.Visible = true;
                    profileOutput.Visible = false;
                }
                else
                {
                    var token = new TokenReplace { User = ProfileUser, AccessingUser = ModuleContext.PortalSettings.UserInfo };
                    profileOutput.InnerHtml = token.ReplaceEnvironmentTokens(template);
                    noPropertiesLabel.Visible = false;
                    profileOutput.Visible = true;
                }

			    var propertyAccess = new ProfilePropertyAccess(ProfileUser);
                var profileResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx";
                StringBuilder sb = new StringBuilder();
                bool propertyNotFound = false;

                foreach (ProfilePropertyDefinition property in ProfileUser.Profile.ProfileProperties)
                {
                    string value = propertyAccess.GetProperty(property.PropertyName,
                                                              String.Empty,
                                                              Thread.CurrentThread.CurrentUICulture,
                                                              ModuleContext.PortalSettings.UserInfo,
                                                              Scope.DefaultSettings,
                                                              ref propertyNotFound);


                    var clientName = Localization.GetSafeJSString(property.PropertyName);
                    sb.Append("self['" + clientName + "'] = ko.observable(");
                    sb.Append("\"");
                    value = Localization.GetSafeJSString(Server.HtmlDecode(value));
                    value = value.Replace("\r", string.Empty).Replace("\n",  " ");
                    sb.Append(value + "\"" + ");");
                    sb.Append('\n');
                    sb.Append("self['" + clientName + "Text'] = '");
                    sb.Append(clientName + "';");
                    sb.Append('\n');
                }

			    string email = (ProfileUserId == ModuleContext.PortalSettings.UserId
			                    || ModuleContext.PortalSettings.UserInfo.IsInRole(ModuleContext.PortalSettings.AdministratorRoleName))
			                       ? ProfileUser.Email
			                       : String.Empty;

                sb.Append("self.Email = ko.observable('");
                sb.Append(email + "');");
                sb.Append('\n');
                sb.Append("self.EmailText = '");
                sb.Append(LocalizeString("Email") + "';");
                sb.Append('\n');


                ProfileProperties = sb.ToString();


			}
			catch (Exception exc)
			{
				//Module failed to load
				Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
        public string ReplaceTokens(string Template, HangoutInfo Hangout, PortalSettings Settings, int ModuleId, string LocalResourceFile)
        {
            var cachedTemplate = DataCache.GetCache(string.Format(TEMPLATE_CACHE_KEY_FORMAT, Hangout.ContentItemId));

            // check for a cached template first
            if (cachedTemplate != null)
            {
                return cachedTemplate.ToString();
            }

            /*
            * workaround for the JSON deserializer bug in DNN's NewtonSoft
            */
            Hangout.StartDate = Hangout.StartDate.AddHours(-7);

            // begin replacing tokens
            Template = Regex.Replace(Template, TOKEN_TITLE, Hangout.Title);
            Template = Regex.Replace(Template, TOKEN_ADDRESS, Hangout.HangoutAddress);
            Template = Regex.Replace(Template, TOKEN_DESCRIPTION, HttpUtility.HtmlDecode(Hangout.Description));
            Template = Regex.Replace(Template, TOKEN_DURATION, Hangout.Duration.ToString());
            Template = Regex.Replace(Template, TOKEN_STARTDATE, Hangout.StartDate.ToString("MM/dd/yyyy hh:mm tt")); // todo: make this a setting

            if (Hangout.DurationUnits == DurationType.Minutes)
            {
                Template = Regex.Replace(Template, TOKEN_DURATIONUNITS, Localization.GetString("Minutes.Text", LocalResourceFile));
            }
            else
            {
                if (Hangout.Duration > 1)
                {
                    Template = Regex.Replace(Template, TOKEN_DURATIONUNITS, Localization.GetString("Hours.Text", LocalResourceFile));
                }
                else
                {
                    Template = Regex.Replace(Template, TOKEN_DURATIONUNITS, Localization.GetString("Hour.Text", LocalResourceFile));
                }
            }

            var tr = new TokenReplace();

            tr.AccessingUser = UserController.GetCurrentUserInfo();
            tr.DebugMessages = Settings.UserMode != PortalSettings.Mode.View;
            tr.ModuleId = ModuleId;
            tr.PortalSettings = Settings;

            // replace DNN tokens
            var template = tr.ReplaceEnvironmentTokens(Template);

            // cache the template
            DataCache.SetCache(string.Format(TEMPLATE_CACHE_KEY_FORMAT, Hangout.ContentItemId), template, DateTime.Now.AddMinutes(10));

            return template;
        }
        private void BindData()
        {
            var user = UserController.GetCurrentUserInfo();
            var tok = new TokenReplace(Scope.DefaultSettings, user.Profile.PreferredLocale, PortalSettings, user);

            var template = tok.ReplaceEnvironmentTokens(GetLocalizedString("Persona.Template", FeatureController.RESOURCEFILE_PERSONA));

            phTemplate.Controls.Add(new LiteralControl(template));
        }
        private string GeneratePersonaMarkup(IEnumerable<UserInfo> users)
        {
            var userTemplate = GetLocalizedString("Head.Template", FeatureController.RESOURCEFILE_PERSONA_SWITCH);
            var sb = new StringBuilder();

            foreach (UserInfo user in users.OrderBy(x => x.DisplayName))
            {
                // perform core token replace
                if (user.UserID != UserId)
                {
                    var userToken = new TokenReplace(Scope.DefaultSettings, user.Profile.PreferredLocale, PortalSettings, user);
                    sb.Append(userToken.ReplaceEnvironmentTokens(userTemplate));
                }
            }

            return sb.ToString();
        }
        private string GenerateScriptMarkup(TokenReplace tok, IEnumerable<UserInfo> users)
        {
            var scriptTemplate = GetLocalizedString("Script.Template", FeatureController.RESOURCEFILE_PERSONA_SWITCH);
            var userScriptTemplate = GetLocalizedString("ScriptItem.Template", FeatureController.RESOURCEFILE_PERSONA_SWITCH);
            var sbUserScript = new StringBuilder();
            var sec = new PortalSecurity();

            // create the user avatar listing
            foreach (UserInfo user in users)
            {
                /*
                 * $('.dpc[User:UserId]')
                 *      .css('background', 'url([Profile:Photo]) no-repeat')
                 *      .css('background-position', 'center center')
                 *      .attr('title', '[User:DisplayName]')
                 *      .click(function(){ window.location = '[DemoPersona:Login]'; })
                 *      .hover(function (){ $(this).css('opacity', '1.0'); }, function (){ $(this).css('opacity', '0.5'); });
                 */
                if (user.UserID != UserId)
                {
                    var userKeyForCookie = sec.EncryptString(user.UserID.ToString(), PortalSettings.GUID.ToString());
                    var userKeyForUrl = HttpUtility.UrlEncode(userKeyForCookie);
                    var newUrl = Globals.NavigateURL(PortalSettings.ActiveTab.TabID,
                        string.Empty,
                        string.Concat(FeatureController.QS_LOGINID, "=", userKeyForUrl));

                    // executing this line of code breaks the JS, removing the BG images
                    var alteredTemplate = userScriptTemplate.Replace(FeatureController.TOKEN_LOGIN, newUrl);

                    // work around for a HTTP 301 redirect issue on homepages in DNN 07.01.00
                    // https://dnntracker.atlassian.net/browse/CONTENT-1561
                    alteredTemplate = alteredTemplate.Replace(FeatureController.TOKEN_COOKIE_NAME, FeatureController.QS_LOGINID);
                    alteredTemplate = alteredTemplate.Replace(FeatureController.TOKEN_COOKIE_VALUE, userKeyForCookie);

                    var userToken = new TokenReplace(Scope.DefaultSettings, user.Profile.PreferredLocale, PortalSettings, user);
                    alteredTemplate = userToken.ReplaceEnvironmentTokens(alteredTemplate);
                    sbUserScript.Append(alteredTemplate);
                }
            }

            // insert the persona scripts
            scriptTemplate = scriptTemplate.Replace(FeatureController.TOKEN_SCRIPT, sbUserScript.ToString());

            // perform core token replace
            scriptTemplate = tok.ReplaceEnvironmentTokens(scriptTemplate);

            return scriptTemplate;
        }
        private void BindData()
        {
            // we are expecting one or more security roles specified and delimited by commas, but...
            // set a default security role, if one or more aren't specified
            if (string.IsNullOrEmpty(SecurityRoles))
            {
                SecurityRoles = "Registered Users";
                _SecurityRoleSet = false;
            }
            else
            {
                _SecurityRoleSet = true;
            }

            // grab the users
            var superusers = from u in UserController.GetUsers(false, true, -1).Cast<UserInfo>().ToList()
                             select u;
            var users = from u in UserController.GetUsers(PortalSettings.PortalId).Cast<UserInfo>().ToList()
                        where u.IsDeleted == false && u.Roles.Any(s => s == SecurityRoles)
                        select u;
            if (!_SecurityRoleSet || IncludeSuperusers) users = users.Concat(superusers);

            var user = UserController.GetCurrentUserInfo();
            UserId = user.UserID;
            var tok = new TokenReplace(Scope.DefaultSettings, user.Profile.PreferredLocale, PortalSettings, user);
            var template = GetLocalizedString("Persona.Template", FeatureController.RESOURCEFILE_PERSONA_SWITCH);

            // build the persona switch content to use for replacement
            var personaSwitchList = GeneratePersonaMarkup(users);

            // replace the switch token
            template = template.Replace(FeatureController.TOKEN_SWITCH, personaSwitchList);

            // perform core token replace
            template = tok.ReplaceEnvironmentTokens(template);

            // add the html to the view
            phTemplate.Controls.Add(new LiteralControl(template));

            // inject jquery for the background images
            litScript.Text = GenerateScriptMarkup(tok, users);
        }
Esempio n. 13
0
        public override string RenderTemplate(IEnumerable<AnnouncementInfo> announcements, bool editEnabled)
        {
            var output = new StringBuilder();


            TokenReplace dnnTokenReplace = null;
            if (TokenReplaceNeeded)
            {
                dnnTokenReplace = new TokenReplace(Scope.DefaultSettings, CultureInfo.CurrentCulture.Name, PortalSettings, PortalSettings.UserInfo);
            }
            bool altItemTemplateAvailable = !(string.IsNullOrEmpty(AltItemTemplate));
            if (dnnTokenReplace != null)
            {
                output.Append(dnnTokenReplace.ReplaceEnvironmentTokens(HeaderTemplate));
            }
            int counter = 0;
            var tokenReplace = new AnnouncementsTokenReplace();
            var announcementInfos = announcements as IList<AnnouncementInfo> ?? announcements.ToList();
            foreach (var announcement in announcementInfos)
            {
                //we have to pass IsEditable to the announcement, because it is used to draw the edit icon
                announcement.IsEditable = editEnabled;

                //Create a Token Replace and replace the tokens for this template
                tokenReplace.SetPropertySource(announcement);
                if ((counter % 2 == 0) | (!altItemTemplateAvailable))
                {
                    output.Append(tokenReplace.ReplaceAnnouncmentTokens(ItemTemplate));
                }
                else
                {
                    output.Append(tokenReplace.ReplaceAnnouncmentTokens(AltItemTemplate));
                }
                if ((dnnTokenReplace != null) && (counter < announcementInfos.Count() - 1))
                {
                    output.Append(dnnTokenReplace.ReplaceEnvironmentTokens(Separator));
                }
                counter += 1;

            }
            if (dnnTokenReplace != null)
            {
                output.Append(dnnTokenReplace.ReplaceEnvironmentTokens(FooterTemplate));
            }

            return output.ToString();
        }
        /// <summary>Send bulkmail to all recipients according to settings</summary>
        /// <returns>Number of emails sent, null.integer if not determinable</returns>
        /// <remarks>Detailed status report is sent by email to sending user</remarks>
        public int SendMails()
        {
            EnsureNotDisposed();
            
            int recipients = 0;
            int messagesSent = 0;
            int errors = 0;
            
            try
            {
				//send to recipients
                string body = _body;
                if (BodyFormat == MailFormat.Html) //Add Base Href for any images inserted in to the email.
                {
                    var host = PortalAlias.Contains("/") ? PortalAlias.Substring(0, PortalAlias.IndexOf('/')) : PortalAlias;
                    body = "<html><head><base href='http://" + host + "'><title>" + Subject + "</title></head><body>" + body + "</body></html>";
                }
                string subject = Subject;
                string startedAt = DateTime.Now.ToString(CultureInfo.InvariantCulture);

                bool replaceTokens = !SuppressTokenReplace && (_tokenReplace.ContainsTokens(Subject) || _tokenReplace.ContainsTokens(_body));
                bool individualSubj = false;
                bool individualBody = false;

                var mailErrors = new StringBuilder();
                var mailRecipients = new StringBuilder();
				
                switch (AddressMethod)
                {
                    case AddressMethods.Send_TO:
                    case AddressMethods.Send_Relay:
                        //optimization:
                        if (replaceTokens)
                        {
                            individualBody = (_tokenReplace.Cacheability(_body) == CacheLevel.notCacheable);
                            individualSubj = (_tokenReplace.Cacheability(Subject) == CacheLevel.notCacheable);
                            if (!individualBody)
                            {
                                body = _tokenReplace.ReplaceEnvironmentTokens(body);
                            }
                            if (!individualSubj)
                            {
                                subject = _tokenReplace.ReplaceEnvironmentTokens(subject);
                            }
                        }
                        foreach (UserInfo user in Recipients())
                        {
                            recipients += 1;
                            if (individualBody || individualSubj)
                            {
                                _tokenReplace.User = user;
                                _tokenReplace.AccessingUser = user;
                                if (individualBody)
                                {
                                    body = _tokenReplace.ReplaceEnvironmentTokens(_body);
                                }
                                if (individualSubj)
                                {
                                    subject = _tokenReplace.ReplaceEnvironmentTokens(Subject);
                                }
                            }
                            string recipient = AddressMethod == AddressMethods.Send_TO ? user.Email : RelayEmailAddress;

                            string mailError = Mail.SendMail(_sendingUser.Email,
                                                                recipient,
                                                                "",
                                                                "",
                                                                ReplyTo.Email,
                                                                Priority,
                                                                subject,
                                                                BodyFormat,
                                                                Encoding.UTF8,
                                                                body,
																LoadAttachments(),
                                                                _smtpServer,
                                                                _smtpAuthenticationMethod,
                                                                _smtpUsername,
                                                                _smtpPassword,
                                                                _smtpEnableSSL);
                            if (!string.IsNullOrEmpty(mailError))
                            {
                                mailErrors.Append(mailError);
                                mailErrors.AppendLine();
                                errors += 1;
                            }
                            else
                            {
                                mailRecipients.Append(user.Email);
                                mailRecipients.Append(BodyFormat == MailFormat.Html ? "<br />" : Environment.NewLine);
                                messagesSent += 1;
                            }
                        }

                        break;
                    case AddressMethods.Send_BCC:
                        var distributionList = new StringBuilder();
                        messagesSent = Null.NullInteger;
                        foreach (UserInfo user in Recipients())
                        {
                            recipients += 1;
                            distributionList.Append(user.Email + "; ");
                            mailRecipients.Append(user.Email);
                            mailRecipients.Append(BodyFormat == MailFormat.Html ? "<br />" : Environment.NewLine);
                        }

                        if (distributionList.Length > 2)
                        {
                            if (replaceTokens)
                            {
								//no access to User properties possible!
                                var tr = new TokenReplace(Scope.Configuration);
                                body = tr.ReplaceEnvironmentTokens(_body);
                                subject = tr.ReplaceEnvironmentTokens(Subject);
                            }
                            else
                            {
                                body = _body;
                                subject = Subject;
                            }
                            string mailError = Mail.SendMail(_sendingUser.Email,
                                                       _sendingUser.Email,
                                                       "",
                                                       distributionList.ToString(0, distributionList.Length - 2),
                                                       ReplyTo.Email,
                                                       Priority,
                                                       subject,
                                                       BodyFormat,
                                                       Encoding.UTF8,
                                                       body,
													   LoadAttachments(),
                                                       _smtpServer,
                                                       _smtpAuthenticationMethod,
                                                       _smtpUsername,
                                                       _smtpPassword,
                                                       _smtpEnableSSL);
                            if (mailError == string.Empty)
                            {
                                messagesSent = 1;
                            }
                            else
                            {
                                mailErrors.Append(mailError);
                                errors += 1;
                            }
                        }
                        break;
                }
                if (mailErrors.Length > 0)
                {
                    mailRecipients = new StringBuilder();
                }
                SendConfirmationMail(recipients, messagesSent, errors, subject, startedAt, mailErrors.ToString(), mailRecipients.ToString());
            }
            catch (Exception exc) //send mail failure
            {
                Logger.Error(exc);

                Debug.Write(exc.Message);
            }
            finally
            {
				foreach (var attachment in _attachments)
				{
					attachment.Dispose();
				}
            }
            return messagesSent;
        }
 /// <summary>internal method to initialize used objects, depending on parameters of construct method</summary>
 private void Initialize()
 {
     _portalSettings = PortalController.GetCurrentPortalSettings();
     PortalAlias = _portalSettings.PortalAlias.HTTPAlias;
     SendingUser = (UserInfo) HttpContext.Current.Items["UserInfo"];
     _tokenReplace = new TokenReplace();
     _confirmBodyHTML = Localization.Localization.GetString("EMAIL_BulkMailConf_Html_Body", Localization.Localization.GlobalResourceFile, _strSenderLanguage);
     _confirmBodyText = Localization.Localization.GetString("EMAIL_BulkMailConf_Text_Body", Localization.Localization.GlobalResourceFile, _strSenderLanguage);
     _confirmSubject = Localization.Localization.GetString("EMAIL_BulkMailConf_Subject", Localization.Localization.GlobalResourceFile, _strSenderLanguage);
     _noError = Localization.Localization.GetString("NoErrorsSending", Localization.Localization.GlobalResourceFile, _strSenderLanguage);
     _smtpEnableSSL = Host.EnableSMTPSSL;
 }
        /// <summary>
        ///   Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        ///   [jlucarino]	02/25/2010 created
        /// </history>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                if (ModuleContext.TabId != ModuleContext.PortalSettings.UserTabId)
                {
                    UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ModuleNotIntended", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                }
                else
                {
                    if (ProfileUserId == Null.NullInteger)
                    {
                        //Clicked on breadcrumb - don't know which user
                        Response.Redirect(Request.IsAuthenticated ? Globals.UserProfileURL(ModuleContext.PortalSettings.UserId) : GetRedirectUrl(), true);
                    }
                    else
                    {
                        var oUser = UserController.GetUserById(ModuleContext.PortalId, ProfileUserId);

                        if (!IsUser)
                        {
                            hlEdit.Visible = false;
                        }

                        hlEdit.NavigateUrl = Globals.NavigateURL(ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + ProfileUserId, "pageno=3");

                        var properties = oUser.Profile.ProfileProperties;
                        var visibleCount = 0;

                        //loop through properties to see if any are set to visible
                        foreach (ProfilePropertyDefinition profProperty in properties)
                        {
                            if (profProperty.Visible)
                            {
                                //Check Visibility
                                if (profProperty.Visibility == UserVisibilityMode.AdminOnly)
                                {
                                    //Only Visible if Admin (or self)
                                    profProperty.Visible = (IsAdmin || IsUser);
                                }
                                else if (profProperty.Visibility == UserVisibilityMode.MembersOnly)
                                {
                                    //Only Visible if Is a Member (ie Authenticated)
                                    profProperty.Visible = Request.IsAuthenticated;
                                }
                            }
                            if (profProperty.Visible)
                            {
                                visibleCount += 1;
                            }
                        }

                        if (visibleCount == 0)
                        {
                            lblNoProperties.Visible = true;
                        }
                        else
                        {
                            var template = "";
                            var oToken = new TokenReplace {User = oUser, AccessingUser = ModuleContext.PortalSettings.UserInfo};

                            template = (ModuleContext.Settings["ProfileTemplate"] != null) ? Convert.ToString(ModuleContext.Settings["ProfileTemplate"]) : Localization.GetString("DefaultTemplate", LocalResourceFile);

                            ProfileOutput.Text = oToken.ReplaceEnvironmentTokens(template);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                //Module failed to load
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }