/// <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">Module Settings</param>
        /// <param name="portalSettings">The Portal Settings.</param>
        /// <param name="page">The Page Instance.</param>
        public static string FormatHtmlText(int moduleId, string content, HtmlModuleSettings settings, PortalSettings portalSettings, Page page)
        {
            // token replace

            if (settings.ReplaceTokens)
            {
                //var tr = new HtmlTokenReplace(page)  //DNN 7.x not support
                var tr = new TokenReplace()
                {
                    AccessingUser  = UserController.Instance.GetCurrentUserInfo(),
                    DebugMessages  = portalSettings.UserMode != PortalSettings.Mode.View,
                    ModuleId       = moduleId,
                    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);
        }
예제 #2
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.Instance.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);
        }
예제 #3
0
        /// <inheritdoc/>
        public override string Tokenize(string content, TokenContext context)
        {
            var tokenizer = new TokenReplace {
                TokenContext = context
            };

            return(tokenizer.ReplaceEnvironmentTokens(content));
        }
예제 #4
0
        public string ReplaceTokens(string s)
        {
            var tokenizer = new TokenReplace();

            tokenizer.AccessingUser = UserController.Instance.GetCurrentUserInfo();
            tokenizer.DebugMessages = false;
            return(tokenizer.ReplaceEnvironmentTokens(s));
        }
예제 #5
0
        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));
        }
        /// <summary>
        /// Display a preview of the message to be sent out
        /// </summary>
        /// <param name="sender">ignored</param>
        /// <param name="e">ignores</param>
        /// <history>
        ///     [vmasanas]	2007-09-07  added
        /// </history>
        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 = teMessage.Text;
                const string pattern = "<(a|link|img|script|object).[^>]*(href|src|action)=(\\\"|'|)(?<url>(.[^\\\"']*))(\\\"|'|)[^>]*>";
                strBody = Regex.Replace(strBody, pattern, FormatUrls);

                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);
            }
        }
예제 #7
0
        public void ObjectInputIsReturnedBlank(string sourceText)
        {
            // Arrange
            var tokenReplace = new TokenReplace(Scope.DefaultSettings, PortalSettings.Current.DefaultLanguage,
                                                PortalSettings.Current, UserController.Instance.GetUser(1, 1), 1);

            // Act
            var outputText = tokenReplace.ReplaceEnvironmentTokens(sourceText);

            // Assert
            Assert.AreEqual(outputText.Trim(), string.Empty);
        }
        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);
        }
예제 #9
0
        /// <summary>Send bulkmail confirmation to admin</summary>
        /// <param name="numRecipients">number of email recipients</param>
        /// <param name="numMessages">number of messages sent, -1 if not determinable</param>
        /// <param name="numErrors">number of emails not sent</param>
        /// <param name="subject">Subject of BulkMail sent (to be used as reference)</param>
        /// <param name="startedAt">date/time, sendout started</param>
        /// <param name="mailErrors">mail error texts</param>
        /// <param name="recipientList">List of recipients as formatted string</param>
        /// <remarks></remarks>
        private void SendConfirmationMail(int numRecipients, int numMessages, int numErrors, string subject, string startedAt, string mailErrors, string recipientList)
		{
            //send confirmation, use resource string like:
        	//Operation started at: [Custom:0]<br>
            //EmailRecipients:      [Custom:1]<b
            //EmailMessages sent:   [Custom:2]<br>
            //Operation Completed:  [Custom:3]<br>
            //Number of Errors:     [Custom:4]<br>
            //Error Report:<br>
            //[Custom:5]
            //--------------------------------------
            //Recipients:
            //[custom:6]
            var parameters = new ArrayList
                                 {
                                     startedAt,
                                     numRecipients.ToString(CultureInfo.InvariantCulture),
                                     numMessages >= 0 ? numMessages.ToString(CultureInfo.InvariantCulture) : "***",
                                     DateTime.Now.ToString(CultureInfo.InvariantCulture),
                                     numErrors > 0 ? numErrors.ToString(CultureInfo.InvariantCulture) : "",
                                     mailErrors != string.Empty ? mailErrors : _noError,
                                     ReportRecipients ? recipientList : ""
                                 };
            _tokenReplace.User = _sendingUser;
            string body = _tokenReplace.ReplaceEnvironmentTokens(BodyFormat == MailFormat.Html ? _confirmBodyHTML : _confirmBodyText, parameters, "Custom");
            string strSubject = string.Format(_confirmSubject, subject);
            if (!SuppressTokenReplace)
            {
                strSubject = _tokenReplace.ReplaceEnvironmentTokens(strSubject);
            }
            var message = new Message {FromUserID = _sendingUser.UserID, ToUserID = _sendingUser.UserID, Subject = strSubject, Body = body, Status = MessageStatusType.Unread};

            Mail.SendEmail(_sendingUser.Email, _sendingUser.Email, message.Subject, message.Body);
        }
예제 #10
0
        public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript)
        {
            var tokenReplace = new TokenReplace {
                ModuleId = moduleId
            };

            foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows)
            {
                if (row[FieldsTableColumn.Type].ToString() == Name)
                {
                    var fieldId    = (int)row[FieldsTableColumn.Id];
                    var columnName = row[FieldsTableColumn.Title].ToString();
                    try
                    {
                        var typestring = row[FieldsTableColumn.InputSettings].AsString();
                        var expression = tokenReplace.ReplaceEnvironmentTokens(
                            row[FieldsTableColumn.Default].AsString("String"));

                        ds.Tables[DataSetTableName.Data].Columns.Remove(columnName);
                        var dc = new DataColumn(columnName, GetType(typestring));
                        ds.Tables[DataSetTableName.Data].Columns.Add(dc);
                        dc.Expression = expression;
                    }
                    catch (SyntaxErrorException ex)
                    {
                        ds.Tables[DataSetTableName.Data].Columns.Remove(columnName);
                        var dc = new DataColumn(columnName, typeof(string));
                        ds.Tables[DataSetTableName.Data].Columns.Add(dc);
                        ds.Tables[DataSetTableName.Data].Columns[columnName].Expression =
                            WarningMessage(ex.Message, moduleId);
                    }
                    catch (EvaluateException ex)
                    {
                        ds.Tables[DataSetTableName.Data].Columns.Remove(columnName);
                        var dc = new DataColumn(columnName, typeof(string));
                        ds.Tables[DataSetTableName.Data].Columns.Add(dc);
                        ds.Tables[DataSetTableName.Data].Columns[columnName].Expression =
                            WarningMessage(ex.Message, moduleId);
                    }
                    catch (ArgumentNullException ex)
                    {
                        var dc = new DataColumn(columnName, typeof(string));
                        ds.Tables[DataSetTableName.Data].Columns.Add(dc);
                        ds.Tables[DataSetTableName.Data].Columns[columnName].Expression =
                            WarningMessage(ex.Message, moduleId);
                    }
                }
            }
        }
예제 #11
0
        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);
        }
예제 #12
0
        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);
        }
예제 #13
0
        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());
        }
예제 #14
0
        string GetRowFilter(string filter, string search)
        {
            var tokenReplace = new TokenReplace(escapeApostrophe: true)
            {
                ModuleInfo = ModuleContext.Configuration
            };

            if (filter != string.Empty)
            {
                filter = tokenReplace.ReplaceEnvironmentTokens(filter);
            }
            if (filter != string.Empty && search != string.Empty)
            {
                return(string.Format("{0} AND ({1})", filter, search));
            }
            return(filter + search);
        }
예제 #15
0
        static string GetAltAttributeForImage(DataRow row, FieldSetting setting, TokenReplace tokenReplace)
        {
            var altTag = setting.AltCaption;

            if (altTag == string.Empty)
            {
                altTag = setting.Title;
            }
            else
            {
                if (altTag != string.Empty)
                {
                    altTag = tokenReplace.ReplaceEnvironmentTokens(altTag, row);
                }
            }
            altTag = new PortalSecurity().InputFilter(altTag, PortalSecurity.FilterFlag.NoMarkup);
            return(altTag);
        }
        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());
            }

            // 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.ToLocalTime().ToString());

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

            var tr = new TokenReplace
            {
                AccessingUser  = UserController.GetCurrentUserInfo(),
                DebugMessages  = Settings.UserMode != PortalSettings.Mode.View,
                ModuleId       = ModuleId,
                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);
        }
예제 #17
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string strText = this.ShowText;

            // load resources
            if (!string.IsNullOrEmpty(this.ResourceKey))
            {
                // localization
                string strFile = Path.GetFileName(this.Server.MapPath(this.PortalSettings.ActiveTab.SkinSrc));
                strFile = this.PortalSettings.ActiveTab.SkinPath + Localization.LocalResourceDirectory + "/" + strFile;
                string strLocalization = Localization.GetString(this.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 = this.ShowText;
            }

            // token replace
            if (this.ReplaceTokens)
            {
                var tr = new TokenReplace();
                tr.AccessingUser = this.PortalSettings.UserInfo;
                strText          = tr.ReplaceEnvironmentTokens(strText);
            }

            this.lblText.Text = strText;
            if (!string.IsNullOrEmpty(this.CssClass))
            {
                this.lblText.CssClass = this.CssClass;
            }
        }
예제 #18
0
        public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript)
        {
            var fields = new ArrayList();
            //List of columns that contains eMail addresses
            var tableData    = ds.Tables[DataSetTableName.Data];
            var tokenReplace = new TokenReplace {
                ModuleId = moduleId
            };

            foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows)
            {
                if (row[FieldsTableColumn.Type].ToString() == Name)
                {
                    var fieldId = (int)row[FieldsTableColumn.Id];
                    var field   = new FieldSetting
                    {
                        Title        = row[FieldsTableColumn.Title].ToString(),
                        OutputFormat = row[FieldsTableColumn.OutputSettings].AsString(),
                        AsLink       = !GetFieldSetting("NoLink", fieldId, ds).AsBoolean()
                    };
                    fields.Add(field);
                    tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original,
                                                         typeof(string)));
                    tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, typeof(string)));
                }
            }
            if (fields.Count > 0)
            {
                foreach (DataRow row in tableData.Rows)
                {
                    foreach (FieldSetting field in fields)
                    {
                        //Link shown to the user
                        //Link readable by browsers
                        var strUrl = row[field.Title].ToString().Trim();
                        //strip optional parameter like subject or body for display:
                        var strLink = strUrl.IndexOf("?", System.StringComparison.Ordinal) != -1 ? strUrl.Substring(0, strUrl.IndexOf("?", System.StringComparison.Ordinal)) : strUrl;

                        if (strLink != string.Empty)
                        {
                            var strCaption = field.OutputFormat;
                            if (!string.IsNullOrEmpty(strCaption))
                            {
                                strCaption = string.Format(tokenReplace.ReplaceEnvironmentTokens(strCaption, row),
                                                           strLink);
                            }
                            else
                            {
                                strCaption = strLink;
                            }

                            string strFieldvalue;
                            if (strCaption != string.Empty && field.AsLink)
                            {
                                strFieldvalue = string.Format("<a href=\"mailto:{0}\">{1}</a>",
                                                              HttpUtility.UrlEncode(strUrl), strCaption);
                            }
                            else
                            {
                                strFieldvalue = strLink;
                            }

                            row[field.Title] = noScript ? strFieldvalue : (Globals.CloakText(strFieldvalue));
                            row[field.Title + DataTableColumn.Appendix_Caption]  = strCaption;
                            row[field.Title + DataTableColumn.Appendix_Original] = strUrl;
                        }
                    }
                }
            }
        }
예제 #19
0
        /// <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);
        }
예제 #20
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("\"");
                    if (!string.IsNullOrEmpty(value))
                    {
                        value = Localization.GetSafeJSString(Server.HtmlDecode(value));
                        value = value.Replace("\r", string.Empty).Replace("\n", " ");
                        value = value.Replace(";", string.Empty).Replace("//", string.Empty);
                    }
                    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('");
                email = Localization.GetSafeJSString(Server.HtmlDecode(email));
                email = email.Replace(";", string.Empty).Replace("//", string.Empty);
                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);
            }
        }
예제 #21
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(this.ProfileUserId))
                {
                    this.Visible = false;
                    return;
                }

                var template = Convert.ToString(this.ModuleContext.Settings["ProfileTemplate"]);
                if (string.IsNullOrEmpty(template))
                {
                    template = Localization.GetString("DefaultTemplate", this.LocalResourceFile);
                }

                var editUrl    = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=1");
                var profileUrl = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=2");

                if (template.Contains("[BUTTON:EDITPROFILE]"))
                {
                    if (this.IncludeButton && this.IsUser)
                    {
                        string editHyperLink = string.Format("<a href=\"{0}\" class=\"dnnPrimaryAction\">{1}</a>", profileUrl, this.LocalizeString("Edit"));
                        template = template.Replace("[BUTTON:EDITPROFILE]", editHyperLink);
                    }

                    this.buttonPanel.Visible = false;
                }
                else
                {
                    this.buttonPanel.Visible  = this.IncludeButton;
                    this.editLink.NavigateUrl = editUrl;
                }

                if (template.Contains("[HYPERLINK:EDITPROFILE]"))
                {
                    if (this.IsUser)
                    {
                        string editHyperLink = string.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", profileUrl, this.LocalizeString("Edit"));
                        template = template.Replace("[HYPERLINK:EDITPROFILE]", editHyperLink);
                    }
                }

                if (template.Contains("[HYPERLINK:MYACCOUNT]"))
                {
                    if (this.IsUser)
                    {
                        string editHyperLink = string.Format("<a href=\"{0}\" class=\"dnnSecondaryAction\">{1}</a>", editUrl, this.LocalizeString("MyAccount"));
                        template = template.Replace("[HYPERLINK:MYACCOUNT]", editHyperLink);
                    }

                    this.buttonPanel.Visible = false;
                }

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

                if (this.ProfileUser.Profile.ProfileProperties.Cast <ProfilePropertyDefinition>().Count(profProperty => profProperty.Visible) == 0)
                {
                    this.noPropertiesLabel.Visible = true;
                    this.profileOutput.Visible     = false;
                    this.pnlScripts.Visible        = false;
                }
                else
                {
                    if (template.IndexOf("[PROFILE:PHOTO]") > -1)
                    {
                        var profileImageHandlerBasedURL =
                            UserController.Instance?.GetUserProfilePictureUrl(this.ProfileUserId, 120, 120);
                        template = template.Replace("[PROFILE:PHOTO]", profileImageHandlerBasedURL);
                    }

                    var token = new TokenReplace {
                        User = this.ProfileUser, AccessingUser = this.ModuleContext.PortalSettings.UserInfo
                    };
                    this.profileOutput.InnerHtml   = token.ReplaceEnvironmentTokens(template);
                    this.noPropertiesLabel.Visible = false;
                    this.profileOutput.Visible     = true;
                }

                var           propertyAccess   = new ProfilePropertyAccess(this.ProfileUser);
                StringBuilder sb               = new StringBuilder();
                bool          propertyNotFound = false;

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

                    var clientName = Localization.GetSafeJSString(property.PropertyName);
                    sb.Append("self['" + clientName + "'] = ko.observable(");
                    sb.Append("\"");
                    if (!string.IsNullOrEmpty(value))
                    {
                        value = Localization.GetSafeJSString(displayDataType == "richtext" ? value : this.Server.HtmlDecode(value));
                        value = value
                                .Replace("\r", string.Empty)
                                .Replace("\n", " ")
                                .Replace(";", string.Empty)
                                .Replace("://", ":||")  // protect http protocols won't be replaced in next step
                                .Replace("//", string.Empty)
                                .Replace(":||", "://"); // restore http protocols
                    }

                    sb.Append(value + "\"" + ");");
                    sb.Append('\n');
                    sb.Append("self['" + clientName + "Text'] = '");
                    sb.Append(clientName + "';");
                    sb.Append('\n');
                }

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

                sb.Append("self.Email = ko.observable('");
                email = Localization.GetSafeJSString(this.Server.HtmlDecode(email));
                email = email.Replace(";", string.Empty).Replace("//", string.Empty);
                sb.Append(email + "');");
                sb.Append('\n');
                sb.Append("self.EmailText = '");
                sb.Append(this.LocalizeString("Email") + "';");
                sb.Append('\n');

                this.ProfileProperties = sb.ToString();
            }
            catch (Exception exc)
            {
                // Module failed to load
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
예제 #22
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        ///     Executes a report and returns the results
        /// </summary>
        /// <param name="objReport">The ReportInfo object</param>
        /// <param name="cacheKey">The cache key for the module</param>
        /// <param name="bypassCache">A boolean indicating that the cache should be bypassed</param>
        /// <param name="hostModule">The module that is hosting the report</param>
        /// <param name="fromCache">A boolean indicating if the data was retrieved from the cache</param>
        /// <exception cref="System.ArgumentNullException">
        ///     The value of <paramref name="objReport" /> was null (Nothing in Visual Basic)
        /// </exception>
        /// <history>
        ///     [anurse]	08/25/2007	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static DataTable ExecuteReport(ReportInfo objReport, string cacheKey, bool bypassCache,
                                              PortalModuleBase hostModule, ref bool fromCache)
        {
            try
            {
                fromCache = false;
                if (ReferenceEquals(objReport, null))
                {
                    throw new ArgumentNullException("objReport");
                }

                if (string.IsNullOrEmpty(objReport.DataSource))
                {
                    return(null); // If there's no data source, there's no report
                }
                // Check the cache
                DataTable results = null;
                if (!bypassCache)
                {
                    results = DataCache.GetCache(cacheKey) as DataTable;
                    if (results != null)
                    {
                        fromCache = true;
                        return(results);
                    }
                }

                // Get an instance of the data source
                //DotNetNuke.Modules.DTSReports.DataSources.IDataSource dataSource = GetDataSource(objReport.DataSourceClass) as DataSources.IDataSource;
                var dataSource = GetDataSource(objReport.DataSourceClass);

                // Create an extension context
                var moduleFolder = string.Empty;
                if (hostModule != null)
                {
                    moduleFolder = hostModule.TemplateSourceDirectory;
                }
                var ctxt = new ExtensionContext(moduleFolder, "DataSource", objReport.DataSource);

                // Load Parameters
                IDictionary <string, object> parameters = BuildParameters(hostModule, objReport);
                if (objReport.CacheDuration != 0)
                {
                    // Check the app setting
                    if (!"True".Equals(
                            WebConfigurationManager.AppSettings[ReportsConstants.APPSETTING_AllowCachingWithParameters],
                            StringComparison.InvariantCulture))
                    {
                        parameters.Clear();
                    }
                }

                // Execute the report
                dataSource.Initialize(ctxt);
                results           = dataSource.ExecuteReport(objReport, hostModule, parameters).ToTable();
                results.TableName = "QueryResults";

                // Check if the converters were run
                if (!dataSource.CanProcessConverters)
                {
                    // If not, run them the slow way :(
                    foreach (DataRow row in results.Rows)
                    {
                        foreach (DataColumn col in results.Columns)
                        {
                            if (!objReport.Converters.ContainsKey(col.ColumnName))
                            {
                                continue;
                            }
                            var list = objReport.Converters[col.ColumnName];
                            foreach (var converter in list)
                            {
                                row[col] = ApplyConverter(row[col], converter.ConverterName, converter.Arguments);
                            }
                        }
                    }
                }

                // Do the token replace if specified
                if (objReport.TokenReplace)
                {
                    var localTokenReplacer = new TokenReplace();
                    foreach (DataColumn col in results.Columns)
                    {
                        // Process each column of the resultset
                        if (col.DataType == typeof(string))
                        {
                            // We want to replace the data, we don't mind that it is marked as readonly
                            if (col.ReadOnly)
                            {
                                col.ReadOnly = false;
                            }

                            var maxLength  = col.MaxLength;
                            var resultText = "";

                            foreach (DataRow row in results.Rows)
                            {
                                resultText =
                                    localTokenReplacer.ReplaceEnvironmentTokens(Convert.ToString(row[col].ToString()));

                                // Don't make it too long
                                if (resultText.Length > maxLength)
                                {
                                    resultText = resultText.Substring(0, maxLength);
                                }

                                row[col] = resultText;
                            }
                        }
                    }
                }


                // Cache it, if not asked to bypass the cache
                if (!bypassCache && results != null)
                {
                    DataCache.SetCache(cacheKey, results);
                }

                // Return the results
                return(results);
            }
            catch (DataSourceException)
            {
                throw;
                //Catch ex As Exception
                //    If hostModule IsNot Nothing Then
                //        Throw New DataSourceException("UnknownError.Text", hostModule.LocalResourceFile, ex, ex.Message)
                //    Else
                //        Throw
                //    End If
            }
        }
예제 #23
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (this.ItemTemplate == string.Empty)
            {
                return;
            }

            writer.Write(this.HeaderTemplate);

            // Filters
            if (this.Filters == null)
            {
                this.Filters = new Dictionary <string, string>();
            }

            var additionalFilters = new Dictionary <string, string>();

            additionalFilters.Add("Records", this.PageSize.ToString());
            additionalFilters.Add("PageIndex", this.PageIndex.ToString());
            additionalFilters.Add("Rowsize", this.RowSize.ToString());
            additionalFilters.Add("SortBy", this.SortBy);
            additionalFilters.Add("SortAscending", this.SortAscending.ToString());

            // Currently Not Used by the SPROC
            var filterUser = this.Filters.ContainsKey("UserId") && this.Filters["UserId"] != null ? new UserInfo()
            {
                UserID = int.Parse(this.Filters["UserId"])
            } : new UserInfo()
            {
                PortalID = this._currentUser.PortalID
            };
            var role = this.Filters.ContainsKey("RoleId") && this.Filters["RoleId"] != null ? new UserRoleInfo()
            {
                RoleID = int.Parse(this.Filters["RoleId"])
            } : null;
            var relationship = this.Filters.ContainsKey("RelationshipTypeId") && this.Filters["RelationshipTypeId"] != null ? new RelationshipType()
            {
                RelationshipTypeId = int.Parse(this.Filters["RelationshipTypeId"])
            } : null;

            foreach (var filter in this.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(this.AlternatingRowHeaderTemplate) || row % 2 == 0 ? this.RowHeaderTemplate : this.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(this.AlternatingItemTemplate) || row % 2 == 0 ? this.ItemTemplate : this.AlternatingItemTemplate;
                    listItem = tokenReplace.ReplaceEnvironmentTokens(listItem, tokenKeyValues, "Member");
                    writer.Write(listItem);

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

                    row++;
                }
            }

            writer.Write(this.FooterTemplate);
        }
        /// <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);
            }
        }
예제 #25
0
        public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript)
        {
            if (ds != null)
            {
                var fields       = new ArrayList();
                var tableData    = ds.Tables[DataSetTableName.Data];
                var tokenReplace = new TokenReplace {
                    ModuleId = moduleId
                };
                foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows)
                {
                    if (row[FieldsTableColumn.Type].ToString() == Name)
                    {
                        var fieldId = (int)row[FieldsTableColumn.Id];
                        var field   = new FieldSetting
                        {
                            Title           = row[FieldsTableColumn.Title].ToString(),
                            TokenText       = GetFieldSetting("TokenText", fieldId, ds).AsString(),
                            ShowUserName    = GetFieldSetting("ShowUserName", fieldId, ds).AsBoolean(),
                            OpenInNewWindow = GetFieldSetting("OpenInNewWindow", fieldId, ds).AsBoolean()
                        };
                        fields.Add(field);
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url, typeof(string)));
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original, typeof(string)));
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption, typeof(string)));
                    }
                }

                if (fields.Count > 0)
                {
                    PortalSettings portalSettings = null;
                    if (HttpContext.Current != null)
                    {
                        portalSettings = PortalController.GetCurrentPortalSettings();
                    }
                    var mc       = new ModuleController();
                    var settings = mc.GetModuleSettings(moduleId);

                    foreach (DataRow row in tableData.Rows)
                    {
                        foreach (FieldSetting field in fields)
                        {
                            var strFieldvalue = string.Empty;
                            //Link showed to the user
                            var link = row[field.Title].ToString();


                            //set caption:
                            var caption = field.TokenText;
                            var url     = string.Empty;
                            //Link readable by browsers

                            link = UrlUtil.StripURL(link);
                            if (link != string.Empty)     //valid link
                            {
                                //var isLink = true;
                                var intUser = Convert.ToInt32(-1);
                                if (link.Like("userid=*") && portalSettings != null)
                                {
                                    try
                                    {
                                        intUser           = int.Parse(link.Substring(7));
                                        tokenReplace.User = new UserController().GetUser(portalSettings.PortalId,
                                                                                         intUser);
                                    }
                                    catch
                                    {
                                    }
                                }
                                if (intUser == -1)
                                {
                                    tokenReplace.User = new UserInfo {
                                        Username = "******"
                                    };
                                }


                                if (caption == string.Empty)
                                {
                                    caption = field.ShowUserName ? "[User:DisplayName]" : "[User:UserName]";
                                }

                                caption = tokenReplace.ReplaceEnvironmentTokens(caption, row);
                                if (caption == string.Empty)     //DisplayName empty
                                {
                                    caption = tokenReplace.ReplaceEnvironmentTokens("[User:username]");
                                }

                                url =
                                    HttpUtility.HtmlEncode(Globals.LinkClick(link, portalSettings.ActiveTab.TabID,
                                                                             moduleId));

                                strFieldvalue = string.Format("<!--{1}--><a href=\"{0}\"{2}>{1}</a>",
                                                              url,
                                                              caption,
                                                              (field.OpenInNewWindow ? " target=\"_blank\"" : ""));
                            }
                            row[field.Title] = strFieldvalue;
                            row[field.Title + DataTableColumn.Appendix_Original] = link;
                            row[field.Title + DataTableColumn.Appendix_Url]      = url;
                            row[field.Title + DataTableColumn.Appendix_Caption]  = caption;
                        }
                    }
                }
            }
        }
예제 #26
0
        public override void RenderValuesToHtmlInsideDataSet(DataSet ds, int moduleId, bool noScript)
        {
            if (ds != null)
            {
                var fields = new ArrayList();
                //List of columns that contains URLs
                var tableData    = ds.Tables[DataSetTableName.Data];
                var tokenReplace = new TokenReplace {
                    ModuleId = moduleId
                };
                foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows)
                {
                    if (row[FieldsTableColumn.Type].ToString() == Name)
                    {
                        var fieldId = (int)row[FieldsTableColumn.Id];
                        var field   = new FieldSettings
                        {
                            Title               = row[FieldsTableColumn.Title].ToString(),
                            OutputFormat        = row[FieldsTableColumn.OutputSettings].AsString(),
                            Abbreviate          = GetFieldSetting("Abbreviate", fieldId, ds).AsBoolean(),
                            ShowOpenInNewWindow = GetFieldSetting("ShowOpenInNewWindow", fieldId, ds).AsBoolean(),
                            EnforceDownload     = GetFieldSetting("EnforceDownload", fieldId, ds).AsBoolean()
                        };
                        fields.Add(field);
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Url, typeof(string)));
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Caption,
                                                             typeof(string)));
                        tableData.Columns.Add(new DataColumn(field.Title + DataTableColumn.Appendix_Original,
                                                             typeof(string)));
                    }
                }
                if (fields.Count > 0)
                {
                    var portalSettings = PortalController.GetCurrentPortalSettings();


                    foreach (DataRow row in tableData.Rows)
                    {
                        foreach (FieldSettings field in fields)
                        {
                            var strFieldvalue   = string.Empty;
                            var strFileId       = row[field.Title].ToString();
                            var openInNewWindow = !field.ShowOpenInNewWindow || UrlUtil.OpenUrlInNewWindow(strFileId);
                            strFileId = UrlUtil.StripURL(strFileId);
                            var strUrl = "";
                            //Link readable by browsers

                            var strCaption = string.Empty;
                            if (strFileId != string.Empty)
                            {
                                strUrl =
                                    HttpUtility.HtmlEncode(Globals.LinkClick(strFileId, portalSettings.ActiveTab.TabID,
                                                                             moduleId));
                                var fName          = "";
                                var strDisplayName = "";
                                if (strFileId.Like("FileID=*"))
                                {
                                    var f = FileManager.Instance.GetFile(int.Parse(UrlUtils.GetParameterValue(strFileId)));
                                    if (f != null)
                                    {
                                        fName = f.FileName;
                                        if (field.Abbreviate)
                                        {
                                            strDisplayName = (f.Folder + fName);
                                        }
                                        else
                                        {
                                            strDisplayName = fName;
                                        }
                                    }
                                }
                                else
                                {
                                    fName          = Globals.ResolveUrl(strUrl);
                                    strDisplayName = field.Abbreviate
                                        ? fName.Substring(Convert.ToInt32(fName.LastIndexOf("/", StringComparison.Ordinal) + 1))
                                        : fName;
                                }
                                strCaption = field.OutputFormat;
                                strCaption = string.IsNullOrEmpty(strCaption)
                                    ? fName
                                    : tokenReplace.ReplaceEnvironmentTokens(strCaption, row);
                                if (field.EnforceDownload)
                                {
                                    strUrl += "&amp;forcedownload=true";
                                }
                                strFieldvalue = string.Format("<!--{0}--><a href=\"{1}\" {2}>{3}</a>", strDisplayName,
                                                              strUrl, (openInNewWindow ? " target=\"_blank\"" : ""),
                                                              strCaption);
                            }
                            row[field.Title] = strFieldvalue;
                            row[field.Title + DataTableColumn.Appendix_Caption]  = strCaption;
                            row[field.Title + DataTableColumn.Appendix_Original] = strFileId;
                            row[field.Title + DataTableColumn.Appendix_Url]      = strUrl;
                        }
                    }
                }
            }
        }
예제 #27
0
        /// <summary>Handles the <see cref="IModuleViewBase.Initialize"/> event of the <see cref="Presenter{TView}.View"/>.</summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void View_Initialize(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.Username) || string.IsNullOrEmpty(this.Password) || string.IsNullOrEmpty(this.IAmKey) ||
                    string.IsNullOrEmpty(this.DiscussionKey))
                {
                    this.View.Model.AdminMessage = this.LocalizeString("ModuleNeedsToBeConfigured.Text");
                    return;
                }

                var decryptedPassword = FIPSCompliant.DecryptAES(this.Password, Config.GetDecryptionkey(), Host.GUID, 1200);

                var authenticationToken = HigherLogicService.GetAuthenticationToken(this.Username, decryptedPassword, this.IAmKey);
                var postTask            = HigherLogicService.GetDiscussionPosts(
                    this.DiscussionKey,
                    this.MaxDiscussionsToRetrieve,
                    this.MaxSubjectLength,
                    this.MaxContentLength,
                    this.IncludeStaff,
                    this.IAmKey,
                    authenticationToken);

                postTask.Wait();

                var discussionPosts = postTask.Result.ToArray();

                var tokenReplace = new TokenReplace();

                this.View.Model.FooterTemplate = tokenReplace.ReplaceEnvironmentTokens(
                    this.FooterTemplate,
                    new Dictionary <string, string>(),
                    "HL").AsRawHtml();

                this.View.Model.HeaderTemplate = tokenReplace.ReplaceEnvironmentTokens(
                    this.HeaderTemplate,
                    new Dictionary <string, string>(),
                    "HL").AsRawHtml();

                if (!discussionPosts.Any())
                {
                    this.View.Model.NoRecordsTemplate = tokenReplace.ReplaceEnvironmentTokens(
                        this.NoRecordsTemplate,
                        new Dictionary <string, string>(),
                        "HL").AsRawHtml();

                    return;
                }

                this.View.Model.HasRecords = true;
                var renderAttachemnts = this.ItemTemplate.Contains("[HL:Discussion:Attachments]");

                this.View.Model.ItemTemplate = (from post in discussionPosts
                                                select tokenReplace.ReplaceEnvironmentTokens(
                                                    this.ItemTemplate,
                                                    this.BuildTokenDictionary(post, renderAttachemnts),
                                                    "HL"))
                                               .Aggregate((template, itemTemplate) => $"{template}{itemTemplate}")
                                               .AsRawHtml();
            }
            catch (AggregateException exc)
            {
                this.ProcessModuleLoadException(exc);
                this.View.Model.AdminMessage = exc.Message;
            }
        }
예제 #28
0
        void FillTypeColumns(int moduleId, TokenReplace objTokenReplace, PortalSettings portalSettings,
                             TabController tabCtrl,
                             DataRow row, FieldSetting field)
        {
            var link = row[field.Title].ToString();
            //Link showed to the user
            bool openInNewWindow;

            if (field.ShowOpenInNewWindow)  //mit URL gepeicherten Wert lesen
            {
                openInNewWindow = UrlUtil.OpenUrlInNewWindow(link);
            }
            else
            {
                switch (Globals.GetURLType(UrlUtil.StripURL(link)))
                {
                case TabType.File:
                    openInNewWindow = true;
                    break;

                case TabType.Tab:     //link to internal tab
                    openInNewWindow = false;
                    break;

                default:
                    openInNewWindow = link.Like(Globals.ApplicationMapPath + "*");
                    break;
                }
            }

            //set caption:
            var caption = field.OutputFormat;

            if (!string.IsNullOrEmpty(caption))
            {
                caption = objTokenReplace.ReplaceEnvironmentTokens(caption, row);
            }
            var isLink = true;

            //Link readable by browsers
            link = UrlUtil.StripURL(link);
            var url = Globals.LinkClick(link, portalSettings.ActiveTab.TabID, moduleId, field.TrackDownloads, field.EnforceDownload);

            if (link != string.Empty)
            {
                switch (Globals.GetURLType(link))
                {
                case TabType.Tab:
                    var tab = tabCtrl.GetTab(int.Parse(link), portalSettings.PortalId, false);
                    if (tab != null)
                    {
                        if (caption == string.Empty)
                        {
                            if (!field.Abbreviate)
                            {
                                var strPath = string.Empty;
                                if (tab.BreadCrumbs != null && tab.BreadCrumbs.Count > 0)
                                {
                                    foreach (TabInfo b in tab.BreadCrumbs)
                                    {
                                        var strLabel = b.TabName;
                                        if (strPath != string.Empty)
                                        {
                                            strPath +=
                                                string.Format(
                                                    "<img src=\"{0}/images/breadcrumb.gif\" border=\"0\" alt=\"Spacer\"/>",
                                                    Globals.ApplicationPath);
                                        }
                                        strPath += strLabel;
                                    }
                                }
                                caption = tab.TabPath.Replace("//",
                                                              string.Format(
                                                                  "<img src=\"{0}/images/breadcrumb.gif\" border=\"0\" alt=\"Spacer\"/>",
                                                                  Globals.ApplicationPath));
                            }
                            else
                            {
                                caption = tab.TabName;
                            }
                        }
                        url = field.EnforceDownload ? url : Globals.NavigateURL(int.Parse(link));
                    }
                    else
                    {
                        caption = Localization.GetString("PageNotFound.ErrorMessage",
                                                         Globals.ResolveUrl(
                                                             string.Format("~{0}{1}/SharedResources.resx",
                                                                           Definition.PathOfModule,
                                                                           Localization.LocalResourceDirectory)));
                        url    = string.Empty;
                        isLink = false;
                    }
                    break;

                case TabType.File:
                    if (caption == string.Empty)
                    {
                        if (link.ToLowerInvariant().StartsWith("fileid="))
                        {
                            var file = FileManager.Instance.GetFile(int.Parse(link.Substring(7)));
                            if (file != null)
                            {
                                if (!field.Abbreviate)
                                {
                                    caption = file.Folder + file.FileName;
                                }
                                else
                                {
                                    caption = file.FileName;
                                }
                            }
                        }
                        else if (field.Abbreviate && link.IndexOf("/", StringComparison.Ordinal) > -1)
                        {
                            caption = link.Substring(Convert.ToInt32(link.LastIndexOf("/", StringComparison.Ordinal) + 1));
                        }
                        else
                        {
                            caption = link;
                        }
                    }
                    break;

                case TabType.Url:
                case TabType.Normal:
                    if (caption == string.Empty)
                    {
                        if (field.Abbreviate && link.IndexOf("/", StringComparison.Ordinal) > -1)
                        {
                            caption = link.Substring(Convert.ToInt32(link.LastIndexOf("/", StringComparison.Ordinal) + 1));
                        }
                        else
                        {
                            caption = link;
                        }
                    }
                    if (!field.TrackDownloads)
                    {
                        url = link;
                    }
                    break;
                }


                if (field.EnforceDownload)
                {
                    url += "&amp;forcedownload=true";
                }

                string strFieldvalue;
                if (isLink)
                {
                    strFieldvalue = string.Format("<!--{1}--><a href=\"{0}\"{2}>{1}</a>", url,
                                                  caption, (openInNewWindow ? " target=\"_blank\"" : ""));
                }
                else
                {
                    strFieldvalue = caption;
                }
                row[field.Title] = strFieldvalue;
                row[field.Title + DataTableColumn.Appendix_Caption]  = caption;
                row[field.Title + DataTableColumn.Appendix_Original] = link;
                row[field.Title + DataTableColumn.Appendix_Url]      = url;
            }
        }