/// <summary> /// Prepares JSON object to be inserted to the breadcrumbs. This object will be used when updating breadcrumbs after changing display name of the campaign. /// </summary> /// <returns>List of objects containing breadcrumb for root element and single campaign.</returns> private object GetBreadcrumbsData() { var breadcrumbsList = new List <object>(); var application = UIContext.UIElement.Application; // Root application string rootRedirectUrl = UrlResolver.ResolveUrl(ApplicationUrlHelper.GetApplicationUrl(application)); breadcrumbsList.Add(new { text = MacroResolver.Resolve(application.ElementDisplayName), redirectUrl = rootRedirectUrl, isRoot = true }); // (Campaign) breadcrumbsList.Add(new { suffix = ResHelper.GetString("analytics.campaign") }); return(new { data = breadcrumbsList, pin = new { elementGuid = UIElementInfoProvider.GetUIElementInfo(UIContext.UIElement.ElementParentID).ElementGUID, applicationGuid = application.ElementGUID, objectType = CampaignInfo.OBJECT_TYPE } }); }
/// <summary> /// OnLoad event. /// </summary> /// <param name="e">Event arguments</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); repItem.ItemDataBound += repItem_ItemDataBound; currentUser = MembershipContext.AuthenticatedUser; string script = ""; // Group invitation script += "function ContextGroupInvitation(id) { \nmodalDialog('" + ApplicationUrlHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=' + id , 'inviteToGroup', 500, 450); \n } \n"; // Redirect to sign in URL string signInUrl = MacroResolver.Resolve(AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName)); if (signInUrl != "") { signInUrl = "window.location.replace('" + URLHelper.AddParameterToUrl(ResolveUrl(signInUrl), "ReturnURL", Server.UrlEncode(RequestContext.CurrentURL)) + "');"; } script += "function ContextRedirectToSignInUrl() { \n" + signInUrl + "} \n"; // Register menu management scripts ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "UserContextMenuManagement", ScriptHelper.GetScript(script)); // Register the dialog script ScriptHelper.RegisterDialogScript(Page); }
protected void Page_Load(object sender, EventArgs e) { // Try skip IIS http errors Response.TrySkipIisCustomErrors = true; // Set service unavailable state Response.StatusCode = 503; // Set title titleElem.TitleText = GetString("Error.SiteOffline"); SiteInfo currentSite = SiteContext.CurrentSite; if (currentSite != null) { if (currentSite.SiteIsOffline) { // Site is offline if (!String.IsNullOrEmpty(currentSite.SiteOfflineMessage)) { lblInfo.Text = MacroResolver.Resolve(currentSite.SiteOfflineMessage); } else { lblInfo.Text = GetString("error.siteisoffline"); } } else { // Redirect to the root URLHelper.ResponseRedirect("~/"); } } }
/// <summary> /// Fills dropdown list with document types. /// </summary> private void FillDocumentTypesDDL() { drpDocTypes.Items.Clear(); // Add (All) record drpDocTypes.Items.Add(new ListItem(GetString("general.selectall"), "0")); // Select only document types from current site marked as product DataSet ds = DocumentTypeHelper.GetDocumentTypeClasses() .OnSite(SiteContext.CurrentSiteID) .WhereTrue("ClassIsProduct") .OrderBy("ClassDisplayName") .Columns("ClassID", "ClassDisplayName"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Tables[0].Rows) { string name = ValidationHelper.GetString(dr["ClassDisplayName"], ""); int id = ValidationHelper.GetInteger(dr["ClassID"], 0); if (!string.IsNullOrEmpty(name) && (id > 0)) { // Handle document name name = ResHelper.LocalizeString(MacroResolver.Resolve(name)); drpDocTypes.Items.Add(new ListItem(name, id.ToString())); } } } }
protected void Page_Load(object sender, EventArgs e) { // Only community manager can delete group if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Groups", CMSAdminControl.PERMISSION_MANAGE)) { RedirectToAccessDenied("CMS.Groups", CMSAdminControl.PERMISSION_MANAGE); } int groupId = QueryHelper.GetInteger("groupid", 0); gi = GroupInfoProvider.GetGroupInfo(groupId); if (gi != null) { lblMsg.Style.Add("font-weight", "bold"); chkDeleteAll.Text = MacroResolver.Resolve(GetString("group.deleterelated")); mGroupListUrl = ResolveUrl(mGroupListUrl); // Pagetitle PageTitle.TitleText = GetString("group.deletegroup") + " \"" + HTMLHelper.HTMLEncode(gi.GroupDisplayName) + "\""; // Initialize breadcrumbs PageBreadcrumbs.Items.Add(new BreadcrumbItem() { Text = GetString("deletegroup.listlink"), RedirectUrl = mGroupListUrl, }); PageBreadcrumbs.Items.Add(new BreadcrumbItem() { Text = HTMLHelper.HTMLEncode(gi.GroupDisplayName), }); btnDelete.Click += new EventHandler(btnDelete_Click); btnCancel.Click += new EventHandler(btnCancel_Click); } }
/// <summary> /// Registers JavaScripts on page. /// </summary> protected void RegisterScripts() { var stamp = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + ".CMSCMStamp"); ScriptHelper.RegisterDialogScript(Page); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "AddStamp", ScriptHelper.GetScript( @"function InsertHTML(htmlString, ckClientID) { // Get the editor instance that we want to interact with. var oEditor = oEditor = window.CKEDITOR.instances[ckClientID]; // Check the active editing mode. if (oEditor != null) { // Check the active editing mode. if (oEditor.mode == 'wysiwyg') { // Insert the desired HTML. //oEditor.focus(); oEditor.insertHtml(htmlString); } } return false; } function AddStamp(ckClientID) { InsertHTML('<div>" + MacroResolver.Resolve(stamp).Replace("'", @"\'") + @"</div>', ckClientID); } ")); }
/// <summary> /// Registers JavaScripts on page. /// </summary> private void RegisterScripts() { ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "AddStamp", ScriptHelper.GetScript( @"function InsertHTML(htmlString, ckClientID) { // Get the editor instance that we want to interact with. var oEditor = oEditor = window.CKEDITOR.instances[ckClientID]; // Check the active editing mode. if (oEditor != null) { // Check the active editing mode. if (oEditor.mode == 'wysiwyg') { // Insert the desired HTML. oEditor.focus(); oEditor.insertHtml(htmlString); } } return false; } function AddStamp(ckClientID) { InsertHTML('<div>" + MacroResolver.Resolve(mStamp).Replace("'", @"\'") + @"</div>', ckClientID); }" )); }
/// <summary> /// Get completly resolved url (resolve macros, hash, url) /// </summary> private string GetUrl(string url) { url = MacroResolver.Resolve(url); url = URLHelper.EnsureHashToQueryParameters(url); url = UrlResolver.ResolveUrl(url); return(url); }
/// <summary> /// OnLoad event. /// </summary> /// <param name="e">Event arguments</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); repItem.ItemDataBound += repItem_ItemDataBound; currentUser = MembershipContext.AuthenticatedUser; string script = ""; // Friendship request script += "function ContextFriendshipRequest(id) { \n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Friends/CMSPages/Friends_Request.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id,'requestFriend', 810, 460); \n" + " } \n"; // Friendship rejection script += "function ContextFriendshipReject(id) { \n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Friends/CMSPages/Friends_Reject.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'rejectFriend', 720, 320); \n" + " } \n"; // Send private message script += "function ContextPrivateMessage(id) { \n" + "modalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Messaging/CMSPages/SendMessage.aspx") + "?userid=" + currentUser.UserID + "&requestid=' + id , 'sendMessage', 700, 650); \n" + " } \n"; // Add to contact list script += "function ContextAddToContactList(usertoadd) { \n" + "if(confirm(" + ScriptHelper.GetString(ResHelper.GetString("messaging.contactlist.addconfirmation")) + "))" + "{" + Page.ClientScript.GetPostBackEventReference(this, "addtocontactlist", false) + "} } \n"; // Add to ignore list script += "function ContextAddToIgnoretList(usertoadd) { \n" + "if(confirm(" + ScriptHelper.GetString(ResHelper.GetString("messaging.ignorelist.addconfirmation")) + "))" + "{" + Page.ClientScript.GetPostBackEventReference(this, "addtoignorelist", false) + "} } \n"; // Group invitation script += "function ContextGroupInvitation(id) { \nmodalDialog('" + AuthenticationHelper.ResolveDialogUrl("~/CMSModules/Groups/CMSPages/InviteToGroup.aspx") + "?invitedid=' + id , 'inviteToGroup', 500, 450); \n } \n"; // Redirect to sign in URL string signInUrl = MacroResolver.Resolve(AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName)); if (signInUrl != "") { signInUrl = "window.location.replace('" + URLHelper.AddParameterToUrl(ResolveUrl(signInUrl), "ReturnURL", Server.UrlEncode(RequestContext.CurrentURL)) + "');"; } script += "function ContextRedirectToSignInUrl() { \n" + signInUrl + "} \n"; // Register menu management scripts ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "UserContextMenuManagement", ScriptHelper.GetScript(script)); // Register the dialog script ScriptHelper.RegisterDialogScript(Page); }
/// <summary> /// Returns safe and localized tooltip from the given source column. /// </summary> /// <param name="dr">Data row with the tooltip column</param> /// <param name="columnName">Name of the tooltip source column</param> private string GetTooltip(DataRow dr, string columnName) { // Get tooltip string string tooltip = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, columnName), ""); // Get safe an localized tooltip if (!string.IsNullOrEmpty(tooltip)) { return(HTMLHelper.HTMLEncode(MacroResolver.Resolve(tooltip))); } return(""); }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing || !ViewMode.IsOneOf(ViewModeEnum.LiveSite, ViewModeEnum.Preview)) { return; } // Registration to chat webservice AbstractCMSPage cmsPage = Page as AbstractCMSPage; if (cmsPage != null) { ChatScriptHelper.RegisterChatAJAXProxy(cmsPage); } // Script references insertion ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterJQueryCookie(Page); ScriptHelper.RegisterScriptFile(Page, "~/CMSModules/Chat/CMSPages/ChatSettings.ashx"); ScriptHelper.RegisterJQueryTemplates(Page); ScriptHelper.RegisterScriptFile(Page, "~/CMSWebParts/Chat/AutoInitiatedChat_files/AutoInitiatedChat.js"); int optID = ChatPopupWindowSettingsHelper.Store(ChatMessageTransformationName, ChatRoomUserTransformationName, ChatErrorTransformationName, ChatErrorDeleteAllButtonTransformationName); // Run script string json = JsonConvert.SerializeObject( new { wpGUID = InstanceGUID, clientID = pnlInitiatedChat.ClientID, contentID = pnlContent.ClientID, pnlErrorID = pnlError.ClientID, lblErrorID = lblError.ClientID, windowURL = ChatUIHelper.GetChatRoomWindowURL(), trans = ChatUIHelper.GetWebpartTransformation(TransformationName, "chat.error.transformation.initiatedchat.error"), guid = optID, delay = Delay * 1000, initiatorName = InitiatorName, messages = MacroResolver.Resolve(Messages).Split('\n') }, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml } ); string startupScript = string.Format("InitAutoInitiatedChat({0});", json); ScriptHelper.RegisterStartupScript(Page, typeof(string), "ChatAutoInitiatedChat_" + ClientID, startupScript, true); }
/// <summary> /// Returns CSS stylesheet for current page. /// Stylesheet can be: /// - normal CSS of current page /// - default CSS for all AMP pages /// - CSS set as AMP stylesheet for current page /// </summary> private string GetStylesheetText() { string cssText = ""; // Checking which CSS file to use ObjectQuery <AmpFilterInfo> q = AmpFilterInfoProvider.GetAmpFilters().WhereEquals("PageNodeGuid", DocumentContext.CurrentPageInfo.NodeGUID.ToString()); AmpFilterInfo ampFilterInfo = q.FirstOrDefault(); bool useDefaultStylesheet = ampFilterInfo?.UseDefaultStylesheet ?? true; if (useDefaultStylesheet) { // Get the ID of default AMP CSS string defaultID = Settings.AmpFilterDefaultCSS; var cssID = ValidationHelper.GetInteger(defaultID, 0); // Default AMP CSS is not set, using ordinary CSS of current page if (cssID == 0) { cssText = DocumentContext.CurrentDocumentStylesheet?.StylesheetText; } else { // Use default AMP CSS stylesheet var cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(cssID); if (cssInfo != null) { cssText = cssInfo.StylesheetText; } } } else { // Use specific AMP CSS set for this page int stylesheetID = ampFilterInfo?.StylesheetID ?? 0; var cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(stylesheetID); if (cssInfo != null) { cssText = cssInfo.StylesheetText; } } // Resolve macros cssText = MacroResolver.Resolve(cssText); // Resolve client URL return(HTMLHelper.ResolveCSSClientUrls(cssText, CMSHttpContext.Current.Request.Url.ToString())); }
protected override void OnPreRender(EventArgs e) { // Select first item if (!String.IsNullOrEmpty(uniMenu.StartingPage) || (HighlightFirstItem && !String.IsNullOrEmpty(TargetFrameset) && (FirstUIElement != null))) { String url = String.IsNullOrEmpty(uniMenu.StartingPage) ? UIContextHelper.GetElementUrl(FirstUIElement, UIContext) : uniMenu.StartingPage; // Ensure hash code if required url = MacroResolver.Resolve(URLHelper.EnsureHashToQueryParameters(url)); String target = UseIFrame ? String.Format("frames['{0}']", TargetFrameset) : String.Format("parent.frames['{0}']", TargetFrameset); String script = String.Format("{0}.location.href = '{1}';", target, ResolveUrl(url)); ScriptHelper.RegisterStartupScript(Page, typeof(String), "FirstItemSelection", ScriptHelper.GetScript(script)); } base.OnPreRender(e); }
protected void btnOk_Click(object sender, EventArgs e) { if (AccountHelper.AuthorizedModifyAccount(SiteID, true)) { Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0); What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedItem.Value, 0); string where = string.Empty; switch (what) { // All items case What.All: where = MacroResolver.Resolve(gridElem.WhereCondition); break; // Selected items case What.Selected: where = SqlHelper.GetWhereCondition <int>("AccountID", gridElem.SelectedItems, false); break; default: return; } switch (action) { // Action 'Remove' case Action.Remove: // Clear HQ ID of selected accounts AccountInfoProvider.UpdateAccountHQ(0, where); ShowConfirmation(GetString("om.account.massaction.removed")); break; default: return; } // Reload UniGrid gridElem.ClearSelectedItems(); gridElem.ReloadData(); pnlUpdate.Update(); } }
/// <summary> /// Gets HTML list code representing the <paramref name="uiElement"/> where can visitors go after the import has finished. /// </summary> /// <param name="uiElement">UI element the caption, icon and link are loaded from</param> /// <param name="description">Description of the element (i.e. some clarification what the application is good for)</param> /// <returns>HTML list code representing the <paramref name="uiElement"/> with given <paramref name="description"/></returns> private string GetContinueToSmartTipListContent(UIElementInfo uiElement, string description) { string applicationUrl = UIContextHelper.GetApplicationUrl(UIContextHelper.GetResourceName(uiElement.ElementResourceID), uiElement.ElementName); return(string.Format(@" <li> <div class=""om-import-csv-next-steps-initial""> <i aria-hidden=""true"" class=""{0} cms-icon-100""></i> </div> <div class=""om-import-csv-next-steps-description""> <p class=""lead""> <a href=""{1}"" target=""_blank"">{2}</a> </p> <p> {3} </p> </div> </li>", uiElement.ElementIconClass, URLHelper.ResolveUrl(applicationUrl), MacroResolver.Resolve(uiElement.ElementCaption), description)); }
protected void Page_Load(object sender, EventArgs e) { // Set the orientation object orientObj = GetValue("Orientation"); if (orientObj == null) { exSlider.Orientation = Orientation; } else { exSlider.Orientation = Orientation = ValidationHelper.GetBoolean(orientObj, false) ? SliderOrientation.Vertical : SliderOrientation.Horizontal; } exSlider.Minimum = Minimum; exSlider.Maximum = Maximum; exSlider.Steps = Steps; exSlider.Decimals = Decimals; exSlider.Orientation = Orientation; exSlider.HandleCssClass = HandleCssClass; exSlider.HandleImageUrl = HandleImageUrl; exSlider.Length = Length; exSlider.RailCssClass = RailCssClass; exSlider.TooltipText = MacroResolver.Resolve(TooltipText); // Initialize label lblValue.CssClass = LabelCssClass; lblValue.Visible = ShowLabel; // Apply CSS styles if (!String.IsNullOrEmpty(CssClass)) { pnlContainer.CssClass = CssClass; CssClass = null; } if (!String.IsNullOrEmpty(ControlStyle)) { pnlContainer.Attributes.Add("style", ControlStyle); ControlStyle = null; } CheckRegularExpression = true; }
protected Directive(Match match, MacroResolver macroResolver) { Match = match; MacroResolver = macroResolver; Attributes = new Dictionary <string, string>(); var keys = Match.Groups["key"].Captures; var values = Match.Groups["value"].Captures; if (keys.Count != values.Count) { throw new T4Exception("Error in T4 directives: Different number of keys and values."); } for (var i = 0; i < keys.Count; i++) { Attributes.Add(keys[i].Value.ToLower(), MacroResolver.Resolve(values[i].Value)); } }
/// <summary> /// Gets <c>Label</c> instance for the input <c>SettingsKeyInfo</c> object. /// </summary> /// <param name="settingsKey"><c>SettingsKeyInfo</c> instance</param> /// <param name="inputControl">Input control associated to the label</param> /// <param name="groupNo">Number representing index of the processing settings group</param> /// <param name="keyNo">Number representing index of the processing SettingsKeyInfo</param> private Label GetLabel(SettingsKeyInfo settingsKey, Control inputControl, int groupNo, int keyNo) { LocalizedLabel label = new LocalizedLabel { EnableViewState = false, ID = string.Format(@"lblDispName{0}{1}", groupNo, keyNo), CssClass = "control-label editing-form-label", Text = settingsKey.KeyDisplayName, DisplayColon = true }; if (inputControl != null) { label.AssociatedControlID = inputControl.ID; } ScriptHelper.AppendTooltip(label, MacroResolver.Resolve(ResHelper.LocalizeString(settingsKey.KeyDescription)), null); return(label); }
protected object gridClasses_OnExternalDataBound(object sender, string sourceName, object parameter) { if (sourceName.ToLowerCSafe() == "classname") { DataRowView drv = (DataRowView)parameter; // Get properties string className = ValidationHelper.GetString(drv["ClassName"], string.Empty); string classDisplayName = ResHelper.LocalizeString(MacroResolver.Resolve(ValidationHelper.GetString(drv["ClassDisplayName"], string.Empty))); int classId = ValidationHelper.GetInteger(drv["ClassId"], 0); string iconClass = ValidationHelper.GetString(drv["ClassIconClass"], string.Empty); string nameFormat = UIHelper.GetDocumentTypeIcon(Page, className, iconClass) + "{0}"; // Append link if url specified if (!string.IsNullOrEmpty(SelectionUrl)) { string url = GetSelectionUrl(classId); if (IsInDialog) { url = URLHelper.UpdateParameterInUrl(url, "dialog", "1"); url = URLHelper.UpdateParameterInUrl(url, "reloadnewpage", "1"); } // Prepare attributes string attrs = ""; if (!string.IsNullOrEmpty(ClientTypeClick)) { attrs = string.Format("onclick=\"{0}\"", ClientTypeClick); } nameFormat = string.Format("<a class=\"ContentNewClass cms-icon-link\" href=\"{0}\" {2}>{1}</a>", url, nameFormat, attrs); } // Format items to output return(string.Format(nameFormat, HTMLHelper.HTMLEncode(classDisplayName)) + GenerateSpaceAfter(className)); } return(HTMLHelper.HTMLEncode(parameter.ToString())); }
/// <summary> /// Generate header of the matrix. /// </summary> /// <param name="matrixData">Data of the matrix to be generated</param> private void GenerateMatrixHeader(List <DataRow> matrixData) { // Prepare matrix header foreach (int index in ColumnOrderIndex) { DataRow dr = matrixData[index]; if (ShowHeaderRow) { // Create header cell var thc = new TableHeaderCell { Scope = TableHeaderScope.Column, Text = HTMLHelper.HTMLEncode(MacroResolver.Resolve(Convert.ToString(dr[ColumnItemDisplayNameColumn]))), ToolTip = (ColumnItemTooltipColumn != null) ? GetTooltip(dr, ItemTooltipColumn) : null, EnableViewState = false }; thrFirstRow.Cells.Add(thc); // Add disabled mark if needed if (!IsColumnEditable(dr[ColumnItemIDColumn])) { thc.Text += DisabledColumnMark; } } else { // Create header cell var thc = new TableHeaderCell { Scope = TableHeaderScope.Column, Text = " ", EnableViewState = false }; thrFirstRow.Cells.Add(thc); } } }
/// <summary> /// Get user information and logs user (register if no user found) /// </summary> private void ProcessLiveIDLogin() { // Get authorization code from URL String code = QueryHelper.GetString("code", String.Empty); // Additional info page for login string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSLiveIDRequiredUserDataPage"); // Create windows login object WindowsLiveLogin wwl = new WindowsLiveLogin(siteName); // Windows live User WindowsLiveLogin.User liveUser = null; if (!WindowsLiveLogin.UseServerSideAuthorization) { if (!RequestHelper.IsPostBack()) { // If client authentication, get token displayed in url after # from window.location String script = ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "window.location"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "PostbackScript", ScriptHelper.GetScript(script)); } else { // Try to get full url from event argument string fullurl = Request[postEventArgumentID]; // Authentication token - use to get uid String token = ParseToken(fullurl, @"authentication_token=([\w\d.-]+)&"); // User token - this token is used in server auth. scenario. It's stored in user object (for possible further use) so parse it too and store it String accessToken = ParseToken(fullurl, @"access_token=([%\w\d.-/]+)&"); if (token != String.Empty) { // Return context from session GetLoginInformation(); // Authenticate user by found token liveUser = wwl.AuthenticateClientToken(token, relativeURL, accessToken); if (liveUser != null) { // Set info to refresh to parent page ScriptHelper.RegisterWOpenerScript(Page); CreateCloseScript(""); } } } } else { GetLoginInformation(); // Process login via Live ID liveUser = wwl.ProcessLogin(code, relativeURL); } // Authorization successful if (liveUser != null) { // Find user by ID UserInfo winUser = UserInfoProvider.GetUserInfoByWindowsLiveID(liveUser.Id); string error = String.Empty; // Register new user if (winUser == null) { // Check whether additional user info page is set // No page set, user can be created/sign if (additionalInfoPage == String.Empty) { // Create new user UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error); // Remove live user object from session, won't be needed Session.Remove("windowsliveloginuser"); // If user was found or successfully created if ((ui != null) && (ui.Enabled)) { double resolvedConversionValue = ValidationHelper.GetDouble(MacroResolver.Resolve(conversionValue), 0); // Log user registration into the web analytics and track conversion if set AnalyticsHelper.TrackUserRegistration(siteName, ui, conversionName, resolvedConversionValue); MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument); SetAuthCookieAndRedirect(ui); } // User not created else { if (WindowsLiveLogin.UseServerSideAuthorization) { WindowsLiveLogin.ClearCookieAndRedirect(loginPage); } else { CreateCloseScript("clearcookieandredirect"); } } } // Required data page exists else { // Store user object in session for additional info page SessionHelper.SetValue("windowsliveloginuser", liveUser); if (WindowsLiveLogin.UseServerSideAuthorization) { // Redirect to additional info page URLHelper.Redirect(UrlResolver.ResolveUrl(additionalInfoPage)); } else { CreateCloseScript("redirectToAdditionalPage"); } } } else { UserInfo ui = AuthenticationHelper.AuthenticateWindowsLiveUser(liveUser.Id, siteName, true, ref error); // If user was found if ((ui != null) && (ui.Enabled)) { SetAuthCookieAndRedirect(ui); } } } }
protected void btnRun_Click(object sender, EventArgs e) { var text = editorElem.Text; // Get the number of iterations int iterations = ValidationHelper.GetInteger(txtIterations.Text, 0); if (iterations <= 0) { ShowError(GetString("macros.benchmark.invaliditerations")); return; } string result = String.Empty; int runs = 0; var startTime = DateTime.Now; double minRunSeconds = double.MaxValue; double maxRunSeconds = 0; double totalRunSeconds = 0; // Run the benchmark for (int i = 0; i < iterations; i++) { var runStart = DateTime.Now; // Execute the run result = MacroResolver.Resolve(text); runs++; // Count the run time var runEnd = DateTime.Now; var runTime = runEnd - runStart; var runSeconds = runTime.TotalSeconds; if (runSeconds < minRunSeconds) { minRunSeconds = runSeconds; } if (runSeconds > maxRunSeconds) { maxRunSeconds = runSeconds; } totalRunSeconds += runSeconds; } var endTime = DateTime.Now; if (Math.Abs(minRunSeconds - double.MaxValue) < Math.E) { minRunSeconds = 0; } editorElem.Text = text; txtOutput.Text = result; var totalTime = endTime - startTime; var totalSeconds = totalTime.TotalSeconds; var secondsPerRun = totalSeconds / runs; txtResults.Text = String.Format( @" Total runs: {0}s Total benchmark time: {1:f5}s Total run time: {5:f5}s Average time per run: {2:f5}s Min run time: {3:f5}s Max run time: {4:f5}s Evaluated text: --------------- {6} " , runs , totalSeconds , secondsPerRun , minRunSeconds , maxRunSeconds , totalRunSeconds , text ); }
/// <summary> /// Sets time controls (dropdown with interval and textbox with interval value). Returns true if time controls are to be hided. /// </summary> private bool SetTimeControls() { HitsIntervalEnum interval = HitsIntervalEnumFunctions.StringToHitsConversion(mIntervalStr); DateTime from = DateTimeHelper.ZERO_TIME; DateTime to = DateTimeHelper.ZERO_TIME; object dcFrom = null; object dcTo = null; if (mParameters != null) { // Load fromdate and todate from report parameters (passed from query string) dcFrom = mParameters.Table.Columns["FromDate"]; dcTo = mParameters.Table.Columns["ToDate"]; if (dcFrom != null) { from = ValidationHelper.GetDateTime(mParameters["FromDate"], DateTimeHelper.ZERO_TIME); } if (dcTo != null) { to = ValidationHelper.GetDateTime(mParameters["ToDate"], DateTimeHelper.ZERO_TIME); } } // If one contains zero time, set all time radio button. In such situation, report can maintain unlimited fromdate or todate. if ((from == DateTimeHelper.ZERO_TIME) || (to == DateTimeHelper.ZERO_TIME)) { mCheckLast = false; } // If one is not set, hide limitdata panel if ((dcFrom == null) || (dcTo == null)) { ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY; return(true); } int diff = 0; bool noAddToDiff = false; // If interval is not known, but 'from' and 'to' is set (f.e. preview, webpart,..) - compute interval from date values if (interval == HitsIntervalEnum.None) { String sFrom = ValidationHelper.GetString(mParameters["FromDate"], String.Empty).ToLowerCSafe(); String sTo = ValidationHelper.GetString(mParameters["ToDate"], String.Empty).ToLowerCSafe(); mCheckLast = true; if (MacroProcessor.ContainsMacro(sFrom) && MacroProcessor.ContainsMacro(sTo)) { if (sFrom.Contains("addhours")) { interval = HitsIntervalEnum.Hour; } else if (sFrom.Contains("adddays")) { interval = HitsIntervalEnum.Day; } else if (sFrom.Contains("addweeks")) { interval = HitsIntervalEnum.Week; } else if (sFrom.Contains("addmonths")) { interval = HitsIntervalEnum.Month; } else if (sFrom.Contains("addyears")) { interval = HitsIntervalEnum.Year; } var macroResolverSettings = new MacroSettings { AvoidInjection = false, Culture = CultureHelper.EnglishCulture.Name }; to = DateTime.Now; from = ValidationHelper.GetDateTime(MacroResolver.Resolve(sFrom, macroResolverSettings), DateTime.Now, macroResolverSettings.Culture); noAddToDiff = true; } else if ((from != DateTimeHelper.ZERO_TIME) && (to != DateTimeHelper.ZERO_TIME)) { // Set interval as greatest possible interval (365+ days -> years, 30+days->months ,...) diff = (int)(to - from).TotalDays; if (diff >= 365) { interval = HitsIntervalEnum.Year; } else if (diff >= 30) { interval = HitsIntervalEnum.Month; } else if (diff >= 7) { interval = HitsIntervalEnum.Week; } else if (diff >= 1) { interval = HitsIntervalEnum.Day; } else { interval = HitsIntervalEnum.Hour; } } } // Set default period and diff based on interval switch (interval) { case HitsIntervalEnum.Year: diff = to.Year - from.Year; ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_MONTH; break; case HitsIntervalEnum.Month: diff = ((to.Year - from.Year) * 12) + to.Month - from.Month; ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_MONTH; break; case HitsIntervalEnum.Week: diff = (int)(to - from).TotalDays / 7; ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_WEEK; break; case HitsIntervalEnum.Day: diff = (int)(to - from).TotalDays; ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY; break; case HitsIntervalEnum.Hour: diff = (int)(to - from).TotalHours; ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_HOUR; break; case HitsIntervalEnum.None: mCheckLast = false; break; } // Add current if (!noAddToDiff) { diff++; } if (interval != HitsIntervalEnum.None) { drpLast.SelectedValue = HitsIntervalEnumFunctions.HitsConversionToString(interval); } if (!mCheckLast) { // Defaul settings for no time ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY; } if (diff != 0) { txtLast.Text = diff.ToString(); } return(false); }
/// <summary> /// Generates panel with buttons loaded from given UI Element. /// </summary> /// <param name="uiElementId">ID of the UI Element</param> protected Panel GetButtons(int uiElementId) { const int bigButtonMinimalWidth = 40; const int smallButtonMinimalWidth = 66; Panel pnlButtons = null; // Load the buttons manually from UI Element DataSet ds = UIElementInfoProvider.GetChildUIElements(uiElementId); // When no child found if (DataHelper.DataSourceIsEmpty(ds)) { // Try to use group element as button ds = UIElementInfoProvider.GetUIElements("ElementID = " + uiElementId, null); if (!DataHelper.DataSourceIsEmpty(ds)) { DataRow dr = ds.Tables[0].Rows[0]; string url = ValidationHelper.GetString(dr["ElementTargetURL"], ""); // Use group element as button only if it has URL specified if (string.IsNullOrEmpty(url)) { ds = null; } } } if (!DataHelper.DataSourceIsEmpty(ds)) { // Filter the dataset according to UI Profile FilterElements(ds); int small = 0; int count = ds.Tables[0].Rows.Count; // No buttons, render nothing if (count == 0) { return(null); } // Prepare the panel pnlButtons = new Panel(); pnlButtons.CssClass = "ActionButtons"; // Prepare the table Table tabGroup = new Table(); TableRow tabGroupRow = new TableRow(); tabGroup.CellPadding = 0; tabGroup.CellSpacing = 0; tabGroup.EnableViewState = false; tabGroupRow.EnableViewState = false; tabGroup.Rows.Add(tabGroupRow); List <Panel> panels = new List <Panel>(); for (int i = 0; i < count; i++) { // Get current and next button UIElementInfo uiElement = new UIElementInfo(ds.Tables[0].Rows[i]); UIElementInfo sel = UIContextHelper.CheckSelectedElement(uiElement, UIContext); if (sel != null) { String selectionSuffix = ValidationHelper.GetString(UIContext["selectionSuffix"], String.Empty); StartingPage = UIContextHelper.GetElementUrl(sel, UIContext) + selectionSuffix; HighlightItem = uiElement.ElementName; } // Raise button creating event if (OnButtonCreating != null) { OnButtonCreating(this, new UniMenuArgs { UIElement = uiElement }); } UIElementInfo uiElementNext = null; if (i < count - 1) { uiElementNext = new UIElementInfo(ds.Tables[0].Rows[i + 1]); } // Set the first button if (mFirstUIElement == null) { mFirstUIElement = uiElement; } // Get the sizes of current and next button. Button is large when it is the only in the group bool isSmall = (uiElement.ElementSize == UIElementSizeEnum.Regular) && (count > 1); bool isResized = (uiElement.ElementSize == UIElementSizeEnum.Regular) && (!isSmall); bool isNextSmall = (uiElementNext != null) && (uiElementNext.ElementSize == UIElementSizeEnum.Regular); // Set the CSS class according to the button size string cssClass = (isSmall ? "SmallButton" : "BigButton"); string elementName = uiElement.ElementName; // Display only caption - do not substitute with Display name when empty string elementCaption = ResHelper.LocalizeString(uiElement.ElementCaption); // Create main button panel CMSPanel pnlButton = new CMSPanel() { ID = "pnlButton" + elementName, ShortID = "b" + elementName }; pnlButton.Attributes.Add("name", elementName); pnlButton.CssClass = cssClass; // Remember the first button if (firstPanel == null) { firstPanel = pnlButton; } // Remember the selected button if ((preselectedPanel == null) && elementName.EqualsCSafe(HighlightItem, true)) { preselectedPanel = pnlButton; // Set the selected button if (mHighlightedUIElement == null) { mHighlightedUIElement = uiElement; } } // URL or behavior string url = uiElement.ElementTargetURL; if (!string.IsNullOrEmpty(url) && url.StartsWithCSafe("javascript:", true)) { pnlButton.Attributes["onclick"] = url.Substring("javascript:".Length); } else { url = UIContextHelper.GetElementUrl(uiElement, UIContext); if (url != String.Empty) { string buttonSelection = (RememberSelectedItem ? "SelectButton(this);" : ""); // Ensure hash code if required url = MacroResolver.Resolve(URLHelper.EnsureHashToQueryParameters(url)); if (!String.IsNullOrEmpty(TargetFrameset)) { if (uiElement.ElementType == UIElementTypeEnum.PageTemplate) { url = URLHelper.UpdateParameterInUrl(url, "displaytitle", "false"); } String target = UseIFrame ? String.Format("frames['{0}']", TargetFrameset) : String.Format("parent.frames['{0}']", TargetFrameset); pnlButton.Attributes["onclick"] = String.Format("{0}{1}.location.href = '{2}';", buttonSelection, target, UrlResolver.ResolveUrl(url)); } else { pnlButton.Attributes["onclick"] = String.Format("{0}self.location.href = '{1}';", buttonSelection, UrlResolver.ResolveUrl(url)); } } } // Tooltip if (!string.IsNullOrEmpty(uiElement.ElementDescription)) { pnlButton.ToolTip = ResHelper.LocalizeString(uiElement.ElementDescription); } else { pnlButton.ToolTip = elementCaption; } pnlButton.EnableViewState = false; // Ensure correct grouping of small buttons if (isSmall && (small == 0)) { small++; Panel pnlSmallGroup = new Panel() { ID = "pnlGroupSmall" + uiElement.ElementName }; if (IsRTL) { pnlSmallGroup.Style.Add("float", "right"); pnlSmallGroup.Style.Add("text-align", "right"); } else { pnlSmallGroup.Style.Add("float", "left"); pnlSmallGroup.Style.Add("text-align", "left"); } pnlSmallGroup.EnableViewState = false; pnlSmallGroup.Controls.Add(pnlButton); panels.Add(pnlSmallGroup); } // Generate button link HyperLink buttonLink = new HyperLink() { ID = "lnkButton" + uiElement.ElementName, EnableViewState = false }; // Generate button image Image buttonImage = new Image() { ID = "imgButton" + uiElement.ElementName, ImageAlign = (isSmall ? ImageAlign.AbsMiddle : ImageAlign.Top), AlternateText = elementCaption, EnableViewState = false }; // Use icon path if (!string.IsNullOrEmpty(uiElement.ElementIconPath)) { string iconPath = GetImagePath(uiElement.ElementIconPath); // Check if element size was changed if (isResized) { // Try to get larger icon string largeIconPath = iconPath.Replace("list.png", "module.png"); if (FileHelper.FileExists(largeIconPath)) { iconPath = largeIconPath; } } buttonImage.ImageUrl = GetImageUrl(iconPath); buttonLink.Controls.Add(buttonImage); } // Use Icon class else if (!string.IsNullOrEmpty(uiElement.ElementIconClass)) { var icon = new CMSIcon { ID = string.Format("ico_{0}_{1}", identifier, i), EnableViewState = false, ToolTip = pnlButton.ToolTip, CssClass = "cms-icon-80 " + uiElement.ElementIconClass }; buttonLink.Controls.Add(icon); } // Load default module icon if ElementIconPath is not specified else { buttonImage.ImageUrl = GetImageUrl("CMSModules/module.png"); buttonLink.Controls.Add(buttonImage); } // Generate caption text Literal captionLiteral = new Literal() { ID = "ltlCaption" + uiElement.ElementName, Text = (isSmall ? "\n" : "<br />") + elementCaption, EnableViewState = false }; buttonLink.Controls.Add(captionLiteral); //Generate button table (IE7 issue) Table tabButton = new Table(); TableRow tabRow = new TableRow(); TableCell tabCellLeft = new TableCell(); TableCell tabCellMiddle = new TableCell(); TableCell tabCellRight = new TableCell(); tabButton.CellPadding = 0; tabButton.CellSpacing = 0; tabButton.EnableViewState = false; tabRow.EnableViewState = false; tabCellLeft.EnableViewState = false; tabCellMiddle.EnableViewState = false; tabCellRight.EnableViewState = false; tabButton.Rows.Add(tabRow); tabRow.Cells.Add(tabCellLeft); tabRow.Cells.Add(tabCellMiddle); tabRow.Cells.Add(tabCellRight); // Generate left border Panel pnlLeft = new Panel() { ID = "pnlLeft" + uiElement.ElementName, CssClass = "Left" + cssClass, EnableViewState = false }; // Generate middle part of button Panel pnlMiddle = new Panel() { ID = "pnlMiddle" + uiElement.ElementName, CssClass = "Middle" + cssClass }; pnlMiddle.Controls.Add(buttonLink); Panel pnlMiddleTmp = new Panel() { EnableViewState = false }; if (isSmall) { pnlMiddle.Style.Add("min-width", smallButtonMinimalWidth + "px"); // IE7 issue with min-width pnlMiddleTmp.Style.Add("width", smallButtonMinimalWidth + "px"); pnlMiddle.Controls.Add(pnlMiddleTmp); } else { pnlMiddle.Style.Add("min-width", bigButtonMinimalWidth + "px"); // IE7 issue with min-width pnlMiddleTmp.Style.Add("width", bigButtonMinimalWidth + "px"); pnlMiddle.Controls.Add(pnlMiddleTmp); } pnlMiddle.EnableViewState = false; // Generate right border Panel pnlRight = new Panel() { ID = "pnlRight" + uiElement.ElementName, CssClass = "Right" + cssClass, EnableViewState = false }; // Add inner controls tabCellLeft.Controls.Add(pnlLeft); tabCellMiddle.Controls.Add(pnlMiddle); tabCellRight.Controls.Add(pnlRight); pnlButton.Controls.Add(tabButton); // If there were two small buttons in a row end the grouping div if ((small == 2) || (isSmall && !isNextSmall)) { small = 0; // Add the button to the small buttons grouping panel panels[panels.Count - 1].Controls.Add(pnlButton); } else { if (small == 0) { // Add the generated button into collection panels.Add(pnlButton); } } if (small == 1) { small++; } // Raise button created event if (OnButtonCreated != null) { OnButtonCreated(this, new UniMenuArgs { UIElement = uiElement, TargetUrl = url, ButtonControl = pnlButton, ImageControl = buttonImage }); } } // Add all panels to control foreach (Panel panel in panels) { TableCell tabGroupCell = new TableCell() { VerticalAlign = VerticalAlign.Top, EnableViewState = false }; tabGroupCell.Controls.Add(panel); tabGroupRow.Cells.Add(tabGroupCell); } pnlButtons.Controls.Add(tabGroup); } return(pnlButtons); }
private string BuildStartupScript() { bool enBBCode = IsSupport || (ChatSettingsProvider.EnableBBCodeSetting && EnableBBCode); WebControl input = enBBCode ? ucBBEditor.TextArea : txtMessage; if (enBBCode) { txtMessage.Visible = false; } else { ucBBEditor.Visible = false; } string json = JsonConvert.SerializeObject( new { roomID = RoomID, inputClientID = GetString(input), buttonClientID = GetString(btnSendMessage), groupID = GroupID, chbWhisperClientID = GetString(chbWhisper), drpRecipientClientID = GetString(drpRecipient), pnlRecipientContainerClientID = GetString(pnlRecipientContainer), noneLabel = ResHelper.GetString("chat.everyone"), enableBBCode = enBBCode, bbCodeClientID = GetString(ucBBEditor), btnCannedResponses = GetString(btnCannedResponses), pnlContent = GetString(pnlWebpartContent), envelopeID = "#envelope_" + ClientID, informDialogID = GetString(pnlChatMessageSendInfoDialog), btnInformDialogClose = GetString(btnChatMessageSendInformDialogClose) }, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml } ); string startupScript = String.Format("InitChatSenderWebpart({0});", json); // If this webpart is for support person -> generate "Canned responses" if ((ChatOnlineUserHelper.GetLoggedInChatUser() != null) && (IsSupport == true)) { // Get canned responses from database IEnumerable <ChatSupportCannedResponseInfo> cannedResponses = ChatSupportCannedResponseInfoProvider.GetCannedResponses(ChatOnlineUserHelper.GetLoggedInChatUser().ChatUserID, SiteContext.CurrentSiteID); if (cannedResponses.Any()) { plcCannedResponses.Visible = true; // Register necessary files ScriptHelper.RegisterScriptFile(Page, "~/CMSWebParts/Chat/ChatMessageSend_files/CannedResponses.js"); CssRegistration.RegisterCssLink(Page, "~/App_Themes/Design/Chat/ChatIntelliSense.css"); // Creates canned responses in format expected in javascript var cannedResponseToSerialize = from cr in cannedResponses let resolvedText = MacroResolver.Resolve(cr.ChatSupportCannedResponseText) select new { label = "#" + HTMLHelper.HTMLEncode(cr.ChatSupportCannedResponseTagName), tooltip = HTMLHelper.HTMLEncode(TextHelper.LimitLength(resolvedText, mTooltipLength)), value = resolvedText }; // Serialize canned responses to JS Array expected by javascript string cannedResponsesJSArray = ""; try { cannedResponsesJSArray = JsonConvert.SerializeObject(cannedResponseToSerialize, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml }); } catch (Exception ex) { EventLogProvider.LogException("Chat", "JSON serialization of canned responses", ex); } startupScript += string.Format("var CannedResponses = {0};", cannedResponsesJSArray); startupScript += string.Format("InitCannedResponses({0}, {1});", ScriptHelper.GetString("#" + input.ClientID), ScriptHelper.GetString("#" + btnCannedResponses.ClientID)); } } return(startupScript); }
/// <summary> /// Prepares the layout of the web part. /// </summary> protected override void PrepareLayout() { StartLayout(); if (IsDesign) { Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">"); if (ViewModeIsDesign()) { Append("<tr><td class=\"LayoutHeader\">"); // Add header container AddHeaderContainer(); Append("</td></tr>"); } Append("<tr><td>"); } // Content before zones Append(BeforeZones); string separator = Separator; string before = BeforeZone; string after = AfterZone; string zoneclass = ZoneCSSClass; string zonewidth = ZoneWidth; // Render the zones for (int i = 1; i <= Zones; i++) { if (i > 1) { Append(separator); } Append("<div"); // Zone class if (!String.IsNullOrEmpty(zoneclass)) { Append(" class=\"", zoneclass, "\""); } // Zone width if (!String.IsNullOrEmpty(zonewidth)) { Append(" style=\"width: ", zonewidth, "\";"); } Append(">", before); // Add the zone CMSWebPartZone zone = AddZone(ID + "_" + i, "[" + i + "]"); Append(after, "</div>"); } // Content after zones Append(AfterZones); if (IsDesign) { Append("</td></tr>"); // Footer if (AllowDesignMode) { Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">"); // Zone actions AppendRemoveAction(ResHelper.GetString("Layout.RemoveZone"), "Zones"); Append(" "); AppendAddAction(ResHelper.GetString("Layout.AddZone"), "Zones"); Append("</div></td></tr>"); } Append("</table>"); } // Register scripts string[] scripts = ScriptFiles.Split('\r', '\n'); foreach (string script in scripts) { // Register the script file string sfile = script.Trim(); if (!String.IsNullOrEmpty(sfile)) { ScriptHelper.RegisterScriptFile(Page, sfile); } } // Add init script string resolvedInitScript = MacroResolver.Resolve(InitScript); if (!string.IsNullOrEmpty(resolvedInitScript)) { ScriptHelper.RegisterStartupScript(this, typeof(string), ShortClientID + "_Init", ScriptHelper.GetScript(resolvedInitScript)); } // Register CSS files string[] cssFiles = CSSFiles.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); Array.ForEach(cssFiles, cssFile => CssRegistration.RegisterCssLink(Page, cssFile.Trim())); // Add inline CSS string inlinecss = MacroResolver.Resolve(InlineCSS); if (!string.IsNullOrEmpty(inlinecss)) { // Add css to page header CssRegistration.RegisterCssBlock(Page, "zonesWithEffectInlineCss_" + ClientID, inlinecss); } FinishLayout(); }
protected void Page_Load(object sender, EventArgs e) { string bannerCategoryCodeName = ValidationHelper.GetString(GetValue("BannerCategoryCodeName"), ""); BannerCategoryInfo bannerCategory = BannerCategoryInfoProvider.GetBannerCategoryInfoFromSiteOrGlobal(bannerCategoryCodeName, SiteContext.CurrentSiteID); if ((bannerCategory == null) || (bannerCategory.BannerCategoryEnabled == false)) { Visible = !HideIfBannerNotFound; return; } if (URLHelper.IsPostback() && KeepPreviousBannerOnPostBack && BannerIDViewState.HasValue) { bannerReused = true; banner = BannerInfoProvider.GetBannerInfo(BannerIDViewState.Value); } // If random banner should be picked or banner from viewstate was not found if (banner == null) { bannerReused = false; // Get random banner from selected category. Decrement hits left for this banner only if page is displayed on the live site. banner = BannerInfoProvider.GetRandomValidBanner(bannerCategory.BannerCategoryID, (currentViewMode.IsLiveSite())); } // Exits if no banner was found if (banner == null) { Visible = !HideIfBannerNotFound; return; } // Store banner id in the viewstate if the same banner should be used if request is postback if (KeepPreviousBannerOnPostBack) { BannerIDViewState = banner.BannerID; } string width = ValidationHelper.GetString(GetValue("Width"), ""); string height = ValidationHelper.GetString(GetValue("Height"), ""); string anchorClass = ValidationHelper.GetString(GetValue("AnchorClass"), ""); bool fakeLink = ValidationHelper.GetBoolean(GetValue("FakeLink"), true); if (width != "") { lnkBanner.Style["width"] = width; } if (height != "") { lnkBanner.Style["height"] = height; } lnkBanner.CssClass = string.Format("CMSBanner {0}", anchorClass).Trim(); lnkBanner.Visible = true; // Do not set link if we are not on the live site. if (currentViewMode.IsOneOf(ViewModeEnum.LiveSite, ViewModeEnum.Preview)) { // Link pointing to our custom handler which logs click and redirects string bannerRedirectURL = URLHelper.ResolveUrl("~/CMSModules/BannerManagement/CMSPages/BannerRedirect.ashx?bannerID=" + banner.BannerID); if (fakeLink) { // By default href attribute will be set to 'nice' URL lnkBanner.Attributes.Add("href", URLHelper.ResolveUrl(banner.BannerURL)); // After clicking href will be set to URL pointing to custom handler which counts clicks lnkBanner.Attributes.Add("onclick", string.Format("this.href='{0}';", bannerRedirectURL)); // GECKO doesn't count middle mouse click as click, so onmouseup (or down) needs to be added lnkBanner.Attributes.Add("onmouseup", string.Format("this.href='{0}';", bannerRedirectURL)); } else { // If faking links is disabled, set href to redirect url lnkBanner.Attributes.Add("href", bannerRedirectURL); } // Add target="_blank" attribute if link should be opened in new window if (banner.BannerBlank) { lnkBanner.Target = "_blank"; } } if (banner.BannerType == BannerTypeEnum.Image) { BannerImageAttributes bannerImageAttributes = BannerManagementHelper.DeserializeBannerImageAttributes(banner.BannerContent); imgBanner.AlternateText = bannerImageAttributes.Alt; imgBanner.ToolTip = bannerImageAttributes.Title; imgBanner.CssClass = bannerImageAttributes.Class; imgBanner.Style.Value = HTMLHelper.HTMLEncode(bannerImageAttributes.Style); imgBanner.ImageUrl = URLHelper.ResolveUrl(bannerImageAttributes.Src); imgBanner.Visible = true; ltrBanner.Visible = false; } else { string text = MacroResolver.Resolve(banner.BannerContent); ltrBanner.Text = HTMLHelper.ResolveUrls(text, null, false); imgBanner.Visible = false; ltrBanner.Visible = true; if (banner.BannerType == BannerTypeEnum.HTML) { ControlsHelper.ResolveDynamicControls(this); } } }
/// <summary> /// Executes the benchmark run /// </summary> /// <param name="benchmark">Benchmark</param> private string Execute(Benchmark <string> benchmark) { return(MacroResolver.Resolve(editorElem.Text)); }
protected void Page_Load(object sender, EventArgs e) { CurrentMaster.PanelContent.RemoveCssClass("dialog-content"); // Set title PageTitle.TitleText = GetString("om.contact.collision"); // Validate hash Regex re = RegexHelper.GetRegex(@"[\w\d_$$]*"); mIdentifier = QueryHelper.GetString("params", ""); if (!QueryHelper.ValidateHash("hash") || !re.IsMatch(mIdentifier)) { pnlContent.Visible = false; return; } // Load dialog parameters Hashtable parameters = (Hashtable)WindowHelper.GetItem(mIdentifier); if (parameters != null) { mMergedAccounts = (DataSet)parameters["MergedAccounts"]; mParentAccount = (AccountInfo)parameters["ParentAccount"]; if (!mParentAccount.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser)) { RedirectToAccessDenied(mParentAccount.TypeInfo.ModuleName, "Read"); } mIsSitemanager = ValidationHelper.GetBoolean(parameters["issitemanager"], false); if (mIsSitemanager) { mStamp = SettingsKeyInfoProvider.GetStringValue("CMSCMStamp"); } else { mStamp = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSCMStamp"); } mStamp = MacroResolver.Resolve(mStamp); if (mParentAccount != null) { // Check permissions AccountHelper.AuthorizedReadAccount(mParentAccount.AccountSiteID, true); // Load data if (!RequestHelper.IsPostBack()) { Initialize(); } LoadContactCollisions(); LoadContactGroups(); LoadCustomFields(); // Init controls btnMerge.Click += new EventHandler(btnMerge_Click); btnStamp.OnClientClick = "AddStamp('" + htmlNotes.CurrentEditor.ClientID + "'); return false;"; ScriptHelper.RegisterTooltip(Page); RegisterScripts(); accountStatusSelector.SiteID = mParentAccount.AccountSiteID; accountSelector.SiteID = mParentAccount.AccountSiteID; accountSelector.WhereCondition = "((AccountMergedWithAccountID IS NULL) AND (AccountSiteID > 0)) OR ((AccountGlobalAccountID IS NULL) AND (AccountSiteID IS NULL))"; accountSelector.WhereCondition = GetSubsidiaryWhere(accountSelector.WhereCondition); // Set tabs tabFields.HeaderText = GetString("om.contact.fields"); tabContacts.HeaderText = GetString("om.contact.list"); tabContactGroups.HeaderText = GetString("om.contactgroup.list"); tabCustomFields.HeaderText = GetString("general.customfields"); } } // User relative messages placeholder so that JQueryTab isn't moved a bit MessagesPlaceHolder.UseRelativePlaceHolder = false; // Do not let the editor overflow dialog window htmlNotes.SetValue("width", "520"); }
object Grid_OnExternalDataBound(object sender, string sourceName, object parameter) { string name = sourceName.ToLowerCSafe(); switch (name) { case "chatmessageauthor": { DataRowView row = (DataRowView)parameter; if (row["AuthorNickname"] == DBNull.Value) { return("<span style=\"color: #777777; font-style: italic;\">" + GetString("chat.system") + "</span>"); } int chatUserID = ValidationHelper.GetInteger(row["ChatMessageUserID"], 0); string nickname = ValidationHelper.GetString(row["AuthorNickname"], "AuthorNickname"); bool isAnonymous = ValidationHelper.GetBoolean(row["AuthorIsAnonymous"], true); return(ChatHelper.GetCMSDeskChatUserField(this, chatUserID, nickname, isAnonymous)); } case "edit": case "reject": case "delete": { DataRowView row = (DataRowView)((GridViewRow)parameter).DataItem; // Whisper message is consider as system here - it can't be rejected or edited ChatMessageTypeEnum msgType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0); bool isSystem = ((msgType != ChatMessageTypeEnum.ClassicMessage) && (msgType != ChatMessageTypeEnum.Announcement)); bool enabled = true; var actionButton = (CMSGridActionButton)sender; if (isSystem) { if (name == "edit" || name == "reject") { // Disable edit and reject buttons for system messages enabled = false; } } else { if (name == "reject") { bool isRejected = ValidationHelper.GetBoolean(row["ChatMessageRejected"], false); if (isRejected) { actionButton.IconCssClass = "icon-check-circle"; actionButton.IconStyle = GridIconStyle.Allow; actionButton.ToolTip = GetString("general.approve"); } } } if (!HasUserModifyPermission && name != "edit") { enabled = false; } actionButton.Enabled = enabled; break; } case "chatmessagesystemmessagetype": { DataRowView row = (DataRowView)parameter; ChatMessageTypeEnum messageType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0); if (messageType == ChatMessageTypeEnum.Whisper) { ChatUserInfo recipient = ChatUserInfoProvider.GetChatUserInfo(ValidationHelper.GetInteger(row["ChatMessageRecipientID"], 0)); if (recipient != null) { // Set text to the format "Whisper to somebody", where somebody may be link to the user if he is not anonymous return(string.Format(ResHelper.GetString("chat.system.cmsdesk.whisperto"), ChatHelper.GetCMSDeskChatUserField(this, recipient))); } } return(messageType.ToStringValue((int)ChatMessageTypeStringValueUsageEnum.CMSDeskDescription)); } case "chatmessagetext": { DataRowView row = (DataRowView)parameter; ChatMessageTypeEnum messageType = (ChatMessageTypeEnum)ValidationHelper.GetInteger(row["ChatMessageSystemMessageType"], 0); string messageText = ValidationHelper.GetString(row["ChatMessageText"], ""); if (messageType.IsSystemMessage()) { messageText = MacroResolver.Resolve(messageText); } return(HTMLHelper.HTMLEncode(messageText)); } } return(parameter); }