void OnAcquireState(object o, EventArgs args) { HttpApplication application = (HttpApplication)o; HttpContext context = application.Context; bool required = (context.Handler is IRequiresSessionState); // This is a hack. Sites that use Session in global.asax event handling code // are not supposed to get a Session object for static files, but seems that // IIS handles those files before getting there and thus they are served without // error. // As a workaround, setting MONO_XSP_STATIC_SESSION variable make this work // on mono, but you lose performance when serving static files. if (sessionForStaticFiles && context.Handler is StaticFileHandler) { required = true; } // hack end if (!required) { return; } bool read_only = (context.Handler is IReadOnlySessionState); bool isNew = false; HttpSessionState session = null; if (handler != null) { session = handler.UpdateContext(context, this, required, read_only, ref isNew); } if (session != null) { if (isNew) { session.SetNewSession(true); } if (read_only) { session = session.Clone(); } context.SetSession(session); HttpRequest request = context.Request; HttpResponse response = context.Response; string id = context.Session.SessionID; if (isNew && config.CookieLess) { request.SetHeader(HeaderName, id); UriBuilder newUri = new UriBuilder(request.Url); newUri.Path = UrlUtils.InsertSessionId(id, request.FilePath); response.Redirect(newUri.Uri.PathAndQuery); } else if (isNew) { HttpCookie cookie = new HttpCookie(CookieName, id); cookie.Path = request.ApplicationPath; context.Response.AppendCookie(cookie); } if (isNew) { OnSessionStart(); HttpSessionState hss = application.Session; if (hss != null) { handler.Touch(hss.SessionID, hss.Timeout); } } } }
protected virtual void ProcessTool() { DnnLink.Visible = false; DnnLinkButton.Visible = false; if ((!string.IsNullOrEmpty(ToolInfo.ToolName))) { if ((ToolInfo.UseButton)) { DnnLinkButton.Visible = HasToolPermissions(ToolInfo.ToolName); DnnLinkButton.Enabled = EnableTool(); DnnLinkButton.Localize = false; DnnLinkButton.CssClass = ToolCssClass; DnnLinkButton.DisabledCssClass = ToolCssClass + " dnnDisabled"; DnnLinkButton.Text = GetText(); DnnLinkButton.ToolTip = GetToolTip(); } else { DnnLink.Visible = HasToolPermissions(ToolInfo.ToolName); DnnLink.Enabled = EnableTool(); DnnLink.Localize = false; if ((DnnLink.Enabled)) { DnnLink.NavigateUrl = BuildToolUrl(); //can't find the page, disable it? if ((string.IsNullOrEmpty(DnnLink.NavigateUrl))) { DnnLink.Enabled = false; } //create popup event else if (ToolInfo.ShowAsPopUp && PortalSettings.EnablePopUps) { // Prevent PageSettings in a popup if SSL is enabled and enforced, which causes redirection/javascript broswer security issues. if (ToolInfo.ToolName == "PageSettings" || ToolInfo.ToolName == "CopyPage" || ToolInfo.ToolName == "NewPage") { if (!(PortalSettings.SSLEnabled && PortalSettings.SSLEnforced)) { DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(DnnLink.NavigateUrl, this, PortalSettings, true, false)); } } else { DnnLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(DnnLink.NavigateUrl, this, PortalSettings, true, false)); } } } DnnLink.CssClass = ToolCssClass; DnnLink.DisabledCssClass = ToolCssClass + " dnnDisabled"; DnnLink.Text = GetText(); DnnLink.ToolTip = GetToolTip(); DnnLink.Target = ToolInfo.LinkWindowTarget; } } }
private string GetHrefWithArgs(string baseHref) => UrlUtils.BuildQueryUrl( baseHref, BuildDict().SelectMany(kvp => kvp.Value.Select(s => new KeyValuePair <string, string>(kvp.Key, s))).ToList() );
private void rtxtException_LinkClicked(object sender, LinkClickedEventArgs e) { UrlUtils.OpenUrlInBrowser(e.LinkText); }
/// ----------------------------------------------------------------------------- /// <summary> /// Contains the functionality to populate the Root aspx page with controls /// </summary> /// <param name="e"></param> /// <remarks> /// - obtain PortalSettings from Current Context /// - set global page settings. /// - initialise reference paths to load the cascading style sheets /// - add skin control placeholder. This holds all the modules and content of the page. /// </remarks> /// ----------------------------------------------------------------------------- protected override void OnInit(EventArgs e) { base.OnInit(e); //set global page settings InitializePage(); //load skin control and register UI js UI.Skins.Skin ctlSkin; if (PortalSettings.EnablePopUps) { ctlSkin = UrlUtils.InPopUp() ? UI.Skins.Skin.GetPopUpSkin(this) : UI.Skins.Skin.GetSkin(this); //register popup js JavaScript.RequestRegistration(CommonJs.jQueryUI); var popupFilePath = HttpContext.Current.IsDebuggingEnabled ? "~/js/Debug/dnn.modalpopup.js" : "~/js/dnn.modalpopup.js"; ClientResourceManager.RegisterScript(this, popupFilePath, FileOrder.Js.DnnModalPopup); } else { ctlSkin = UI.Skins.Skin.GetSkin(this); } // DataBind common paths for the client resource loader ClientResourceLoader.DataBind(); ClientResourceLoader.PreRender += (sender, args) => JavaScript.Register(Page); //check for and read skin package level doctype SetSkinDoctype(); //Manage disabled pages if (PortalSettings.ActiveTab.DisableLink) { if (TabPermissionController.CanAdminPage()) { var heading = Localization.GetString("PageDisabled.Header"); var message = Localization.GetString("PageDisabled.Text"); UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, ModuleMessage.ModuleMessageType.YellowWarning); } else { if (PortalSettings.HomeTabId > 0) { Response.Redirect(Globals.NavigateURL(PortalSettings.HomeTabId), true); } else { Response.Redirect(Globals.GetPortalDomainName(PortalSettings.PortalAlias.HTTPAlias, Request, true), true); } } } //Manage canonical urls if (PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl) { string primaryHttpAlias = null; if (Config.GetFriendlyUrlProvider() == "advanced") //advanced mode compares on the primary alias as set during alias identification { if (PortalSettings.PrimaryAlias != null && PortalSettings.PortalAlias != null) { if (string.Compare(PortalSettings.PrimaryAlias.HTTPAlias, PortalSettings.PortalAlias.HTTPAlias, StringComparison.InvariantCulture) != 0) { primaryHttpAlias = PortalSettings.PrimaryAlias.HTTPAlias; } } } else //other modes just depend on the default alias { if (string.Compare(PortalSettings.PortalAlias.HTTPAlias, PortalSettings.DefaultPortalAlias, StringComparison.InvariantCulture) != 0) { primaryHttpAlias = PortalSettings.DefaultPortalAlias; } } if (primaryHttpAlias != null && string.IsNullOrEmpty(CanonicalLinkUrl))//a primary http alias was identified { var originalurl = Context.Items["UrlRewrite:OriginalUrl"].ToString(); CanonicalLinkUrl = originalurl.Replace(PortalSettings.PortalAlias.HTTPAlias, primaryHttpAlias); if (UrlUtils.IsSecureConnectionOrSslOffload(Request)) { CanonicalLinkUrl = CanonicalLinkUrl.Replace("http://", "https://"); } } } //check if running with known account defaults if (Request.IsAuthenticated && string.IsNullOrEmpty(Request.QueryString["runningDefault"]) == false) { var userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo; var usernameLower = userInfo?.Username?.ToLowerInvariant(); //only show message to default users if ("admin".Equals(usernameLower) || "host".Equals(usernameLower)) { var messageText = RenderDefaultsWarning(); var messageTitle = Localization.GetString("InsecureDefaults.Title", Localization.GlobalResourceFile); UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle, messageText, ModuleMessage.ModuleMessageType.RedError); } } //add CSS links ClientResourceManager.RegisterDefaultStylesheet(this, string.Concat(Globals.ApplicationPath, "/Resources/Shared/stylesheets/dnndefault/7.0.0/default.css")); ClientResourceManager.RegisterIEStylesheet(this, string.Concat(Globals.HostPath, "ie.css")); ClientResourceManager.RegisterStyleSheet(this, string.Concat(ctlSkin.SkinPath, "skin.css"), FileOrder.Css.SkinCss); ClientResourceManager.RegisterStyleSheet(this, ctlSkin.SkinSrc.Replace(".ascx", ".css"), FileOrder.Css.SpecificSkinCss); //add skin to page SkinPlaceHolder.Controls.Add(ctlSkin); ClientResourceManager.RegisterStyleSheet(this, string.Concat(PortalSettings.HomeDirectory, "portal.css"), FileOrder.Css.PortalCss); //add Favicon ManageFavicon(); //ClientCallback Logic ClientAPI.HandleClientAPICallbackEvent(this); //add viewstateuserkey to protect against CSRF attacks if (User.Identity.IsAuthenticated) { ViewStateUserKey = User.Identity.Name; } //set the async postback timeout. if (AJAX.IsEnabled()) { AJAX.GetScriptManager(this).AsyncPostBackTimeout = Host.AsyncTimeout; } }
/// <exclude /> public override RouteData GetRouteData(HttpContextBase context) { if (!SystemSetupFacade.IsSystemFirstTimeInitialized) { return(null); } string localPath = context.Request.Url.LocalPath; if (IsPagePreviewPath(localPath) && PagePreviewContext.TryGetPreviewKey(context.Request, out Guid previewKey)) { var page = PagePreviewContext.GetPage(previewKey); if (page == null) { throw new InvalidOperationException("Not preview information found by key: " + previewKey); } return(new RouteData(this, new C1PageRouteHandler(new PageUrlData(page)))); } if (UrlUtils.IsAdminConsoleRequest(localPath) || IsRenderersPath(localPath)) { return(null); } var urlProvider = PageUrls.UrlProvider; string currentUrl = context.Request.Url.OriginalString; UrlKind urlKind; PageUrlData pageUrlData = urlProvider.ParseUrl(currentUrl, out urlKind); if (pageUrlData == null || urlKind == UrlKind.Renderer) { return(null); } var urlSpace = new UrlSpace(context); // Redirecting friendly urls to public urls if (urlKind == UrlKind.Friendly || urlKind == UrlKind.Redirect || urlKind == UrlKind.Internal) { if (pageUrlData.PathInfo == "/") { pageUrlData.PathInfo = null; } string publicUrl = urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace); if (publicUrl == null) { if (urlKind != UrlKind.Internal) { return(null); } // Rendering internal url if public url is missing } else { return(GetRedirectRoute(publicUrl)); } } Verify.That(urlKind == UrlKind.Public || urlKind == UrlKind.Internal, "Unexpected url kind '{0}", urlKind); bool isPublicUrl = urlKind == UrlKind.Public; if (isPublicUrl) { // If url ends with a trailing slash - doing a redirect. F.e. http://localhost/a/ -> http://localhost/a if (pageUrlData.PathInfo == "/") { pageUrlData.PathInfo = null; return(GetRedirectRoute(urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace))); } // Checking casing in url, so the same page will not appear as a few pages by a crawler string correctUrl = urlProvider.BuildUrl(pageUrlData, UrlKind.Public, urlSpace); Verify.IsNotNull(correctUrl, "Failed to rebuild a public url from url '{0}'", currentUrl); string originalFilePath = new UrlBuilder(currentUrl).RelativeFilePath; string correctFilePath = new UrlBuilder(correctUrl).RelativeFilePath; string decodedOriginalPath = HttpUtility.UrlDecode(originalFilePath); string decodedCorrectFilePath = HttpUtility.UrlDecode(correctFilePath); if (!urlSpace.ForceRelativeUrls && (originalFilePath.Length != correctFilePath.Length && decodedOriginalPath != correctFilePath && decodedOriginalPath != decodedCorrectFilePath) || (string.Compare(originalFilePath, correctFilePath, false, CultureInfo.InvariantCulture) != 0 && string.Compare(originalFilePath, correctFilePath, true, CultureInfo.InvariantCulture) == 0) && decodedOriginalPath != decodedCorrectFilePath) { // redirect to a url with right casing return(GetRedirectRoute(correctUrl)); } } // GetRouteData may be executed multiple times if (!context.Items.Contains(HttpContextItem_C1PageUrl)) { PageUrlData = pageUrlData; } var data = new RouteData(this, new C1PageRouteHandler(pageUrlData)); data.Values.Add(RouteData_PageUrl, pageUrlData); return(data); }
protected void OnCancelClick(object sender, EventArgs e) { Response.Redirect(UrlUtils.PopUpUrl("~/GettingStarted.aspx", this, PortalSettings, false, true)); }
/// ----------------------------------------------------------------------------- /// <summary> /// LoadActions loads the Actions collections /// </summary> /// <remarks> /// </remarks> /// ----------------------------------------------------------------------------- private void LoadActions(HttpRequest request) { _actions = new ModuleActionCollection(); if (PortalSettings.IsLocked) { return; } _moduleGenericActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); int maxActionId = Null.NullInteger; //check if module Implements Entities.Modules.IActionable interface var actionable = _moduleControl as IActionable; if (actionable != null) { _moduleSpecificActions = new ModuleAction(GetNextActionID(), Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile), string.Empty, string.Empty, string.Empty); ModuleActionCollection moduleActions = actionable.ModuleActions; foreach (ModuleAction action in moduleActions) { if (ModulePermissionController.HasModuleAccess(action.Secure, "CONTENT", Configuration)) { if (String.IsNullOrEmpty(action.Icon)) { action.Icon = "edit.gif"; } if (action.ID > maxActionId) { maxActionId = action.ID; } _moduleSpecificActions.Actions.Add(action); if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl")) { action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false); } } } if (_moduleSpecificActions.Actions.Count > 0) { _actions.Add(_moduleSpecificActions); } } //Make sure the Next Action Id counter is correct int actionCount = GetActionsCount(_actions.Count, _actions); if (_nextActionId < maxActionId) { _nextActionId = maxActionId; } if (_nextActionId < actionCount) { _nextActionId = actionCount; } //Custom injection of Module Settings when shared as ViewOnly if (Configuration != null && (Configuration.IsShared && Configuration.IsShareableViewOnly) && TabPermissionController.CanAddContentToPage()) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString("ModulePermissions.Action", Localization.GlobalResourceFile), "ModulePermissions", "", "action_settings.gif", NavigateUrl(TabId, "ModulePermissions", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)), false, SecurityAccessLevel.ViewPermissions, true, false); } else { if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration)) { if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.ModuleSettings, Localization.GlobalResourceFile), ModuleActionType.ModuleSettings, "", "action_settings.gif", NavigateUrl(TabId, "Module", false, "ModuleId=" + ModuleId, "ReturnURL=" + FilterUrl(request)), false, SecurityAccessLevel.Edit, true, false); } } } if (!string.IsNullOrEmpty(Configuration.DesktopModule.BusinessControllerClass)) { //check if module implements IPortable interface, and user has Admin permissions if (Configuration.DesktopModule.IsPortable) { if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "EXPORT", Configuration)) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.ExportModule, Localization.GlobalResourceFile), ModuleActionType.ExportModule, "", "action_export.gif", NavigateUrl(PortalSettings.ActiveTab.TabID, "ExportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)), "", false, SecurityAccessLevel.View, true, false); } if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "IMPORT", Configuration)) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.ImportModule, Localization.GlobalResourceFile), ModuleActionType.ImportModule, "", "action_import.gif", NavigateUrl(PortalSettings.ActiveTab.TabID, "ImportModule", false, "moduleid=" + ModuleId, "ReturnURL=" + FilterUrl(request)), "", false, SecurityAccessLevel.View, true, false); } } if (Configuration.DesktopModule.IsSearchable && Configuration.DisplaySyndicate) { AddSyndicateAction(); } } //help module actions available to content editors and administrators const string permisisonList = "CONTENT,DELETE,EDIT,EXPORT,IMPORT,MANAGE"; if (ModulePermissionController.HasModulePermission(Configuration.ModulePermissions, permisisonList) && request.QueryString["ctl"] != "Help" && !Globals.IsAdminControl()) { AddHelpActions(); } //Add Print Action if (Configuration.DisplayPrint) { //print module action available to everyone AddPrintAction(); } if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Host, "MANAGE", Configuration) && !Globals.IsAdminControl()) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.ViewSource, Localization.GlobalResourceFile), ModuleActionType.ViewSource, "", "action_source.gif", NavigateUrl(TabId, "ViewSource", false, "ModuleId=" + ModuleId, "ctlid=" + Configuration.ModuleControlId, "ReturnURL=" + FilterUrl(request)), false, SecurityAccessLevel.Host, true, false); } if (!Globals.IsAdminControl() && ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE,MANAGE", Configuration)) { if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "DELETE", Configuration)) { //Check if this is the owner instance of a shared module. string confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteModule.Confirm")) + "')"; if (!Configuration.IsShared) { var portal = PortalController.Instance.GetPortal(PortalSettings.PortalId); if (PortalGroupController.Instance.IsModuleShared(Configuration.ModuleID, portal)) { confirmText = "confirm('" + ClientAPI.GetSafeJSString(Localization.GetString("DeleteSharedModule.Confirm")) + "')"; } } _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.DeleteModule, Localization.GlobalResourceFile), ModuleActionType.DeleteModule, Configuration.ModuleID.ToString(), "action_delete.gif", "", confirmText, false, SecurityAccessLevel.View, true, false); } if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) { _moduleGenericActions.Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.ClearCache, Localization.GlobalResourceFile), ModuleActionType.ClearCache, Configuration.ModuleID.ToString(), "action_refresh.gif", "", false, SecurityAccessLevel.View, true, false); } if (ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Admin, "MANAGE", Configuration)) { //module movement AddMenuMoveActions(); } } if (_moduleGenericActions.Actions.Count > 0) { _actions.Add(_moduleGenericActions); } if (_moduleMoveActions != null && _moduleMoveActions.Actions.Count > 0) { _actions.Add(_moduleMoveActions); } foreach (ModuleAction action in _moduleGenericActions.Actions) { if (!UIUtilities.IsLegacyUI(ModuleId, action.ControlKey, PortalId) && action.Url.Contains("ctl")) { action.ClientScript = UrlUtils.PopUpUrl(action.Url, _moduleControl as Control, PortalSettings, true, false); } } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); cmdLogin.Click += OnLoginClick; cmdCancel.Click += OnCancelClick; ClientAPI.RegisterKeyCapture(Parent, cmdLogin, 13); if (PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration) { liRegister.Visible = false; } lblLogin.Text = Localization.GetSystemMessage(PortalSettings, "MESSAGE_LOGIN_INSTRUCTIONS"); if (!string.IsNullOrEmpty(Response.Cookies["USERNAME_CHANGED"].Value)) { txtUsername.Text = Response.Cookies["USERNAME_CHANGED"].Value; DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetSystemMessage(PortalSettings, "MESSAGE_USERNAME_CHANGED_INSTRUCTIONS"), ModuleMessage.ModuleMessageType.BlueInfo); } var returnUrl = Globals.NavigateURL(); string url; if (PortalSettings.UserRegistration != (int)Globals.PortalRegistrationType.NoRegistration) { if (!string.IsNullOrEmpty(UrlUtils.ValidReturnUrl(Request.QueryString["returnurl"]))) { returnUrl = Request.QueryString["returnurl"]; } returnUrl = HttpUtility.UrlEncode(returnUrl); url = Globals.RegisterURL(returnUrl, Null.NullString); registerLink.NavigateUrl = url; if (PortalSettings.EnablePopUps && PortalSettings.RegisterTabId == Null.NullInteger && !HasSocialAuthenticationEnabled()) { registerLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 600, 950)); } } else { registerLink.Visible = false; } //see if the portal supports persistant cookies chkCookie.Visible = Host.RememberCheckbox; // no need to show password link if feature is disabled, let's check this first if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { url = Globals.NavigateURL("SendPassword", "returnurl=" + returnUrl); passwordLink.NavigateUrl = url; if (PortalSettings.EnablePopUps) { passwordLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(url, this, PortalSettings, true, false, 300, 650)); } } else { passwordLink.Visible = false; } if (!IsPostBack) { if (!string.IsNullOrEmpty(Request.QueryString["verificationcode"]) && PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) { if (Request.IsAuthenticated) { Controls.Clear(); } var verificationCode = Request.QueryString["verificationcode"]; try { UserController.VerifyUser(verificationCode.Replace(".", "+").Replace("-", "/").Replace("_", "=")); var redirectTabId = PortalSettings.Registration.RedirectAfterRegistration; if (Request.IsAuthenticated) { Response.Redirect(Globals.NavigateURL(redirectTabId > 0 ? redirectTabId : PortalSettings.HomeTabId, string.Empty, "VerificationSuccess=true"), true); } else { if (redirectTabId > 0) { var redirectUrl = Globals.NavigateURL(redirectTabId, string.Empty, "VerificationSuccess=true"); redirectUrl = redirectUrl.Replace(Globals.AddHTTP(PortalSettings.PortalAlias.HTTPAlias), string.Empty); Response.Cookies.Add(new HttpCookie("returnurl", redirectUrl) { Path = (!string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/") }); } UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("VerificationSuccess", LocalResourceFile), ModuleMessage.ModuleMessageType.GreenSuccess); } } catch (UserAlreadyVerifiedException) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserAlreadyVerified", LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } catch (InvalidVerificationCodeException) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } catch (UserDoesNotExistException) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("UserDoesNotExist", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } catch (Exception) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InvalidVerificationCode", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } } } if (!Request.IsAuthenticated) { if (!Page.IsPostBack) { try { if (Request.QueryString["username"] != null) { txtUsername.Text = Request.QueryString["username"]; } } catch (Exception ex) { //control not there Logger.Error(ex); } } try { Globals.SetFormFocus(string.IsNullOrEmpty(txtUsername.Text) ? txtUsername : txtPassword); } catch (Exception ex) { //Not sure why this Try/Catch may be necessary, logic was there in old setFormFocus location stating the following //control not there or error setting focus Logger.Error(ex); } } var registrationType = PortalSettings.Registration.RegistrationFormType; bool useEmailAsUserName; if (registrationType == 0) { useEmailAsUserName = PortalSettings.Registration.UseEmailAsUserName; } else { var registrationFields = PortalSettings.Registration.RegistrationFields; useEmailAsUserName = !registrationFields.Contains("Username"); } plUsername.Text = LocalizeString(useEmailAsUserName ? "Email" : "Username"); divCaptcha1.Visible = UseCaptcha; divCaptcha2.Visible = UseCaptcha; }
void GenerateClassWrapperForCallbackMethods() { Type objectType = GetType(); StringBuilder sb = new StringBuilder(2048); string nameSpace = GetType().Namespace; string typeId = GetType().Name; if (!string.IsNullOrEmpty(nameSpace)) { if (true) //ClientScriptProxy.IsMsAjax()) { sb.AppendLine("registerNamespace(\"" + nameSpace + "\");"); } sb.AppendLine(nameSpace + "." + typeId + " = { "); } else { sb.AppendLine(typeId + " = { "); } MethodInfo[] Methods = objectType.GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo Method in Methods) { if (Method.GetCustomAttributes(typeof(CallbackMethodAttribute), false).Length > 0) { sb.Append(" " + Method.Name + ": function " + "("); string ParameterList = ""; foreach (ParameterInfo Parm in Method.GetParameters()) { ParameterList += Parm.Name + ","; } sb.Append(ParameterList + "completed,errorHandler)"); sb.AppendFormat(@" {{ var _cb = {0}_GetProxy(); _cb.callMethod(""{1}"",[{2}],completed,errorHandler); return _cb; }}, ", typeId, Method.Name, ParameterList.TrimEnd(',')); } } if (sb.Length > 2) { sb.Length -= 3; // strip trailing ,\r\n } // End of class sb.Append("\r\n}\r\n"); string Url = Request.Path.ToLower().Replace(Request.PathInfo, ""); sb.Append("function " + typeId + @"_GetProxy() { var _cb = new AjaxMethodCallback('" + typeId + "','" + Url + @"'); _cb.serverUrl = '" + Url + @"'; _cb.postbackMode = 'PostMethodParametersOnly'; return _cb; } "); UrlUtils.GZipEncodePage(); Response.ContentType = ControlResources.STR_JavaScriptContentType; HttpContext.Current.Response.Write(sb.ToString()); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Visible) { try { if (LegacyMode) { loginLink.Visible = true; loginGroup.Visible = false; } else { loginLink.Visible = false; loginGroup.Visible = true; } if (!String.IsNullOrEmpty(CssClass)) { loginLink.CssClass = CssClass; enhancedLoginLink.CssClass = CssClass; } if (Request.IsAuthenticated) { if (!String.IsNullOrEmpty(LogoffText)) { if (LogoffText.IndexOf("src=") != -1) { LogoffText = LogoffText.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); } loginLink.Text = LogoffText; enhancedLoginLink.Text = LogoffText; } else { loginLink.Text = Localization.GetString("Logout", Localization.GetResourceFile(this, MyFileName)); enhancedLoginLink.Text = loginLink.Text; loginLink.ToolTip = loginLink.Text; enhancedLoginLink.ToolTip = loginLink.Text; } loginLink.NavigateUrl = Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Logoff"); enhancedLoginLink.NavigateUrl = loginLink.NavigateUrl; } else { if (!String.IsNullOrEmpty(Text)) { if (Text.IndexOf("src=") != -1) { Text = Text.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); } loginLink.Text = Text; enhancedLoginLink.Text = Text; } else { loginLink.Text = Localization.GetString("Login", Localization.GetResourceFile(this, MyFileName)); enhancedLoginLink.Text = loginLink.Text; loginLink.ToolTip = loginLink.Text; enhancedLoginLink.ToolTip = loginLink.Text; } string returnUrl = HttpContext.Current.Request.RawUrl; if (returnUrl.IndexOf("?returnurl=") != -1) { returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); } returnUrl = HttpUtility.UrlEncode(returnUrl); loginLink.NavigateUrl = Globals.LoginURL(returnUrl, (Request.QueryString["override"] != null)); enhancedLoginLink.NavigateUrl = loginLink.NavigateUrl; //avoid issues caused by multiple clicks of login link var oneclick = "this.disabled=true;"; if (Request.UserAgent != null && Request.UserAgent.Contains("MSIE 8.0") == false) { loginLink.Attributes.Add("onclick", oneclick); enhancedLoginLink.Attributes.Add("onclick", oneclick); } if (PortalSettings.EnablePopUps && PortalSettings.LoginTabId == Null.NullInteger && !AuthenticationController.HasSocialAuthenticationEnabled(this)) { //To avoid duplicated encodes of URL var clickEvent = "return " + UrlUtils.PopUpUrl(HttpUtility.UrlDecode(loginLink.NavigateUrl), this, PortalSettings, true, false, 300, 650); loginLink.Attributes.Add("onclick", clickEvent); enhancedLoginLink.Attributes.Add("onclick", clickEvent); } } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } }
static ImageFields GetImageFields(string value, FieldSetting setting, int portalId) { var strFieldvalue = value; var url = string.Empty; var imageUrl = string.Empty; var path = string.Empty; if (strFieldvalue != string.Empty) { if (strFieldvalue.StartsWith("http:") || strFieldvalue.StartsWith("https:")) { imageUrl = strFieldvalue; url = imageUrl; } else { var fileInfo = strFieldvalue.StartsWith("FileID=") ? FileManager.Instance.GetFile(int.Parse(UrlUtils.GetParameterValue(strFieldvalue))) : FileManager.Instance.GetFile(portalId, strFieldvalue); if (fileInfo != null) { imageUrl = FileManager.Instance.GetUrl(fileInfo); path = Path.Combine(fileInfo.Folder, fileInfo.FileName); } var parms = ""; if (setting.Width > 0) { parms = string.Format("{0}&w={1}", parms, setting.Width); } if (setting.Height > 0) { parms = string.Format("{0}&h={1}", parms, setting.Height); } if (parms != "") { url = string.Format("{0}?image={1}{2}&PortalId={3}", Globals.ResolveUrl(string.Format("~{0}MakeThumbnail.ashx", Definition.PathOfModule)), HttpUtility.UrlEncode(path), parms, portalId); } else { url = imageUrl; } } url = HttpUtility.HtmlEncode(url); if (setting.AsLink) { strFieldvalue = string.Format( "<a href=\"{0}\" target=\"_blank\"><img alt=\"{1}\" title=\"{1}\" border=\"0\" src=\"{2}\" /></a>", imageUrl, "{0}", url); } else { strFieldvalue = string.Format("<img alt=\"{0}\" title=\"{0}\" src=\"{1}\" />", "{0}", url); } } var imageFields = new ImageFields { Value = strFieldvalue, Original = value, Url = url }; return(imageFields); }
private void AddPositionFolders(EntityToken entityToken, List <Element> list) { var page = PageManager.GetPageById(new Guid(entityToken.Source)); IList <Tuple <string, string> > positions; if (!TemplateTeaserPositions.TryGetValue(page.TemplateId, out positions)) { return; } foreach (var position in positions) { var elementHandle = _context.CreateElementHandle(new PageTeaserPositionFolderEntityToken(page, position.Item1)); var positionElement = new Element(elementHandle) { VisualData = new ElementVisualizedData { Label = position.Item2, ToolTip = position.Item2, HasChildren = TeaserFacade.GetPageTeasers(page, position.Item1, false).Any(), Icon = new ResourceHandle("Composite.Icons", "folder"), OpenedIcon = new ResourceHandle("Composite.Icons", "folder_active"), } }; var addActionToken = new WorkflowActionToken(typeof(AddPageTeaserWorkFlow), new[] { PermissionType.Add }); positionElement.AddAction(new ElementAction(new ActionHandle(addActionToken)) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("CompositeC1Contrib.Teasers", "TeaserElementAttachingProvider.Add.Label"), ToolTip = StringResourceSystemFacade.GetString("CompositeC1Contrib.Teasers", "TeaserElementAttachingProvider.Add.ToolTip"), Icon = new ResourceHandle("Composite.Icons", "generated-type-data-add"), ActionLocation = ActionLocation } }); var url = String.Format("InstalledPackages/CompositeC1Contrib.Teasers/SortPageTeasers.aspx?pageId={0}&position={1}", page.Id, position.Item1); var sortActionToken = new UrlActionToken(StringResourceSystemFacade.GetString("CompositeC1Contrib.Teasers", "TeaserElementAttachingProvider.SortItems"), UrlUtils.ResolveAdminUrl(url), new[] { PermissionType.Add, PermissionType.Edit, PermissionType.Administrate, }); positionElement.AddAction(new ElementAction(new ActionHandle(sortActionToken)) { VisualData = new ActionVisualizedData { Label = StringResourceSystemFacade.GetString("CompositeC1Contrib.Teasers", "TeaserElementAttachingProvider.Sort.Label"), ToolTip = StringResourceSystemFacade.GetString("CompositeC1Contrib.Teasers", "TeaserElementAttachingProvider.Sort.ToolTip"), Icon = new ResourceHandle("Composite.Icons", "cut"), ActionLocation = ActionLocation } }); list.Add(positionElement); } }
public void ProcessRequest(System.Web.HttpContext context) { PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings(); int TabId = -1; int ModuleId = -1; try { if (context.Request.QueryString["tabid"] != null) { Int32.TryParse(context.Request.QueryString["tabid"], out TabId); } if (context.Request.QueryString["mid"] != null) { Int32.TryParse(context.Request.QueryString["mid"], out ModuleId); } } catch (Exception ex) { ex.ToString(); throw new HttpException(404, "Not Found"); } string Language = _portalSettings.DefaultLanguage; if (context.Request.QueryString["language"] != null) { Language = context.Request.QueryString["language"]; } else { if (context.Request.Cookies["language"] != null) { Language = context.Request.Cookies["language"].Value; } } if (Localization.Localization.LocaleIsEnabled(Language)) { System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(Language); Localization.Localization.SetLanguage(Language); } string URL = ""; bool blnClientCache = true; bool blnForceDownload = false; if (context.Request.QueryString["fileticket"] != null) { URL = "FileID=" + UrlUtils.DecryptParameter(context.Request.QueryString["fileticket"]); } if (context.Request.QueryString["userticket"] != null) { URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]); } if (context.Request.QueryString["link"] != null) { URL = context.Request.QueryString["link"]; if (URL.ToLowerInvariant().StartsWith("fileid=")) { URL = ""; } } if (!String.IsNullOrEmpty(URL)) { UrlController objUrls = new UrlController(); objUrls.UpdateUrlTracking(_portalSettings.PortalId, URL, ModuleId, -1); TabType UrlType = Globals.GetURLType(URL); if (UrlType != TabType.File) { URL = Common.Globals.LinkClick(URL, TabId, ModuleId, false); } if (UrlType == TabType.File && URL.ToLowerInvariant().StartsWith("fileid=") == false) { FileController objFiles = new FileController(); URL = "FileID=" + objFiles.ConvertFilePathToFileId(URL, _portalSettings.PortalId); } if (context.Request.QueryString["clientcache"] != null) { blnClientCache = bool.Parse(context.Request.QueryString["clientcache"]); } if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null)) { blnForceDownload = bool.Parse(context.Request.QueryString["forcedownload"]); } context.Response.Clear(); try { switch (UrlType) { case TabType.File: if (TabId == Null.NullInteger) { if (!FileSystemUtils.DownloadFile(_portalSettings.PortalId, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload)) { throw new HttpException(404, "Not Found"); } } else { if (!FileSystemUtils.DownloadFile(_portalSettings, int.Parse(UrlUtils.GetParameterValue(URL)), blnClientCache, blnForceDownload)) { throw new HttpException(404, "Not Found"); } } break; case TabType.Url: if (objUrls.GetUrl(_portalSettings.PortalId, URL) != null) { context.Response.Redirect(URL, true); } break; default: context.Response.Redirect(URL, true); break; } } catch (ThreadAbortException ex) { ex.ToString(); } catch (Exception ex) { ex.ToString(); throw new HttpException(404, "Not Found"); } } else { throw new HttpException(404, "Not Found"); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { if (!String.IsNullOrEmpty(CssClass)) { loginLink.CssClass = CssClass; } if (Request.IsAuthenticated) { if (!String.IsNullOrEmpty(LogoffText)) { if (LogoffText.IndexOf("src=") != -1) { LogoffText = LogoffText.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); } loginLink.Text = LogoffText; } else { loginLink.Text = Localization.GetString("Logout", Localization.GetResourceFile(this, MyFileName)); } loginLink.NavigateUrl = Globals.NavigateURL(PortalSettings.ActiveTab.TabID, "Logoff"); } else { if (!String.IsNullOrEmpty(Text)) { if (Text.IndexOf("src=") != -1) { Text = Text.Replace("src=\"", "src=\"" + PortalSettings.ActiveTab.SkinPath); } loginLink.Text = Text; } else { loginLink.Text = Localization.GetString("Login", Localization.GetResourceFile(this, MyFileName)); } string returnUrl = HttpContext.Current.Request.RawUrl; if (returnUrl.IndexOf("?returnurl=") != -1) { returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); } returnUrl = HttpUtility.UrlEncode(returnUrl); loginLink.NavigateUrl = Globals.LoginURL(returnUrl, (Request.QueryString["override"] != null)); if (PortalSettings.EnablePopUps && PortalSettings.LoginTabId == Null.NullInteger) { loginLink.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(loginLink.NavigateUrl, this, PortalSettings, true, false, 300, 650)); } } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } }
private void ShowRoleDialog() { if (_talkIndex >= _wordsList.Count) { EndDialog(); return; } var currentWords = _wordsList[_talkIndex]; const char ch = (char)1; currentWords = currentWords.Replace("[playername]", "[00ff00]" + MeVo.instance.Name + "[-]"); //替换玩家名字显示 var currentList = currentWords.Replace("#r", ch.ToString()).Split(ch); HideAllBust(); canSwitch = false; if (_currentSpeak == NpcSpeaker) { _playerHead.gameObject.SetActive(false); _npcHead.gameObject.SetActive(true); _dialogPlayerLabel.SetActive(false); _dialogNpcLabel.SetActive(true); SetDialogTypeWriter(20); _dialogLabel.supportEncoding = true; _dialogLabel.text = currentList[0]; var scale = _speakBackground.transform.localScale; scale.x = 1; _speakBackground.transform.localScale = scale; _npcNameLabel.text = _currentSysNpcVo.name; _npcSprite.atlas = AtlasManager.Instance.GetAtlas(AtlasManager.Header); _npcSprite.spriteName = _currentSysNpcVo.npcId.ToString(); _npcSprite.SetActive(false); NPCBustMgr.Instance.GetBust(UrlUtils.npcBustUrl(_currentSysNpcVo.model.ToString()), NPCBustLoaded); } else if (_currentSpeak == PlayerSpeaker) { if (currentList.Length > 1) { _npcHead.gameObject.SetActive(false); _playerHead.gameObject.SetActive(true); _dialogPlayerLabel.SetActive(true); _dialogNpcLabel.SetActive(false); SetDialogTypeWriter(20); _dialogLabel.supportEncoding = true; _dialogLabel.text = currentList[1]; var scale = _speakBackground.transform.localScale; scale.x = -1; _speakBackground.transform.localScale = scale; _playerNameLabel.text = MeVo.instance.Name; _playerSprite.atlas = AtlasManager.Instance.GetAtlas(AtlasManager.Header); _playerSprite.spriteName = "101"; _playerSprite.SetActive(false); NPCBustMgr.Instance.GetBust(MeVo.instance.BustUrl, RoleBustLoaded); } else { EndDialog(); } } }
/// <summary> /// Set startUrls of Spider. /// Prior to startUrls of Site. /// </summary> /// <param name="startUrls"></param> /// <returns></returns> public Spider AddStartUrls(IList <string> startUrls) { CheckIfRunning(); Site.StartRequests.AddRange(UrlUtils.ConvertToRequests(startUrls, 1)); return(this); }
public void SubmitFeed(IList <string> asinList, PublishedStatuses overrideStatus) { using (var db = _dbFactory.GetRWDb()) { var toDate = _time.GetAppNowTime().AddHours(-2); IList <ItemDTO> itemsToSubmit; if (asinList == null || !asinList.Any()) { itemsToSubmit = (from i in db.Items.GetAll() join l in db.Listings.GetAll() on i.Id equals l.ItemId where (i.ItemPublishedStatus == (int)PublishedStatuses.None || i.ItemPublishedStatus == (int)PublishedStatuses.New || i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors || i.ItemPublishedStatus == (int)PublishedStatuses.HasChanges || i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithProductId || i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithSKU || ((i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress || i.ItemPublishedStatus == (int)PublishedStatuses.ChangesSubmited) && (i.ItemPublishedStatusDate < toDate || !i.ItemPublishedStatusDate.HasValue))) //NOTE: Added in-progress statuses if items in it more then one day && i.Market == (int)_api.Market //&& !String.IsNullOrEmpty(i.Barcode) && i.StyleItemId.HasValue && !l.IsRemoved && !String.IsNullOrEmpty(i.Barcode) select new ItemDTO() { Id = i.Id, PuclishedStatusDate = i.ItemPublishedStatusDate, CreateDate = i.CreateDate, ParentASIN = i.ParentASIN, }) .ToList(); } else { itemsToSubmit = (from i in db.Items.GetAll() join l in db.Listings.GetAll() on i.Id equals l.ItemId where i.Market == (int)_api.Market && !l.IsRemoved //&& !String.IsNullOrEmpty(i.Barcode) && i.StyleItemId.HasValue && asinList.Contains(l.SKU) select new ItemDTO() { Id = i.Id, PuclishedStatusDate = i.ItemPublishedStatusDate, CreateDate = i.CreateDate, ParentASIN = i.ParentASIN, }) .ToList(); } //NOTE: Need to submit items with group, otherwise we have incorrect color variations calculation, and sometimes image calculation var parentInfoQuery = from i in itemsToSubmit group i by i.ParentASIN into byParent select new { ParentASIN = byParent.Key, ItemPublishedStatusDate = byParent.Min(i => i.PuclishedStatusDate ?? i.CreateDate) }; var parentASINList = parentInfoQuery .OrderBy(pi => pi.ItemPublishedStatusDate) .Select(pi => pi.ParentASIN) //NOTE: Walmart has issue with large request ("(413) Request Entity Too Large.") .ToList(); var itemDtoList = db.Items.GetAllActualExAsDto() .Where(i => parentASINList.Contains(i.ParentASIN) && i.Market == (int)_api.Market && !String.IsNullOrEmpty(i.Barcode)).ToList(); _log.Info("Parent ASIN Count to submit=" + parentASINList.Count + ", item actually submitted=" + itemDtoList.Count + " (items in queue to submit: " + itemsToSubmit.Count + ")"); _log.Info("SKUs to submit: " + String.Join(", ", itemDtoList.Select(i => i.SKU))); if (overrideStatus != PublishedStatuses.None) { var toOverrideItems = itemDtoList.Where(i => asinList.Contains(i.SKU)).ToList(); toOverrideItems.ForEach(i => i.PublishedStatus = (int)overrideStatus); } //var parentASINList = dbItems.Select(i => i.ParentASIN).Distinct().ToList(); var parentItemDtoList = db.ParentItems.GetAllAsDto().Where(p => parentASINList.Contains(p.ASIN) && p.Market == (int)_api.Market) .ToList(); var styleIdList = itemDtoList.Where(i => i.StyleId.HasValue).Select(i => i.StyleId.Value).ToList(); var styleList = db.Styles.GetAllAsDtoEx().Where(s => styleIdList.Contains(s.Id)).ToList(); var allStyleImageList = db.StyleImages.GetAllAsDto().Where(sim => styleIdList.Contains(sim.StyleId) && sim.Category != (int)StyleImageCategories.Deleted).ToList(); var allFeatures = db.FeatureValues.GetValuesByStyleIds(styleIdList); var allBrandMappings = db.WalmartBrandInfoes.GetAllAsDto().ToList(); foreach (var item in itemDtoList) { var parent = parentItemDtoList.FirstOrDefault(p => p.ASIN == item.ParentASIN); if (parent != null && parent.OnHold) { item.OnHold = parent.OnHold; } var styleForItem = styleList.FirstOrDefault(s => s.Id == item.StyleId); var features = allFeatures.Where(f => f.StyleId == item.StyleId).ToList(); var subLiscense = StyleFeatureHelper.GetFeatureValue( features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SUB_LICENSE1)); var mainLicense = StyleFeatureHelper.PrepareMainLicense( StyleFeatureHelper.GetFeatureValue( features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MAIN_LICENSE)), subLiscense); var brand = StringHelper.GetFirstNotEmpty(mainLicense, styleForItem.Manufacturer); var brandMapping = allBrandMappings.FirstOrDefault(b => b.GlobalBrandLicense == brand && StringHelper.ContainsNoCase(b.Character, subLiscense)); if (brandMapping == null) { var brandMappingCandidates = allBrandMappings.Where(b => b.GlobalBrandLicense == brand).ToList(); if (brandMappingCandidates.Count == 1) { brandMapping = brandMappingCandidates.FirstOrDefault(); } } var character = StringHelper.GetFirstNotEmpty(brandMapping?.Character, StyleFeatureHelper.GetFeatureValueByName(features, StyleFeatureHelper.MAIN_CHARACTER_KEY)); StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.MAIN_CHARACTER_KEY, character); var globalLicense = StringHelper.GetFirstNotEmpty(brandMapping?.GlobalBrandLicense, brand); StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.GLOBAL_LICENSE_KEY, globalLicense); brand = StringHelper.GetFirstNotEmpty(brandMapping?.Brand, brand); StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.BRAND_KEY, brand); if (String.IsNullOrEmpty(styleForItem.BulletPoint1)) { var material = StyleFeatureHelper.GetFeatureValue( features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MATERIAL)); var gender = StyleFeatureHelper.GetFeatureValue( features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.GENDER)); var bulletPoints = ExportDataHelper.BuildKeyFeatures(mainLicense, subLiscense, material, gender); styleForItem.BulletPoint1 = bulletPoints.Count > 0 ? bulletPoints[0] : null; styleForItem.BulletPoint2 = bulletPoints.Count > 1 ? bulletPoints[1] : null; styleForItem.BulletPoint3 = bulletPoints.Count > 2 ? bulletPoints[2] : null; styleForItem.BulletPoint4 = bulletPoints.Count > 3 ? bulletPoints[3] : null; styleForItem.BulletPoint5 = bulletPoints.Count > 4 ? bulletPoints[4] : null; item.Features = String.Join(";", bulletPoints); } else { //var itemStyleValue = WalmartUtils.GetFeatureValue(allFeatures.Where(f => f.StyleId == itemStyle.Id).ToList(), StyleFeatureHelper.ITEMSTYLE); item.Features = String.Join(";", StyleFeatureHelper.PrepareBulletPoints(new string[] { styleForItem.BulletPoint1, styleForItem.BulletPoint2, styleForItem.BulletPoint3, styleForItem.BulletPoint4, styleForItem.BulletPoint5, })); } } //Exclude OnHold (after ParentItem onHold was applied) //itemDtoList = itemDtoList.Where(i => !i.OnHold).ToList(); foreach (var styleImage in allStyleImageList) { try { var styleString = styleList.FirstOrDefault(s => s.Id == styleImage.StyleId)?.StyleID; var filepath = ImageHelper.BuildWalmartImage(_walmartImageDirectory, styleImage.Image, styleString + "_" + MD5Utils.GetMD5HashAsString(styleImage.Image)); var filename = Path.GetFileName(filepath); styleImage.Image = UrlUtils.CombinePath(_walmartImageBaseUrl, filename); } catch (Exception ex) { _log.Info("BuildWalmartImage error, image=" + styleImage.Image, ex); } } foreach (var style in styleList) { //var styleImages = allStyleImageList.Where(sim => sim.StyleId == style.Id).ToList(); //var styleImage = styleImages.Where(si => si.Type == (int) StyleImageType.LoRes // || si.Type == (int) StyleImageType.HiRes) // .OrderByDescending(si => si.Type) //First Hi-res // .ThenBy(si => si.IsSystem) //First not system // .ThenByDescending(si => si.IsDefault) //First isDefault // .FirstOrDefault(); //if (styleImage != null) // style.Image = styleImage.Image; //Set to Hi-res try { var swatchImage = style.Image; var swatchImageObj = allStyleImageList.FirstOrDefault(st => st.Id == style.Id && st.Category == (int)StyleImageCategories.Swatch); if (swatchImageObj != null) { swatchImage = swatchImageObj.Image; } var filepath = ImageHelper.BuildSwatchImage(_swatchImageDirectory, swatchImage); var filename = Path.GetFileName(filepath); style.SwatchImage = UrlUtils.CombinePath(_swatchImageBaseUrl, filename); } catch (Exception ex) { _log.Info("BuildSwatchImage error, image=" + style.Image, ex); } } if (itemDtoList.Any()) { _log.Info("Items to submit=" + String.Join(", ", itemDtoList.Select(i => i.SKU).ToList())); var newFeed = new Feed() { Market = (int)Market, MarketplaceId = MarketplaceId, Type = (int)FeedType, Status = (int)FeedStatus.Submitted, MessageCount = itemDtoList.Count, SubmitDate = _time.GetAppNowTime() }; db.Feeds.Add(newFeed); db.Commit(); _log.Info("Feed id=" + newFeed.Id); IList <FeedMessageDTO> messages; var submitResult = _api.SubmitItemsFeed(newFeed.Id.ToString(), itemDtoList, parentItemDtoList, styleList, allStyleImageList, allFeatures, _feedBaseDirectory, out messages); #region Update item errors var itemIds = itemDtoList.Select(i => i.Id).ToList(); //Remove all exist errors var dbExistErrors = db.ItemAdditions.GetAll().Where(i => itemIds.Contains(i.ItemId) && (i.Field == ItemAdditionFields.PrePublishError)).ToList(); foreach (var dbExistError in dbExistErrors) { db.ItemAdditions.Remove(dbExistError); } foreach (var message in messages) { db.ItemAdditions.Add(new Core.Entities.Listings.ItemAddition() { ItemId = (int)message.ItemId.Value, Field = ItemAdditionFields.PrePublishError, Value = message.Message, Source = newFeed.Id.ToString(), CreateDate = _time.GetAppNowTime(), }); } db.Commit(); #endregion if (submitResult.IsSuccess) { _log.Info("Walmart feed id=" + submitResult.Data); newFeed.AmazonIdentifier = submitResult.Data.AmazonIdentifier; newFeed.RequestFilename = submitResult.Data.RequestFilename; db.Commit(); var dbItems = db.Items.GetAll().Where(i => itemIds.Contains(i.Id)).ToList(); foreach (var item in dbItems) { _log.Info("Mark item as in-progress, id=" + item.Id); item.ItemPublishedStatusBeforeRepublishing = item.ItemPublishedStatus; item.ItemPublishedStatus = (int)PublishedStatuses.ChangesSubmited; item.ItemPublishedStatusDate = _time.GetAppNowTime(); } db.Commit(); foreach (var item in itemDtoList) { db.FeedItems.Add(new Core.Entities.Feeds.FeedItem() { FeedId = newFeed.Id, ItemId = item.Id, }); db.Commit(); } _log.Info("Feed submitted, feedId=" + newFeed.AmazonIdentifier); } else { _log.Fatal("Feed DIDN'T submitted, mark feed as deleted"); newFeed.Status = (int)FeedStatus.SubmissionFail; db.Commit(); throw new Exception("Unable to submit feed, submission status failed. Details: " + submitResult.Message); } } } }
public string EncryptTicket(EncryptTicketDTO dto) { return(UrlUtils.EncryptParameter(UrlUtils.GetParameterValue(dto.Url))); }
/// ----------------------------------------------------------------------------- /// <summary> /// This handler handles requests for LinkClick.aspx, but only those specifc /// to file serving /// </summary> /// <param name="context">System.Web.HttpContext)</param> /// <remarks> /// </remarks> /// <history> /// [cpaterra] 4/19/2006 Created /// </history> /// ----------------------------------------------------------------------------- public void ProcessRequest(HttpContext context) { PortalSettings _portalSettings = PortalController.GetCurrentPortalSettings(); int TabId = -1; int ModuleId = -1; try { //get TabId if (context.Request.QueryString["tabid"] != null) { Int32.TryParse(context.Request.QueryString["tabid"], out TabId); } //get ModuleId if (context.Request.QueryString["mid"] != null) { Int32.TryParse(context.Request.QueryString["mid"], out ModuleId); } } catch (Exception) { //The TabId or ModuleId are incorrectly formatted (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } //get Language string Language = _portalSettings.DefaultLanguage; if (context.Request.QueryString["language"] != null) { Language = context.Request.QueryString["language"]; } else { if (context.Request.Cookies["language"] != null) { Language = context.Request.Cookies["language"].Value; } } if (LocaleController.Instance.IsEnabled(ref Language, _portalSettings.PortalId)) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(Language); Localization.Localization.SetLanguage(Language); } //get the URL string URL = ""; bool blnClientCache = true; bool blnForceDownload = false; if (context.Request.QueryString["fileticket"] != null) { URL = "FileID=" + UrlUtils.DecryptParameter(context.Request.QueryString["fileticket"]); } if (context.Request.QueryString["userticket"] != null) { URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]); } if (context.Request.QueryString["link"] != null) { URL = context.Request.QueryString["link"]; if (URL.ToLowerInvariant().StartsWith("fileid=")) { URL = ""; //restrict direct access by FileID } } if (!String.IsNullOrEmpty(URL)) { //update clicks, this must be done first, because the url tracker works with unmodified urls, like tabid, fileid etc var objUrls = new UrlController(); objUrls.UpdateUrlTracking(_portalSettings.PortalId, URL, ModuleId, -1); TabType UrlType = Globals.GetURLType(URL); if (UrlType == TabType.Tab) { //verify whether the tab is exist, otherwise throw out 404. if (new TabController().GetTab(int.Parse(URL), _portalSettings.PortalId, false) == null) { Exceptions.Exceptions.ProcessHttpException(); } } if (UrlType != TabType.File) { URL = Globals.LinkClick(URL, TabId, ModuleId, false); } if (UrlType == TabType.File && URL.ToLowerInvariant().StartsWith("fileid=") == false) { //to handle legacy scenarios before the introduction of the FileServerHandler var fileName = Path.GetFileName(URL); var folderPath = URL.Substring(0, URL.LastIndexOf(fileName)); var folder = FolderManager.Instance.GetFolder(_portalSettings.PortalId, folderPath); var file = FileManager.Instance.GetFile(folder, fileName); URL = "FileID=" + file.FileId; } //get optional parameters if (context.Request.QueryString["clientcache"] != null) { blnClientCache = bool.Parse(context.Request.QueryString["clientcache"]); } if ((context.Request.QueryString["forcedownload"] != null) || (context.Request.QueryString["contenttype"] != null)) { blnForceDownload = bool.Parse(context.Request.QueryString["forcedownload"]); } var contentDisposition = blnForceDownload ? ContentDisposition.Attachment : ContentDisposition.Inline; //clear the current response context.Response.Clear(); var fileManager = FileManager.Instance; try { switch (UrlType) { case TabType.File: var download = false; var file = fileManager.GetFile(int.Parse(UrlUtils.GetParameterValue(URL))); if (file != null) { try { var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); var directUrl = fileManager.GetUrl(file); if (directUrl.Contains("LinkClick") || (blnForceDownload && folderMapping.FolderProviderType == "StandardFolderProvider")) { fileManager.WriteFileToResponse(file, contentDisposition); download = true; } else { context.Response.Redirect(directUrl, /*endResponse*/ true); } } catch (PermissionsNotMetException) { if (context.Request.IsAuthenticated) { context.Response.Redirect(Globals.AccessDeniedURL(Localization.Localization.GetString("FileAccess.Error")), true); } else { context.Response.Redirect(Globals.AccessDeniedURL(), true); } } catch (Exception ex) { DnnLog.Error(ex); } } if (!download) { Exceptions.Exceptions.ProcessHttpException(URL); } break; case TabType.Url: //prevent phishing by verifying that URL exists in URLs table for Portal if (objUrls.GetUrl(_portalSettings.PortalId, URL) != null) { context.Response.Redirect(URL, true); } break; default: //redirect to URL context.Response.Redirect(URL, true); break; } } catch (ThreadAbortException exc) { DnnLog.Error(exc); } catch (Exception) { Exceptions.Exceptions.ProcessHttpException(URL); } } else { Exceptions.Exceptions.ProcessHttpException(URL); } }
public RedirectsController(IUrlShortenerService urlShortenerService) { this.urlShortenerService = urlShortenerService; urlUtils = new UrlUtils(); }
public IActionResult Index(Microsoft.AspNetCore.Http.HttpRequest request, JObject userAttributes) { if (request != null) { try { userAttributes.Add(IdpConstants.SUBJECT, new Newtonsoft.Json.Linq.JValue(request.Form[IdpConstants.USERNAME])); userAttributes.Add(IdpConstants.AUTH_INST, new Newtonsoft.Json.Linq.JValue(DateTime.UtcNow)); } catch (ArgumentException) { userAttributes[IdpConstants.SUBJECT] = new Newtonsoft.Json.Linq.JValue(request.Form[IdpConstants.USERNAME]); userAttributes[IdpConstants.AUTH_INST] = new Newtonsoft.Json.Linq.JValue(DateTime.UtcNow); } HttpResponseMessage response = null; using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { // For simplicity, trust any certificate. Do not use in production. httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); }; using (HttpClient client = new HttpClient(httpClientHandler)) { try { string authenticationString = _configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.ADAPTER_USERNAME) + ":" + _configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.ADAPTER_PASSWORD); string base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString)); client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64EncodedAuthenticationString); client.DefaultRequestHeaders.Add(IdpConstants.PING_ADAPTER_HEADER, _configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.ADAPTER_ID)); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent content = new StringContent(Convert.ToString(userAttributes), Encoding.UTF8, "application/json"); // Drop the attributes into PingFederate response = client.PostAsync(UrlUtils.dropoffUrl(_configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.BASE_PF_URL)), content).Result; response.EnsureSuccessStatusCode(); } catch (HttpRequestException e) { // proper logging here is omitted for simplicity Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } } } String responseBody = response.Content.ReadAsStringAsync().Result; dynamic responseBodyJson = JsonConvert.DeserializeObject <dynamic>(responseBody); ViewData["resumePath"] = request.Form[IdpConstants.RESUME_PATH]; ViewData["resumeUrl"] = UrlUtils.resumeUrl(request); ViewData["REF"] = responseBodyJson[IdpConstants.REF]; ViewData["responseBody"] = responseBodyJson; ViewData["dropoffEndpoint"] = IdpConstants.DROPOFF_ENDPOINT; ViewData["configureUrl"] = UrlUtils.configureUrl(request); ViewData["httpStatus"] = ReferenceIdAdapterUtil.httpStatus(response.StatusCode); ViewData["rawRequest"] = ReferenceIdAdapterUtil.dropoffPost(_configuration, Convert.ToString(userAttributes)); ViewData["rawResponse"] = ReferenceIdAdapterUtil.sessionResponse(response.Headers, responseBodyJson); ViewData["showData"] = true; ViewData["userAttributes"] = userAttributes; ViewData["ssoUrl"] = UrlUtils.ssoUrl(_configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.BASE_PF_URL), _configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.PARTNER_ENTITY_ID)); return(View()); } else { ViewData["configureUrl"] = UrlUtils.configureUrl(request); ViewData["ssoUrl"] = UrlUtils.ssoUrl(_configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.BASE_PF_URL), _configuration.GetValue <string>(IdpConstants.ADAPTER_CONFIG_SECTION + ":" + IdpConstants.PARTNER_ENTITY_ID)); return(View("~/Views/Error/Index.cshtml")); } }
/// ----------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <remarks> /// - Obtain PortalSettings from Current Context /// - redirect to a specific tab based on name /// - if first time loading this page then reload to avoid caching /// - set page title and stylesheet /// - check to see if we should show the Assembly Version in Page Title /// - set the background image if there is one selected /// - set META tags, copyright, keywords and description /// </remarks> /// ----------------------------------------------------------------------------- private void InitializePage() { //There could be a pending installation/upgrade process if (InstallBlocker.Instance.IsInstallInProgress()) { Exceptions.ProcessHttpException(new HttpException(503, Localization.GetString("SiteAccessedWhileInstallationWasInProgress.Error", Localization.GlobalResourceFile))); } //Configure the ActiveTab with Skin/Container information PortalSettingsController.Instance().ConfigureActiveTab(PortalSettings); //redirect to a specific tab based on name if (!String.IsNullOrEmpty(Request.QueryString["tabname"])) { TabInfo tab = TabController.Instance.GetTabByName(Request.QueryString["TabName"], PortalSettings.PortalId); if (tab != null) { var parameters = new List <string>(); //maximum number of elements for (int intParam = 0; intParam <= Request.QueryString.Count - 1; intParam++) { switch (Request.QueryString.Keys[intParam].ToLowerInvariant()) { case "tabid": case "tabname": break; default: parameters.Add( Request.QueryString.Keys[intParam] + "=" + Request.QueryString[intParam]); break; } } Response.Redirect(Globals.NavigateURL(tab.TabID, Null.NullString, parameters.ToArray()), true); } else { //404 Error - Redirect to ErrorPage Exceptions.ProcessHttpException(Request); } } string cacheability = Request.IsAuthenticated ? Host.AuthenticatedCacheability : Host.UnauthenticatedCacheability; switch (cacheability) { case "0": Response.Cache.SetCacheability(HttpCacheability.NoCache); break; case "1": Response.Cache.SetCacheability(HttpCacheability.Private); break; case "2": Response.Cache.SetCacheability(HttpCacheability.Public); break; case "3": Response.Cache.SetCacheability(HttpCacheability.Server); break; case "4": Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache); break; case "5": Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); break; } //page comment if (Host.DisplayCopyright) { Comment += string.Concat(Environment.NewLine, "<!--*********************************************-->", Environment.NewLine, "<!-- DNN Platform - http://www.dnnsoftware.com -->", Environment.NewLine, "<!-- Copyright (c) 2002-2018, by DNN Corporation -->", Environment.NewLine, "<!--*********************************************-->", Environment.NewLine); } //Only insert the header control if a comment is needed if (!String.IsNullOrWhiteSpace(Comment)) { Page.Header.Controls.AddAt(0, new LiteralControl(Comment)); } if (PortalSettings.ActiveTab.PageHeadText != Null.NullString && !Globals.IsAdminControl()) { Page.Header.Controls.Add(new LiteralControl(PortalSettings.ActiveTab.PageHeadText)); } if (!string.IsNullOrEmpty(PortalSettings.PageHeadText)) { metaPanel.Controls.Add(new LiteralControl(PortalSettings.PageHeadText)); } //set page title if (UrlUtils.InPopUp()) { var strTitle = new StringBuilder(PortalSettings.PortalName); var slaveModule = UIUtilities.GetSlaveModule(PortalSettings.ActiveTab.TabID); //Skip is popup is just a tab (no slave module) if (slaveModule.DesktopModuleID != Null.NullInteger) { var control = ModuleControlFactory.CreateModuleControl(slaveModule) as IModuleControl; string extension = Path.GetExtension(slaveModule.ModuleControl.ControlSrc.ToLowerInvariant()); switch (extension) { case ".mvc": var segments = slaveModule.ModuleControl.ControlSrc.Replace(".mvc", "").Split('/'); control.LocalResourceFile = String.Format("~/DesktopModules/MVC/{0}/{1}/{2}.resx", slaveModule.DesktopModule.FolderName, Localization.LocalResourceDirectory, segments[0]); break; default: control.LocalResourceFile = string.Concat( slaveModule.ModuleControl.ControlSrc.Replace( Path.GetFileName(slaveModule.ModuleControl.ControlSrc), string.Empty), Localization.LocalResourceDirectory, "/", Path.GetFileName(slaveModule.ModuleControl.ControlSrc)); break; } var title = Localization.LocalizeControlTitle(control); strTitle.Append(string.Concat(" > ", PortalSettings.ActiveTab.LocalizedTabName)); strTitle.Append(string.Concat(" > ", title)); } else { strTitle.Append(string.Concat(" > ", PortalSettings.ActiveTab.LocalizedTabName)); } //Set to page Title = strTitle.ToString(); } else { //If tab is named, use that title, otherwise build it out via breadcrumbs if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Title)) { Title = PortalSettings.ActiveTab.Title; } else { //Elected for SB over true concatenation here due to potential for long nesting depth var strTitle = new StringBuilder(PortalSettings.PortalName); foreach (TabInfo tab in PortalSettings.ActiveTab.BreadCrumbs) { strTitle.Append(string.Concat(" > ", tab.TabName)); } Title = strTitle.ToString(); } } //set the background image if there is one selected if (!UrlUtils.InPopUp() && FindControl("Body") != null) { if (!string.IsNullOrEmpty(PortalSettings.BackgroundFile)) { var fileInfo = GetBackgroundFileInfo(); var url = FileManager.Instance.GetUrl(fileInfo); ((HtmlGenericControl)FindControl("Body")).Attributes["style"] = string.Concat("background-image: url('", url, "')"); } } //META Refresh // Only autorefresh the page if we are in VIEW-mode and if we aren't displaying some module's subcontrol. if (PortalSettings.ActiveTab.RefreshInterval > 0 && this.PortalSettings.UserMode == PortalSettings.Mode.View && Request.QueryString["ctl"] == null) { MetaRefresh.Content = PortalSettings.ActiveTab.RefreshInterval.ToString(); MetaRefresh.Visible = true; } else { MetaRefresh.Visible = false; } //META description if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Description)) { Description = PortalSettings.ActiveTab.Description; } else { Description = PortalSettings.Description; } //META keywords if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.KeyWords)) { KeyWords = PortalSettings.ActiveTab.KeyWords; } else { KeyWords = PortalSettings.KeyWords; } if (Host.DisplayCopyright) { KeyWords += ",DotNetNuke,DNN"; } //META copyright if (!string.IsNullOrEmpty(PortalSettings.FooterText)) { Copyright = PortalSettings.FooterText.Replace("[year]", DateTime.Now.Year.ToString()); } else { Copyright = string.Concat("Copyright (c) ", DateTime.Now.Year, " by ", PortalSettings.PortalName); } //META generator if (Host.DisplayCopyright) { Generator = "DotNetNuke "; } else { Generator = ""; } //META Robots - hide it inside popups and if PageHeadText of current tab already contains a robots meta tag if (!UrlUtils.InPopUp() && !(HeaderTextRegex.IsMatch(PortalSettings.ActiveTab.PageHeadText) || HeaderTextRegex.IsMatch(PortalSettings.PageHeadText))) { MetaRobots.Visible = true; var allowIndex = true; if ((PortalSettings.ActiveTab.TabSettings.ContainsKey("AllowIndex") && bool.TryParse(PortalSettings.ActiveTab.TabSettings["AllowIndex"].ToString(), out allowIndex) && !allowIndex) || (Request.QueryString["ctl"] != null && (Request.QueryString["ctl"] == "Login" || Request.QueryString["ctl"] == "Register"))) { MetaRobots.Content = "NOINDEX, NOFOLLOW"; } else { MetaRobots.Content = "INDEX, FOLLOW"; } } //NonProduction Label Injection if (NonProductionVersion() && Host.DisplayBetaNotice && !UrlUtils.InPopUp()) { string versionString = string.Format(" ({0} Version: {1})", DotNetNukeContext.Current.Application.Status, DotNetNukeContext.Current.Application.Version); Title += versionString; } //register the custom stylesheet of current page if (PortalSettings.ActiveTab.TabSettings.ContainsKey("CustomStylesheet") && !string.IsNullOrEmpty(PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString())) { var customStylesheet = Path.Combine(PortalSettings.HomeDirectory, PortalSettings.ActiveTab.TabSettings["CustomStylesheet"].ToString()); ClientResourceManager.RegisterStyleSheet(this, customStylesheet); } // Cookie Consent if (PortalSettings.ShowCookieConsent) { ClientAPI.RegisterClientVariable(this, "cc_morelink", PortalSettings.CookieMoreLink, true); ClientAPI.RegisterClientVariable(this, "cc_message", Localization.GetString("cc_message", Localization.GlobalResourceFile), true); ClientAPI.RegisterClientVariable(this, "cc_dismiss", Localization.GetString("cc_dismiss", Localization.GlobalResourceFile), true); ClientAPI.RegisterClientVariable(this, "cc_link", Localization.GetString("cc_link", Localization.GlobalResourceFile), true); ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.js", FileOrder.Js.DnnControls); ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/Components/CookieConsent/cookieconsent.min.css", FileOrder.Css.ResourceCss); ClientResourceManager.RegisterScript(Page, "~/js/dnn.cookieconsent.js", FileOrder.Js.DefaultPriority); } }
public void GetIdFromUrl_ValidInput_ReturnsId(string url, int id) { var result = UrlUtils.GetIdFromUrl(url); Assert.AreEqual(id, result); }
/// ----------------------------------------------------------------------------- /// <summary> /// cmdUpdate_Click runs when the Update button is clicked /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 5/10/2004 Updated to reflect design changes for Help, 508 support /// and localisation /// </history> /// ----------------------------------------------------------------------------- private void cmdUpdate_Click(Object sender, EventArgs e) { if (Page.IsValid) { PortalController.PortalTemplateInfo template = LoadPortalTemplateInfoForSelectedItem(); try { bool blnChild; string strPortalAlias; string strChildPath = string.Empty; var closePopUpStr = string.Empty; var objPortalController = new PortalController(); //check template validity var messages = new ArrayList(); string schemaFilename = Server.MapPath(string.Concat(AppRelativeTemplateSourceDirectory, "portal.template.xsd")); string xmlFilename = template.TemplateFilePath; var xval = new PortalTemplateValidator(); if (!xval.Validate(xmlFilename, schemaFilename)) { UI.Skins.Skin.AddModuleMessage(this, "", String.Format(Localization.GetString("InvalidTemplate", LocalResourceFile), Path.GetFileName(template.TemplateFilePath)), ModuleMessage.ModuleMessageType.RedError); messages.AddRange(xval.Errors); lstResults.Visible = true; lstResults.DataSource = messages; lstResults.DataBind(); validationPanel.Visible = true; return; } //Set Portal Name txtPortalAlias.Text = txtPortalAlias.Text.ToLowerInvariant(); txtPortalAlias.Text = txtPortalAlias.Text.Replace("http://", ""); //Validate Portal Name if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) { blnChild = true; strPortalAlias = txtPortalAlias.Text; } else { blnChild = (optType.SelectedValue == "C"); strPortalAlias = blnChild ? PortalController.GetPortalFolder(txtPortalAlias.Text) : txtPortalAlias.Text; } string message = String.Empty; ModuleMessage.ModuleMessageType messageType = ModuleMessage.ModuleMessageType.RedError; if (!PortalAliasController.ValidateAlias(strPortalAlias, blnChild)) { message = Localization.GetString("InvalidName", LocalResourceFile); } //check whether have conflict between tab path and portal alias. var checkTabPath = string.Format("//{0}", strPortalAlias); if (TabController.GetTabByTabPath(PortalSettings.PortalId, checkTabPath, string.Empty) != Null.NullInteger) { message = Localization.GetString("DuplicateWithTab", LocalResourceFile); } //Validate Password if (txtPassword.Text != txtConfirm.Text) { if (!String.IsNullOrEmpty(message)) { message += "<br/>"; } message += Localization.GetString("InvalidPassword", LocalResourceFile); } string strServerPath = Globals.GetAbsoluteServerPath(Request); //Set Portal Alias for Child Portals if (String.IsNullOrEmpty(message)) { if (blnChild) { strChildPath = strServerPath + strPortalAlias; if (Directory.Exists(strChildPath)) { message = Localization.GetString("ChildExists", LocalResourceFile); } else { if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) { strPortalAlias = Globals.GetDomainName(Request, true) + "/" + strPortalAlias; } else { strPortalAlias = txtPortalAlias.Text; } } } } //Get Home Directory string homeDir = txtHomeDirectory.Text != @"Portals/[PortalID]" ? txtHomeDirectory.Text : ""; //Validate Home Folder if (!string.IsNullOrEmpty(homeDir)) { if (string.IsNullOrEmpty(String.Format("{0}\\{1}\\", Globals.ApplicationMapPath, homeDir).Replace("/", "\\"))) { message = Localization.GetString("InvalidHomeFolder", LocalResourceFile); } if (homeDir.Contains("admin") || homeDir.Contains("DesktopModules") || homeDir.ToLowerInvariant() == "portals/") { message = Localization.GetString("InvalidHomeFolder", LocalResourceFile); } } //Validate Portal Alias if (!string.IsNullOrEmpty(strPortalAlias)) { PortalAliasInfo portalAlias = PortalAliasController.GetPortalAliasLookup(strPortalAlias.ToLower()); if (portalAlias != null) { message = Localization.GetString("DuplicatePortalAlias", LocalResourceFile); } } //Create Portal if (String.IsNullOrEmpty(message)) { //Attempt to create the portal UserInfo adminUser = new UserInfo(); int intPortalId; try { if (useCurrent.Checked) { adminUser = UserInfo; intPortalId = objPortalController.CreatePortal(txtPortalName.Text, adminUser.UserID, txtDescription.Text, txtKeyWords.Text, template, homeDir, strPortalAlias, strServerPath, strChildPath, blnChild); } else { adminUser = new UserInfo { FirstName = txtFirstName.Text, LastName = txtLastName.Text, Username = txtUsername.Text, DisplayName = txtFirstName.Text + " " + txtLastName.Text, Email = txtEmail.Text, IsSuperUser = false, Membership = { Approved = true, Password = txtPassword.Text, PasswordQuestion = txtQuestion.Text, PasswordAnswer = txtAnswer.Text }, Profile = { FirstName = txtFirstName.Text, LastName = txtLastName.Text } }; intPortalId = objPortalController.CreatePortal(txtPortalName.Text, adminUser, txtDescription.Text, txtKeyWords.Text, template, homeDir, strPortalAlias, strServerPath, strChildPath, blnChild); } } catch (Exception ex) { intPortalId = Null.NullInteger; message = ex.Message; } if (intPortalId != -1) { //Create a Portal Settings object for the new Portal PortalInfo objPortal = objPortalController.GetPortal(intPortalId); var newSettings = new PortalSettings { PortalAlias = new PortalAliasInfo { HTTPAlias = strPortalAlias }, PortalId = intPortalId, DefaultLanguage = objPortal.DefaultLanguage }; string webUrl = Globals.AddHTTP(strPortalAlias); try { if (!Globals.IsHostTab(PortalSettings.ActiveTab.TabID)) { message = Mail.SendMail(PortalSettings.Email, txtEmail.Text, PortalSettings.Email + ";" + Host.HostEmail, Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser), Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser), "", "", "", "", "", ""); } else { message = Mail.SendMail(Host.HostEmail, txtEmail.Text, Host.HostEmail, Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_SUBJECT", adminUser), Localization.GetSystemMessage(newSettings, "EMAIL_PORTAL_SIGNUP_BODY", adminUser), "", "", "", "", "", ""); } } catch (Exception exc) { Logger.Error(exc); closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : ""; message = string.Format(Localization.GetString("UnknownSendMail.Error", LocalResourceFile), webUrl, closePopUpStr); } var objEventLog = new EventLogController(); objEventLog.AddLog(objPortalController.GetPortal(intPortalId), PortalSettings, UserId, "", EventLogController.EventLogType.PORTAL_CREATED); // mark default language as published if content localization is enabled bool ContentLocalizationEnabled = PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", PortalId, false); if (ContentLocalizationEnabled) { LocaleController lc = new LocaleController(); lc.PublishLanguage(intPortalId, objPortal.DefaultLanguage, true); } //Redirect to this new site if (message == Null.NullString) { webUrl = (PortalSettings.EnablePopUps) ? UrlUtils.ClosePopUp(true, webUrl, false) : webUrl; Response.Redirect(webUrl, true); } else { closePopUpStr = (PortalSettings.EnablePopUps) ? "onclick=\"return " + UrlUtils.ClosePopUp(true, webUrl, true) + "\"" : ""; message = string.Format(Localization.GetString("SendMail.Error", LocalResourceFile), message, webUrl, closePopUpStr); messageType = ModuleMessage.ModuleMessageType.YellowWarning; } } } UI.Skins.Skin.AddModuleMessage(this, "", message, messageType); } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } }
/// <summary> /// Executes the search. /// </summary> /// <param name = "searchText">The text which will be used to perform the search.</param> /// <param name = "searchType">The type of the search. Use "S" for a site search, and "W" for a web search.</param> /// <remarks> /// All web based searches will open in a new window, while site searches will open in the current window. A site search uses the built /// in search engine to perform the search, while both web based search variants will use an external search engine to perform a search. /// </remarks> protected void ExecuteSearch(string searchText, string searchType) { int searchTabId = GetSearchTabId(); if (searchTabId == Null.NullInteger) { return; } string strURL; if (!string.IsNullOrEmpty(searchText)) { switch (searchType) { case "S": // site if (UseWebForSite) { strURL = SiteURL; if (!string.IsNullOrEmpty(strURL)) { strURL = strURL.Replace("[TEXT]", Server.UrlEncode(searchText)); strURL = strURL.Replace("[DOMAIN]", Request.Url.Host); UrlUtils.OpenNewWindow(Page, GetType(), strURL); } } else { if (Host.UseFriendlyUrls) { Response.Redirect(Globals.NavigateURL(searchTabId) + "?Search=" + Server.UrlEncode(searchText)); } else { Response.Redirect(Globals.NavigateURL(searchTabId) + "&Search=" + Server.UrlEncode(searchText)); } } break; case "W": // web strURL = WebURL; if (!string.IsNullOrEmpty(strURL)) { strURL = strURL.Replace("[TEXT]", Server.UrlEncode(searchText)); strURL = strURL.Replace("[DOMAIN]", ""); UrlUtils.OpenNewWindow(Page, GetType(), strURL); } break; } } else { if (Host.UseFriendlyUrls) { Response.Redirect(Globals.NavigateURL(searchTabId)); } else { Response.Redirect(Globals.NavigateURL(searchTabId)); } } }
/// <inheritdoc/> public string ToAbsoluteUrl(string path) { return(UrlUtils.Join(options.Host, path)); }
private Containers.Container LoadModuleContainer(ModuleInfo module) { var containerSrc = Null.NullString; var request = PaneControl.Page.Request; Containers.Container container = null; if (PortalSettings.EnablePopUps && UrlUtils.InPopUp()) { containerSrc = module.ContainerPath + "popUpContainer.ascx"; //Check Skin for a popup Container if (module.ContainerSrc == PortalSettings.ActiveTab.ContainerSrc) { if (File.Exists(HttpContext.Current.Server.MapPath(containerSrc))) { container = LoadContainerByPath(containerSrc); } } //error loading container - load default popup container if (container == null) { containerSrc = Globals.HostPath + "Containers/_default/popUpContainer.ascx"; container = LoadContainerByPath(containerSrc); } } else { container = (LoadContainerFromQueryString(module, request) ?? LoadContainerFromCookie(request)) ?? LoadNoContainer(module); if (container == null) { //Check Skin for Container var masterModules = PortalSettings.ActiveTab.ChildModules; if (masterModules.ContainsKey(module.ModuleID) && string.IsNullOrEmpty(masterModules[module.ModuleID].ContainerSrc)) { //look for a container specification in the skin pane if (PaneControl != null) { if ((PaneControl.Attributes["ContainerSrc"] != null)) { container = LoadContainerFromPane(); } } } } //else load assigned container if (container == null) { containerSrc = module.ContainerSrc; if (!String.IsNullOrEmpty(containerSrc)) { containerSrc = SkinController.FormatSkinSrc(containerSrc, PortalSettings); container = LoadContainerByPath(containerSrc); } } //error loading container - load default if (container == null) { containerSrc = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalContainer(), PortalSettings); container = LoadContainerByPath(containerSrc); } } //Set container path module.ContainerPath = SkinController.FormatSkinPath(containerSrc); //set container id to an explicit short name to reduce page payload container.ID = "ctr"; //make the container id unique for the page if (module.ModuleID > -1) { container.ID += module.ModuleID.ToString(); } return(container); }
private static string NormalizePath(string path) { return(UrlUtils.NormalizePath(path, canonicalize: true)); }
/// <summary> /// Converts internal urls to public ones in a given html fragment /// </summary> /// <param name="html"></param> /// <param name="converters"></param> /// <returns></returns> internal static string ConvertInternalUrlsToPublic(string html, IEnumerable <IInternalUrlConverter> converters) { var convertersMap = GetConvertersMap(_ => _); if (!convertersMap.Any()) { return(html); } // Urls, generated in UserControl-s may still have "~/" as a prefix foreach (var urlPrefix in convertersMap.Keys) { string rawUrlPrefix = "~/" + urlPrefix; string resolvedUrlPrefix = ResolvePrefix(urlPrefix); html = UrlUtils.ReplaceUrlPrefix(html, rawUrlPrefix, resolvedUrlPrefix); } StringBuilder result = null; var urlsToConvert = new List <UrlToConvert> (); foreach (var pair in convertersMap) { string internalPrefix = ResolvePrefix(pair.Key); var converter = pair.Value; // Bracket encoding fix string prefixToSearch = internalPrefix; if (prefixToSearch.EndsWith("(", StringComparison.Ordinal)) { prefixToSearch = prefixToSearch.Substring(0, internalPrefix.Length - 1); } urlsToConvert.AddRange(UrlUtils.FindUrlsInHtml(html, prefixToSearch).Select(match => new UrlToConvert(match, internalPrefix, converter))); } // Sorting the offsets by descending, so we can replace urls in that order by not affecting offsets of not yet processed urls urlsToConvert.Sort((a, b) => - a.Match.Index.CompareTo(b.Match.Index)); int lastReplacementIndex = int.MaxValue; var urlSpace = new UrlSpace(); var measurements = new Dictionary <string, Measurement>(); var convertionCache = new Dictionary <string, string>(); foreach (var urlToConvert in urlsToConvert) { UrlUtils.UrlMatch urlMatch = urlToConvert.Match; if (urlMatch.Index == lastReplacementIndex) { continue; } string internalUrlPrefix = urlToConvert.UrlPrefix; string internalUrl = urlMatch.Value; string publicUrl; if (!convertionCache.TryGetValue(internalUrl, out publicUrl)) { string decodedInternalUrl = internalUrl.Replace("%28", "(").Replace("%29", ")").Replace("&", "&"); if (!decodedInternalUrl.StartsWith(internalUrlPrefix)) { continue; } var converter = urlToConvert.Converter; MeasureConvertionPerformance(measurements, converter, () => { publicUrl = urlToConvert.Converter.ToPublicUrl(decodedInternalUrl, urlSpace); }); if (publicUrl == null) { convertionCache.Add(internalUrl, null); continue; } // Encoding xml attribute value publicUrl = publicUrl.Replace("&", "&"); convertionCache.Add(internalUrl, publicUrl); } else { if (internalUrl == null) { continue; } } if (result == null) { result = new StringBuilder(html); } result.Remove(urlMatch.Index, urlMatch.Value.Length); result.Insert(urlMatch.Index, publicUrl); lastReplacementIndex = urlMatch.Index; } foreach (var measurement in measurements.Values) { Profiler.AddSubMeasurement(measurement); } return(result != null?result.ToString() : html); }