public UrlResolverTests() { Mock<HttpContextBase> httpContext = TestHelper.CreateMockedHttpContext(); UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContext.Object, new RouteData())); _resolver = new UrlResolver(urlHelper); }
public MarketController(IMarketService marketService, ICurrentMarket currentMarket, UrlResolver urlResolver, LanguageService languageService) { _marketService = marketService; _currentMarket = currentMarket; _urlResolver = urlResolver; _languageService = languageService; }
public CartItemViewModelFactory( IContentLoader contentLoader, IPricingService pricingService, UrlResolver urlResolver, ICurrentMarket currentMarket, ICurrencyService currencyService, IPromotionService promotionService, AppContextFacade appContext, ILineItemCalculator lineItemCalculator, IProductService productService, IRelationRepository relationRepository, ICartService cartService) { _contentLoader = contentLoader; _pricingService = pricingService; _urlResolver = urlResolver; _currentMarket = currentMarket; _currencyService = currencyService; _promotionService = promotionService; _appContext = appContext; _lineItemCalculator = lineItemCalculator; _productService = productService; _relationRepository = relationRepository; _cartService = cartService; }
// private readonly ViewModelFactory _modelFactory; /// <summary> /// Initializes a new instance of the <see cref="PageContextActionFilter"/> class. /// </summary> public PageContextActionFilter(IContentLoader contentLoader, UrlResolver urlResolver, ILanguageBranchRepository languageBranchRepository, ISiteSettingsProvider siteConfiguration) { _contentLoader = contentLoader; _urlResolver = urlResolver; _languageBranchRepository = languageBranchRepository; _siteConfiguration = siteConfiguration; }
public PageRatingController() { _reviewService = ServiceLocator.Current.GetInstance<IReviewService>(); _loader = ServiceLocator.Current.GetInstance<IContentLoader>(); contentAssetHelper = ServiceLocator.Current.GetInstance<ContentAssetHelper>(); _repository = ServiceLocator.Current.GetInstance<IContentRepository>(); _urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>(); //_logger = logger; }
public void Given_Web_Exception_Occures_Resolve_Returns_Original_Url() { var invalidUrl = "http"; var resolver = new UrlResolver(); var resolvedUrl = resolver.Resolve(invalidUrl); Assert.AreEqual(invalidUrl, resolvedUrl); }
public void Given_Full_Url_Resolve_Sucsessfully_Returns_Same_Url() { var originalUrl = "http://sergejus.blogas.lt/itishnikai-7-jau-online-1586.html"; var resolver = new UrlResolver(); var resolvedUrl = resolver.Resolve(originalUrl); Assert.AreEqual(originalUrl, resolvedUrl); }
protected SitemapXmlGenerator(ISitemapRepository sitemapRepository, IContentRepository contentRepository, UrlResolver urlResolver, SiteDefinitionRepository siteDefinitionRepository, ILanguageBranchRepository languageBranchRepository) { this.SitemapRepository = sitemapRepository; this.ContentRepository = contentRepository; this.UrlResolver = urlResolver; this.SiteDefinitionRepository = siteDefinitionRepository; this.LanguageBranchRepository = languageBranchRepository; this.EnabledLanguages = this.LanguageBranchRepository.ListEnabled(); this._urlSet = new HashSet<string>(); }
public MailService(HttpContextBase httpContextBase, UrlResolver urlResolver, IContentLoader contentLoader, IHtmlDownloader htmlDownloader) { _httpContextBase = httpContextBase; _urlResolver = urlResolver; _contentLoader = contentLoader; _htmlDownloader = htmlDownloader; }
public void Given_Shorten_Url_Resolve_Successfully_Resolves_Orignial_Url() { var shortenUrl = "http://t.co/53rFHuMG"; var originalUrl = "http://sergejus.blogas.lt/itishnikai-7-jau-online-1586.html"; var resolver = new UrlResolver(); var resolvedUrl = resolver.Resolve(shortenUrl); Assert.AreEqual(originalUrl, resolvedUrl); }
private string GetImageUrl(EntryContentBase product, UrlResolver urlResolver) { var mediaReferences = product.AssetImageUrls(); if (mediaReferences != null && mediaReferences.Any()) { var media = mediaReferences.FirstOrDefault(); var mediaUrl = urlResolver.GetUrl(media); return mediaUrl + "?preset=imagenarrow"; } return string.Empty; }
/// <summary> /// Instantiates new QueryStringBuilder with provided URL. /// </summary> /// <param name="contentLink">ContentReference for which to build query.</param> /// <param name="urlResolver">UrlResolver instance.</param> /// <param name="includeHost">Mark if include host name in the url.</param> public QueryStringBuilder(ContentReference contentLink, UrlResolver urlResolver, bool includeHost = false) { EPiUrlResolver = urlResolver; var url = EPiUrlResolver.GetUrl(contentLink); if (includeHost) { url = url.GetExternalUrl(); } UrlBuilder = new UrlBuilder(url); }
private static IWebAssetItemMerger CreateAssetMerger(ControllerContext context) { IPathResolver pathResolver = new PathResolver(); IFileSystem fileSystem = new FileSystemWrapper(); IUrlResolver urlResolver = new UrlResolver(new UrlHelper(context.RequestContext)); IWebAssetLocator assetLocator = new WebAssetLocator(context.HttpContext.IsDebuggingEnabled, pathResolver, fileSystem); ICacheManager cacheManager = new CacheManagerWrapper(); IWebAssetRegistry assetRegistry = new WebAssetRegistry(cacheManager, assetLocator, pathResolver, fileSystem); IWebAssetItemMerger assetItemMerger = new WebAssetItemMerger(assetRegistry, urlResolver, context.HttpContext.Server); return assetItemMerger; }
public EntryImporter(IContentRepository contentRepository, ReferenceConverter referenceConverter, IContentTypeRepository typeRepository, ILogger logger, UrlResolver urlResolver, IWarehouseRepository warehouseRepository, IWarehouseInventoryService inventoryService, IPriceService priceService) : base(contentRepository, referenceConverter, typeRepository, logger) { _urlResolver = urlResolver; _warehouseRepository = warehouseRepository; _inventoryService = inventoryService; _priceService = priceService; }
public CartService(Func<string, CartHelper> cartHelper, IContentLoader contentLoader, ReferenceConverter referenceConverter, UrlResolver urlResolver, IProductService productService, IPricingService pricingService) { _cartHelper = cartHelper; _contentLoader = contentLoader; _referenceConverter = referenceConverter; _preferredCulture = ContentLanguage.PreferredCulture; _urlResolver = urlResolver; _productService = productService; _pricingService = pricingService; }
public MultiShipmentViewModelFactory( LocalizationService localizationService, IAddressBookService addressBookService, IContentLoader contentLoader, UrlResolver urlResolver, ServiceAccessor<HttpContextBase> httpContextAccessor, ShipmentViewModelFactory shipmentViewModelFactory) { _localizationService = localizationService; _addressBookService = addressBookService; _contentLoader = contentLoader; _urlResolver = urlResolver; _httpContextAccessor = httpContextAccessor; _shipmentViewModelFactory = shipmentViewModelFactory; }
public SearchService(ICurrentMarket currentMarket, ICurrencyService currencyService, UrlResolver urlResolver, SearchFacade search, Func<CultureInfo> preferredCulture, IContentLoader contentLoader, LocalizationService localizationService) { _search = search; _currentMarket = currentMarket; _currencyService = currencyService; _urlResolver = urlResolver; _preferredCulture = preferredCulture(); _contentLoader = contentLoader; _localizationService = localizationService; }
public static string GetUrl(this VariationContent variant, ILinksRepository linksRepository, UrlResolver urlResolver) { var productLink = variant.GetParentProducts(linksRepository).FirstOrDefault(); if (productLink == null) { return string.Empty; } var urlBuilder = new UrlBuilder(urlResolver.GetUrl(productLink)); if (variant.Code != null) { urlBuilder.QueryCollection.Add("variationCode", variant.Code); } return urlBuilder.ToString(); }
public CheckoutViewModelFactory( LocalizationService localizationService, PaymentMethodViewModelFactory paymentMethodViewModelFactory, IAddressBookService addressBookService, IContentLoader contentLoader, IOrderFactory orderFactory, UrlResolver urlResolver, ServiceAccessor<HttpContextBase> httpContextAccessor, ShipmentViewModelFactory shipmentViewModelFactory) { _localizationService = localizationService; _paymentMethodViewModelFactory = paymentMethodViewModelFactory; _addressBookService = addressBookService; _contentLoader = contentLoader; _orderFactory = orderFactory; _urlResolver = urlResolver; _httpContextAccessor = httpContextAccessor; _shipmentViewModelFactory = shipmentViewModelFactory; }
public ProductService(IContentLoader contentLoader, IPromotionService promotionService, IPricingService pricingService, UrlResolver urlResolver, LinksRepository linksRepository, IRelationRepository relationRepository, ICurrentMarket currentMarket, ICurrencyService currencyService, AppContextFacade appContext, ReferenceConverter referenceConverter) { _contentLoader = contentLoader; _promotionService = promotionService; _pricingService = pricingService; _urlResolver = urlResolver; _linksRepository = linksRepository; _relationRepository = relationRepository; _preferredCulture = ContentLanguage.PreferredCulture; _currentMarket = currentMarket; _currencyService = currencyService; _appContext = appContext; _referenceConverter = referenceConverter; }
public static IList <string> GetAssets <TContentMedia>(this IAssetContainer assetContainer, IContentLoader contentLoader, UrlResolver urlResolver) where TContentMedia : IContentMedia { var assets = new List <string>(); if (assetContainer.CommerceMediaCollection != null) { assets.AddRange(assetContainer.CommerceMediaCollection .Where(x => ValidateCorrectType <TContentMedia>(x.AssetLink, contentLoader)) .Select(media => urlResolver.GetUrl(media.AssetLink, null, new VirtualPathArguments() { ContextMode = ContextMode.Default }))); } if (!assets.Any()) { assets.Add(string.Empty); } return(assets); }
public void TestSkippableHandlers() { var url = new HttpUrl(); url.SetHost("www.example.com"); url.SetLocation("/docgen/member/Color/ToString?thingy=stuff"); url.AssertComplete(); Assert.AreEqual(0, url.ParentDomains.Length); Assert.AreEqual("www.example.com", url.Domain); var resolver = new UrlResolver( new UrlMapping(req => { Assert.AreEqual(1, req.Url.ParentDomains.Length); Assert.AreEqual("www.example.com", req.Url.ParentDomains[0]); Assert.AreEqual("", req.Url.Domain); return null; }, "www.example.com", skippable: true), new UrlMapping(req => { Assert.AreEqual(1, req.Url.ParentDomains.Length); Assert.AreEqual("example.com", req.Url.ParentDomains[0]); Assert.AreEqual("www.", req.Url.Domain); return null; }, "example.com", skippable: true), new UrlMapping(req => { Assert.AreEqual(0, req.Url.ParentDomains.Length); Assert.AreEqual("www.example.com", req.Url.Domain); return null; }, skippable: true), new UrlMapping(req => { Assert.AreEqual(0, req.Url.ParentDomains.Length); Assert.AreEqual("www.example.com", req.Url.Domain); return HttpResponse.PlainText("blah"); } )); resolver.Handle(new HttpRequest { Url = url }); }
public void TestNestedResolve() { var url = new HttpUrl(); url.SetHost("www.example.com"); url.SetLocation("/docgen/member/Color/ToString?thingy=stuff"); url.AssertComplete(); Assert.AreEqual(0, url.ParentDomains.Length); Assert.AreEqual("www.example.com", url.Domain); Assert.AreEqual("/docgen/member/Color/ToString", url.Path); Assert.IsTrue(url.ParentPaths.SequenceEqual(new string[0])); bool okProp = false, okDocGen = false; var resolverDocGen = new UrlResolver( new UrlMapping(path: "/member", handler: req => { Assert.AreEqual("/Color/ToString", req.Url.Path); Assert.AreEqual("/docgen/member/blah/xyz?thingy=stuff", req.Url.WithPath("/blah/xyz").ToHref()); var url2 = req.Url.WithPathOnly("/blah/xyz"); Assert.AreEqual("/docgen/member/blah/xyz", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); Assert.AreEqual("http://www.example.com/docgen/member/blah/xyz", url2.ToFull()); url2 = req.Url.WithPath("/blah/xyz"); Assert.AreEqual("/docgen/member/blah/xyz?thingy=stuff", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); url2 = req.Url.WithPathParent().WithPath("/blah/xyz"); Assert.AreEqual("/docgen/blah/xyz?thingy=stuff", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); url2 = req.Url.WithPathParent().WithPathParent().WithPath("/blah/xyz"); Assert.AreEqual("/blah/xyz?thingy=stuff", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); okDocGen = true; return HttpResponse.Empty(); }) ); var resolverPropeller = new UrlResolver( new UrlMapping(path: "/docgen", handler: req => { Assert.AreEqual("/member/Color/ToString", req.Url.Path); Assert.AreEqual("/docgen/blah/xyz?thingy=stuff", req.Url.WithPath("/blah/xyz").ToHref()); var url2 = req.Url.WithPathOnly("/blah/xyz"); Assert.AreEqual("/docgen/blah/xyz", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); Assert.AreEqual("http://www.example.com/docgen/blah/xyz", url2.ToFull()); url2 = req.Url.WithPath("/blah/xyz"); Assert.AreEqual("/docgen/blah/xyz?thingy=stuff", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); url2 = req.Url.WithPathParent().WithPath("/blah/xyz"); Assert.AreEqual("/blah/xyz?thingy=stuff", url2.ToHref()); Assert.AreEqual("/blah/xyz", url2.Path); okProp = true; return resolverDocGen.Handle(req); }) ); resolverPropeller.Handle(new HttpRequest() { Url = url }); Assert.IsTrue(okProp); Assert.IsTrue(okDocGen); }
/// <summary> /// AnswerEdit event handler. /// </summary> protected void AnswerEdit_OnSaved(object sender, EventArgs e) { URLHelper.Redirect(UrlResolver.ResolveUrl("Polls_Answer_Edit.aspx?answerId=" + AnswerEdit.ItemID.ToString() + "&saved=1")); }
/// <summary> /// Returns all parameters of the selected item as name – value collection. /// </summary> public override Hashtable GetItemProperties() { Hashtable retval = new Hashtable(); #region "Image general tab" string ext = ValidationHelper.GetString(ViewState[DialogParameters.URL_EXT], ""); string url = ValidationHelper.GetString(ViewState[DialogParameters.URL_URL], ""); if (!(IsRelationship || IsSelectPath)) { bool resolveUrl = (!Config.ContentUseRelativeUrl && !((Config.OutputFormat == OutputFormatEnum.URL) && (Config.SelectableContent == SelectableContentEnum.OnlyMedia))); // Exception for MediaSelector control (it can't be resolved) url = (resolveUrl ? UrlResolver.ResolveUrl(url) : url); if (MediaHelper.IsAudioVideo(ext)) { retval[DialogParameters.AV_URL] = txtUrl.Text.Trim(); } else if (tabImageGeneral.Visible) { string imgUrl = txtUrl.Text.Trim(); bool sizeToUrl = ValidationHelper.GetBoolean(ViewState[DialogParameters.IMG_SIZETOURL], false); if (widthHeightElem.Width < DefaultWidth) { retval[DialogParameters.IMG_WIDTH] = widthHeightElem.Width; if (sizeToUrl) { url = URLHelper.AddParameterToUrl(url, "width", widthHeightElem.Width.ToString()); } } if (widthHeightElem.Height < DefaultHeight) { retval[DialogParameters.IMG_HEIGHT] = widthHeightElem.Height; if (sizeToUrl) { url = URLHelper.AddParameterToUrl(url, "height", widthHeightElem.Height.ToString()); } } retval[DialogParameters.IMG_URL] = (resolveUrl ? UrlResolver.ResolveUrl(imgUrl) : imgUrl); retval[DialogParameters.IMG_EXT] = ValidationHelper.GetString(ViewState[DialogParameters.URL_EXT], ""); retval[DialogParameters.IMG_SIZETOURL] = sizeToUrl; retval[DialogParameters.IMG_ALT] = txtAlt.Text.Trim(); retval[DialogParameters.IMG_ALT_CLIENTID] = QueryHelper.GetString(DialogParameters.IMG_ALT_CLIENTID, String.Empty); } } #endregion #region "General items" retval[DialogParameters.URL_EXT] = ext; retval[DialogParameters.URL_URL] = url; retval[DialogParameters.EDITOR_CLIENTID] = EditorClientID; #endregion #region "Select path & Relationship items" if (IsRelationship || IsSelectPath) { string path = txtSelectPath.Text; if (chkItems.Checked) { if (!path.EndsWithCSafe("/%")) { path = path.TrimEnd('/') + "/%"; } } else if (path.EndsWithCSafe("/%")) { path = path.Substring(0, path.Length - 2); } retval[DialogParameters.DOC_NODEALIASPATH] = path; if (!ContentChanged) { // Don't set 'content changed' flag retval[DialogParameters.CONTENT_CHANGED] = false; } // Fill target node id only if single path selection is enabled or in relationship dialog if (IsSelectSinglePath || IsRelationship) { retval[DialogParameters.DOC_TARGETNODEID] = ViewState[DialogParameters.DOC_TARGETNODEID]; } } #endregion return(retval); }
private static MvcHtmlString AssetUrl(ContentReference mediaReference, UrlResolver urlResolver) { string url = urlResolver.GetUrl(mediaReference); if (PageEditing.PageIsInEditMode && url.ToLower().EndsWith("epieditmode=false")) { url = System.Text.RegularExpressions.Regex.Replace(url, @",,\d+[?]epieditmode=false$", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase); } return new MvcHtmlString(url); }
public ShareThisBlockController(IPageRouteHelper pageRouteHelper, UrlResolver urlResolver) { this.pageRouteHelper = pageRouteHelper; this.urlResolver = urlResolver; }
/// <summary> /// Stores data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Perform validation string errorMessage = new Validator().NotEmpty(selSite.Value, GetString("srch.err.emptysite")).Result; if (String.IsNullOrEmpty(errorMessage) && (ItemType == SearchIndexSettingsInfo.TYPE_EXLUDED) && String.IsNullOrEmpty(Convert.ToString(selForum.Value))) { errorMessage = GetString("srch.err.emptyforum"); } if (String.IsNullOrEmpty(errorMessage)) { SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(ItemID); if (sii != null) { SearchIndexSettings sis = sii.IndexSettings; SearchIndexSettingsInfo sisi; var isInsert = false; if (ItemGUID != Guid.Empty) { // If we are updating existing Search Index Settings Info sisi = sis.GetSearchIndexSettingsInfo(ItemGUID); } else { // If we are creating new Search Index Settings Info isInsert = true; sisi = new SearchIndexSettingsInfo(); sisi.ID = Guid.NewGuid(); sisi.Type = ItemType; } // Save values if (sisi != null) { string siteName = selSite.Value.ToString(); if (siteName == "-1") { siteName = String.Empty; } sisi.SiteName = siteName; sisi.ForumNames = selForum.Value.ToString(); // Update settings item sis.SetSearchIndexSettingsInfo(sisi); // Update xml value sii.IndexSettings = sis; SearchIndexInfoProvider.SetSearchIndexInfo(sii); ItemGUID = sisi.ID; if (isInsert) { // Redirect to edit mode var editUrl = "SearchIndex_Content_Edit.aspx"; editUrl = URLHelper.AddParameterToUrl(editUrl, "indexId", sii.IndexID.ToString()); editUrl = URLHelper.AddParameterToUrl(editUrl, "guid", sisi.ID.ToString()); editUrl = URLHelper.AddParameterToUrl(editUrl, "saved", "1"); if (smartSearchEnabled) { editUrl = URLHelper.AddParameterToUrl(editUrl, "rebuild", "1"); } URLHelper.Redirect(UrlResolver.ResolveUrl(editUrl)); } ShowChangesSaved(); if (smartSearchEnabled) { // Show rebuild message ShowInformation(String.Format(GetString("srch.indexrequiresrebuild"), "<a href=\"javascript:" + Page.ClientScript.GetPostBackEventReference(this, "saved") + "\">" + GetString("General.clickhere") + "</a>")); } } // Error loading SearchIndexSettingsInfo else { ShowError(GetString("srch.err.loadingsisi")); } } // Error loading SearchIndexInfo else { ShowError(GetString("srch.err.loadingsii")); } } else { ShowError(errorMessage); } }
public CommerceSitemapXmlGenerator(ISitemapRepository sitemapRepository, IContentRepository contentRepository, UrlResolver urlResolver, SiteDefinitionRepository siteDefinitionRepository, ILanguageBranchRepository languageBranchRepository, ReferenceConverter referenceConverter) : base(sitemapRepository, contentRepository, urlResolver, siteDefinitionRepository, languageBranchRepository) { if (referenceConverter == null) throw new ArgumentNullException("referenceConverter"); _referenceConverter = referenceConverter; }
public SearchController(IContentLoader contentLoader, ReferenceConverter referenceConverter, UrlResolver urlResolver) { _contentLoader = contentLoader; _referenceConverter = referenceConverter; _urlResolver = urlResolver; }
protected SitemapXmlGenerator(ISitemapRepository sitemapRepository, IContentRepository contentRepository, UrlResolver urlResolver, SiteDefinitionRepository siteDefinitionRepository, ILanguageBranchRepository languageBranchRepository) { this.SitemapRepository = sitemapRepository; this.ContentRepository = contentRepository; this.UrlResolver = urlResolver; this.SiteDefinitionRepository = siteDefinitionRepository; this.LanguageBranchRepository = languageBranchRepository; this.EnabledLanguages = this.LanguageBranchRepository.ListEnabled(); this.UrlSet = new HashSet <string>(); }
/// <summary> /// OK click event handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if ((uploadAvatar.PostedFile == null) && (ai == null)) { ShowError(GetString("avat.fileinputerror")); } else { SiteInfo site = SiteContext.CurrentSite; int width = 0; int height = 0; int sidesize = 0; // Get resize values if (drpAvatarType.SelectedValue != "all") { // Get right settings key string siteName = ((site != null) ? (site.SiteName + ".") : ""); string prefix = "CMSAvatar"; if (drpAvatarType.SelectedValue == "group") { prefix = "CMSGroupAvatar"; } width = SettingsKeyInfoProvider.GetIntValue(siteName + prefix + "Width"); height = SettingsKeyInfoProvider.GetIntValue(siteName + prefix + "Height"); sidesize = SettingsKeyInfoProvider.GetIntValue(siteName + prefix + "MaxSideSize"); } // Check if avatar name is unique string newAvatarName = txtAvatarName.Text.Trim(); AvatarInfo avatarWithSameName = AvatarInfoProvider.GetAvatarInfoWithoutBinary(newAvatarName); if (avatarWithSameName != null) { if (ai != null) { // Check unique avatar name of existing avatar if (avatarWithSameName.AvatarID != ai.AvatarID) { ShowError(GetString("avat.uniqueavatarname")); return; } } // Check unique avatar name of new avatar else { ShowError(GetString("avat.uniqueavatarname")); return; } } // Process form in these cases: // 1 - creating new avatar and uploaded file is not empty and it is image file // 2 - updating existing avatar and not uploading new image file // 3 - updating existing avatar and uploading image file if (((ai == null) && (uploadAvatar.PostedFile != null) && (uploadAvatar.PostedFile.ContentLength > 0) && (ImageHelper.IsImage(Path.GetExtension(uploadAvatar.PostedFile.FileName)))) || ((ai != null) && ((uploadAvatar.PostedFile == null) || (uploadAvatar.PostedFile.ContentLength == 0))) || ((ai != null) && (uploadAvatar.PostedFile != null) && (uploadAvatar.PostedFile.ContentLength > 0) && (ImageHelper.IsImage(Path.GetExtension(uploadAvatar.PostedFile.FileName))))) { if (ai == null) { switch (drpAvatarType.SelectedValue) { case "user": ai = new AvatarInfo(uploadAvatar.PostedFile, width, height, sidesize); break; case "group": ai = new AvatarInfo(uploadAvatar.PostedFile, width, height, sidesize); break; case "all": ai = new AvatarInfo(uploadAvatar.PostedFile, 0, 0, 0); break; default: ai = new AvatarInfo(uploadAvatar.PostedFile, 0, 0, 0); break; } ai.AvatarIsCustom = false; ai.AvatarGUID = Guid.NewGuid(); } else if ((uploadAvatar.PostedFile != null) && (uploadAvatar.PostedFile.ContentLength > 0) && (ImageHelper.IsMimeImage(uploadAvatar.PostedFile.ContentType))) { AvatarInfoProvider.DeleteAvatarFile(ai.AvatarGUID.ToString(), ai.AvatarFileExtension, false, false); AvatarInfoProvider.UploadAvatar(ai, uploadAvatar.PostedFile, width, height, sidesize); } // Set new avatar name ai.AvatarName = newAvatarName; imgAvatar.Visible = true; imgAvatar.ImageUrl = GetAvatarImageUrl(ai.AvatarGUID); // Set new type ai.AvatarType = drpAvatarType.SelectedValue; // If avatar is not global, can't be default any default avatar if (ai.AvatarIsCustom) { // Set all default avatar options to false ai.DefaultUserAvatar = ai.DefaultMaleUserAvatar = ai.DefaultFemaleUserAvatar = ai.DefaultGroupAvatar = false; } else { // If user default avatar is changing if (ai.DefaultUserAvatar ^ chkDefaultUserAvatar.Checked) { AvatarInfoProvider.ClearDefaultAvatar(DefaultAvatarTypeEnum.User); } // If male default avatar is changing if (ai.DefaultMaleUserAvatar ^ chkDefaultMaleUserAvatar.Checked) { AvatarInfoProvider.ClearDefaultAvatar(DefaultAvatarTypeEnum.Male); } // If female default avatar is changing if (ai.DefaultFemaleUserAvatar ^ chkDefaultFemaleUserAvatar.Checked) { AvatarInfoProvider.ClearDefaultAvatar(DefaultAvatarTypeEnum.Female); } // If group default avatar is changing if (ai.DefaultGroupAvatar ^ chkDefaultGroupAvatar.Checked) { AvatarInfoProvider.ClearDefaultAvatar(DefaultAvatarTypeEnum.Group); } // Set new default avatar settings ai.DefaultUserAvatar = chkDefaultUserAvatar.Checked; ai.DefaultMaleUserAvatar = chkDefaultMaleUserAvatar.Checked; ai.DefaultFemaleUserAvatar = chkDefaultFemaleUserAvatar.Checked; ai.DefaultGroupAvatar = chkDefaultGroupAvatar.Checked; } AvatarInfoProvider.SetAvatarInfo(ai); avatarId = ai.AvatarID; URLHelper.Redirect(UrlResolver.ResolveUrl("Avatar_Edit.aspx?saved=1&avatarid=" + avatarId)); } else { // If given file is not valid if ((uploadAvatar.PostedFile != null) && (uploadAvatar.PostedFile.ContentLength > 0) && !ImageHelper.IsImage(Path.GetExtension(uploadAvatar.PostedFile.FileName))) { ShowError(GetString("avat.filenotvalid")); } else { // If posted file is not given ShowError(GetString("avat.fileinputerror")); } } } }
/// <summary> /// Checks status of current user. /// </summary> protected void CheckStatus() { // Get current site name string siteName = SiteContext.CurrentSiteName; string error = null; // Check return URL string returnUrl = QueryHelper.GetString("returnurl", null); returnUrl = HttpUtility.UrlDecode(returnUrl); // Get current URL string currentUrl = RequestContext.CurrentURL; currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "token"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.ns"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.mode"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.return_to"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.claimed_id"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.identity"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.assoc_handle"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.realm"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.response_nonce"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.signed"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.op_endpoint"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.pape.auth_level.nist"); currentUrl = URLHelper.RemoveParameterFromUrl(currentUrl, "openid.sig"); // Get OpenID response status switch (openIDhelper.CheckStatus()) { // User is authenticated case CMSOpenIDHelper.RESPONSE_AUTHENTICATED: // Claimed ID not found = save new user if (OpenIDUserInfoProvider.GetUserInfoByOpenID(openIDhelper.ClaimedIdentifier) == null) { // Check whether additional user info page is set string additionalInfoPage = SettingsKeyInfoProvider.GetValue(siteName + ".CMSRequiredOpenIDPage").Trim(); // No page set, user can be created if (String.IsNullOrEmpty(additionalInfoPage)) { // Register new user UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error); // If user was found or successfuly created if (ui != null) { // Load values submited by OpenID provider // Load date of birth if (openIDhelper.BirthDate != DateTime.MinValue) { ui.UserSettings.UserDateOfBirth = openIDhelper.BirthDate; } // Load default country if (openIDhelper.Culture != null) { ui.PreferredCultureCode = openIDhelper.Culture.Name; } // Load e-mail if (!String.IsNullOrEmpty(openIDhelper.Email)) { ui.Email = openIDhelper.Email; } // Nick name if (!String.IsNullOrEmpty(openIDhelper.Nickname)) { ui.UserSettings.UserNickName = openIDhelper.Nickname; } // User gender if (openIDhelper.UserGender != null) { ui.UserSettings.UserGender = (int)openIDhelper.UserGender; } UserInfoProvider.SetUserInfo(ui); // If user is enabled if (ui.Enabled) { // Create autentification cookie AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "openidlogin" }); // Log activity MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); } // Notify administrator if (NotifyAdministrator && !String.IsNullOrEmpty(FromAddress) && !String.IsNullOrEmpty(ToAddress)) { AuthenticationHelper.NotifyAdministrator(ui, FromAddress, ToAddress); } // Log user registration into the web analytics and track conversion if set AnalyticsHelper.TrackUserRegistration(siteName, ui, TrackConversionName, ConversionValue); MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument); } // Redirect when authentication was succesfull if (String.IsNullOrEmpty(error)) { if (URLHelper.IsLocalUrl(returnUrl)) { URLHelper.Redirect(returnUrl); } else { URLHelper.Redirect(currentUrl); } } // Display error otherwise else { lblError.Text = error; lblError.Visible = true; } } // Additional information page is set else { // Store user object in session for additional use StoreResponseInSession(); // Redirect to additional info page string targetURL = URLHelper.GetAbsoluteUrl(additionalInfoPage); if (URLHelper.IsLocalUrl(returnUrl)) { // Add return URL to parameter targetURL = URLHelper.AddParameterToUrl(targetURL, "returnurl", HttpUtility.UrlEncode(returnUrl)); } URLHelper.Redirect(UrlResolver.ResolveUrl(targetURL)); } } // Claimed OpenID is in DB else { // Login existing user UserInfo ui = AuthenticationHelper.AuthenticateOpenIDUser(openIDhelper.ClaimedIdentifier, ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null), siteName, false, true, ref error); if ((ui != null) && (ui.Enabled)) { // Create autentification cookie AuthenticationHelper.SetAuthCookieWithUserData(ui.UserName, true, Session.Timeout, new[] { "openilogin" }); // Log activity MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); // Redirect user if (URLHelper.IsLocalUrl(returnUrl)) { URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.GetAbsoluteUrl(returnUrl))); } else { URLHelper.Redirect(currentUrl); } } // Display error which occured during authentication process else if (!String.IsNullOrEmpty(error)) { lblError.Text = error; lblError.Visible = true; } // Otherwise is user disabled else { lblError.Text = GetString("membership.userdisabled"); lblError.Visible = true; } } break; // Authentication was canceled case CMSOpenIDHelper.RESPONSE_CANCELED: lblError.Text = GetString("openid.logincanceled"); lblError.Visible = true; break; // Authentication failed case CMSOpenIDHelper.RESPONSE_FAILED: lblError.Text = GetString("openid.loginfailed"); lblError.Visible = true; break; } }
public CommerceAndStandardSitemapXmlGenerator(ISitemapRepository sitemapRepository, IContentRepository contentRepository, UrlResolver urlResolver, ISiteDefinitionRepository siteDefinitionRepository, ILanguageBranchRepository languageBranchRepository, ReferenceConverter referenceConverter, IContentFilter contentFilter, IContentLoader contentLoader) : base(sitemapRepository, contentRepository, urlResolver, siteDefinitionRepository, languageBranchRepository, referenceConverter, contentFilter, contentLoader) { }
public CommerceAndStandardSitemapXmlGenerator(ISitemapRepository sitemapRepository, IContentRepository contentRepository, UrlResolver urlResolver, SiteDefinitionRepository siteDefinitionRepository, ILanguageBranchRepository languageBranchRepository, ReferenceConverter referenceConverter) : base(sitemapRepository, contentRepository, urlResolver, siteDefinitionRepository, languageBranchRepository, referenceConverter) { }
public StartPageUrlResolver(ISiteDefinitionRepository siteDefinitionRepository, UrlResolver urlResolver, IContentLoader contentLoader) { _urlResolver = urlResolver; _contentLoader = contentLoader; _startPages = new Lazy <IEnumerable <ContentReference> >(() => { return(siteDefinitionRepository.List().Select(x => x.StartPage.ToReferenceWithoutVersion())); }); }
/// <summary> /// SignOut handler. /// </summary> protected void btnSignOut_Click(object sender, EventArgs e) { if (StopProcessing) { // Do not process } else { if (AuthenticationHelper.IsAuthenticated()) { string redirectUrl = RedirectToUrl; // If the user has registered Windows Live ID if (!String.IsNullOrEmpty(MembershipContext.AuthenticatedUser.UserSettings.WindowsLiveID)) { // Get data from auth cookie string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie(); // If user has logged in using Windows Live ID, then sign him out from Live too if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0)) { string siteName = SiteContext.CurrentSiteName; // Get LiveID settings string appId = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationID"); string secret = SettingsKeyInfoProvider.GetValue(siteName + ".CMSApplicationSecret"); // Check valid Windows LiveID parameters if ((appId != string.Empty) && (secret != string.Empty)) { WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret); // Redirect to Windows Live and back to "home" page string defaultAliasPath = SettingsKeyInfoProvider.GetValue(siteName + ".CMSDefaultAliasPath"); string url = DocumentURLProvider.GetUrl(defaultAliasPath); redirectUrl = wll.GetLogoutUrl(URLHelper.GetAbsoluteUrl(url)); } } } PortalContext.ViewMode = ViewModeEnum.LiveSite; AuthenticationHelper.SignOut(); Response.Cache.SetNoStore(); URLHelper.Redirect(UrlResolver.ResolveUrl(redirectUrl)); } else { string returnUrl = null; string signInUrl = null; if (SignInUrl != "") { signInUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(SignInUrl))); } else { signInUrl = AuthenticationHelper.GetSecuredAreasLogonPage(SiteContext.CurrentSiteName); } if (ReturnPath != "") { returnUrl = ResolveUrl(DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(ReturnPath))); } else { returnUrl = RequestContext.CurrentURL; } if (signInUrl != "") { // Prevent multiple returnUrl parameter returnUrl = URLHelper.RemoveParameterFromUrl(returnUrl, "returnUrl"); URLHelper.Redirect(UrlResolver.ResolveUrl(URLHelper.UpdateParameterInUrl(signInUrl, "returnurl", Server.UrlEncode(returnUrl)))); } } } }
protected void Page_Load(object sender, EventArgs e) { objectType = UIContextHelper.GetObjectType(UIContext); CloneItemButton.Visible = DisplayCloneButton; if ((!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource(ResourceName, "Modify")) || (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource(ResourceName, "Create"))) { CloneItemButton.ViewStateMode = ViewStateMode.Disabled; } // Pass tabindex int tabIndex = ValidationHelper.GetInteger(UIContext["TabIndex"], 0); if (tabIndex != 0) { tabIndexStr = "&tabindex=" + tabIndex; } String editElem = ValidationHelper.GetString(UIContext["itemEdit"], String.Empty); String categoryElem = ValidationHelper.GetString(UIContext["categoryedit"], String.Empty); categoryPathColumn = ValidationHelper.GetString(UIContext["pathColumn"], String.Empty); categoryParentColumn = ValidationHelper.GetString(UIContext["categoryparentcolumn"], String.Empty); categoryObjectType = ValidationHelper.GetString(UIContext["parentobjecttype"], String.Empty); itemParentColumn = ValidationHelper.GetString(UIContext["parentColumn"], String.Empty); newItem = ValidationHelper.GetString(UIContext["newitem"], String.Empty); if (!ValidateInput()) { return; } itemLocation = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ResourceName, editElem), "?tabslayout=horizontal&displaytitle=false"); categoryLocation = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ResourceName, categoryElem), "?tabslayout=horizontal&displaytitle=false"); RegisterExportScript(); RegisterTreeScript(); RegisterMenuScript(); InitTree(); // Setup menu action scripts String newItemText = newItem.StartsWith("javascript", StringComparison.InvariantCultureIgnoreCase) ? newItem : "NewItem('item'); return false;"; AddButon.Actions.Add(new CMSButtonAction { Text = GetString(objectType + ".newitem"), OnClientClick = newItemText }); AddButon.Actions.Add(new CMSButtonAction { Text = GetString("development.tree.newcategory"), OnClientClick = "NewItem('category'); return false;" }); DeleteItemButton.OnClientClick = "DeleteItem(); return false;"; ExportItemButton.OnClientClick = "ExportObject(); return false;"; CloneItemButton.OnClientClick = "if ((selectedItemId > 0) && (selectedItemType == 'item')) { modalDialog('" + UrlResolver.ResolveUrl("~/CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?reloadall=1&displaytitle=" + UIContext["displaytitle"] + "&objecttype=" + objectType + "&objectid=") + "' + selectedItemId, 'Clone item', 750, 470); } return false;"; // Tooltips DeleteItemButton.ToolTip = GetString("development.tree.deleteselected"); ExportItemButton.ToolTip = GetString("exportobject.title"); CloneItemButton.ToolTip = GetString(objectType + ".clone"); // URLs for menu actions String script = "var doNotReloadContent = false;\n"; // Script for deleting widget or category string delPostback = ControlsHelper.GetPostBackEventReference(this, "##"); string deleteScript = @" function DeleteItem() { if ((selectedItemId > 0) && (selectedItemParent > 0) && confirm(" + ScriptHelper.GetLocalizedString("general.deleteconfirmation") + @")) { " + delPostback.Replace("'##'", "selectedItemType+';'+selectedItemId+';'+selectedItemParent") + @" } }"; script += deleteScript; // Preselect tree item if (!RequestHelper.IsPostBack()) { int parentobjectid = QueryHelper.GetInteger("parentobjectid", 0); int objectID = QueryHelper.GetInteger("objectID", 0); // Select category if (parentobjectid > 0) { BaseInfo biParent = ProviderHelper.GetInfoById(categoryObjectType, parentobjectid); if (biParent != null) { String path = ValidationHelper.GetString(biParent.GetValue(categoryPathColumn), String.Empty); int parentID = ValidationHelper.GetInteger(biParent.GetValue(categoryParentColumn), 0); script += SelectAfterLoad(path + "/", parentobjectid, "category", parentID, true, true); } } // Select item else if (objectID > 0) { BaseInfo bi = ProviderHelper.GetInfoById(objectType, objectID); if (bi != null) { script += SelectItem(bi); } } else { // Selection by hierarchy URL BaseInfo biSel = UIContext.EditedObject as BaseInfo; BaseInfo biParent = UIContext.EditedObjectParent as BaseInfo; // Check for category selection if ((biParent != null) && (biParent.TypeInfo.ObjectType == categoryObjectType)) { String path = ValidationHelper.GetString(biParent.GetValue(categoryPathColumn), String.Empty); int parentID = ValidationHelper.GetInteger(biParent.GetValue(categoryParentColumn), 0); script += SelectAfterLoad(path, biParent.Generalized.ObjectID, "category", parentID, false, true); } // Check for item selection else if ((biSel != null) && (biSel.TypeInfo.ObjectType == objectType)) { script += SelectItem(biSel); } else { // Select root by default BaseInfo bi = ProviderHelper.GetInfoByName(categoryObjectType, "/"); if (bi != null) { script += SelectAfterLoad("/", bi.Generalized.ObjectID, "category", 0, true, true); } } } } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "GeneralTree_" + ClientID, ScriptHelper.GetScript(script)); }
public static MvcHtmlString AssetUrl(this HtmlHelper html, EntryContentBase entry, UrlResolver urlResolver, IPermanentLinkMapper permanentLinkMapper) { var commerceMedia = entry.GetCommerceMedia(); if (commerceMedia == null) { return new MvcHtmlString(null); } return AssetUrl(commerceMedia.AssetContentLink(permanentLinkMapper), urlResolver); }
/// <summary> /// Creates new culture version of object. /// </summary> protected void btnCreateDocument_Click(object sender, EventArgs e) { if (radCopy.Checked) { string sourceCulture = copyCulturesElem.Value.ToString(); TreeNode actualSourceNode = DocumentHelper.GetDocument(NodeID, sourceCulture, Tree); TreeNode sourceNode = actualSourceNode.IsLink ? DocumentHelper.GetDocument(Tree.GetOriginalNode(actualSourceNode), Tree) : actualSourceNode; if (sourceNode != null) { if (chkSaveBeforeEditing.Checked && (Node != null)) { // Create the version first TreeNode newCulture = TreeNode.New(Node.ClassName); DocumentHelper.CopyNodeData(sourceNode, newCulture, new CopyNodeDataSettings(true, null) { ResetChanges = true }); if (string.Equals(Node.ClassName, "cms.blogpost", StringComparison.InvariantCultureIgnoreCase)) { // Ensure blog post hierarchy if node is blog post newCulture.DocumentCulture = RequiredCulture; DocumentHelper.EnsureBlogPostHierarchy(newCulture, DocumentHelper.GetDocument(newCulture.NodeParentID, TreeProvider.ALL_CULTURES, Tree), Tree); } var settings = new NewCultureDocumentSettings(newCulture, RequiredCulture, Tree) { CopyAttachments = true, CopyCategories = true, ClearAttachmentFields = false }; try { DocumentHelper.InsertNewCultureVersion(settings); } catch (Exception ex) { // Catch possible exceptions LogAndShowError("Content", "NEWCULTUREVERSION", ex); return; } // Make sure document is published when versioning without workflow is applied var workflow = newCulture.GetWorkflow(); if ((workflow != null) && workflow.WorkflowAutoPublishChanges && !workflow.UseCheckInCheckOut(newCulture.NodeSiteName)) { newCulture.MoveToPublishedStep(); } // Refresh page if (RequiresDialog) { string url = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(newCulture) + "?" + URLHelper.LanguageParameterName + "=" + RequiredCulture); ScriptHelper.RegisterStartupScript(this, typeof(string), "NewCultureRefreshAction", ScriptHelper.GetScript(" wopener.location = " + ScriptHelper.GetString(url) + "; CloseDialog();")); } else { ViewModeEnum mode = ViewModeEnum.Edit; if (!TreePathUtils.IsMenuItemType(Node.NodeClassName) && (PortalContext.ViewMode != ViewModeEnum.EditLive)) { mode = ViewModeEnum.EditForm; } ScriptHelper.RegisterStartupScript(this, typeof(string), "NewCultureRefreshAction", ScriptHelper.GetScript("if (FramesRefresh) { FramesRefresh(" + Node.NodeID + ", '" + mode + "'); }")); } } else { var url = GetEditUrl(Node); url = URLHelper.AddParameterToUrl(url, "sourcedocumentid", sourceNode.DocumentID.ToString()); if (RequiresDialog) { // Reload new page after save url = URLHelper.AddParameterToUrl(url, "reloadnewpage", "true"); } // Provide information about actual node if (actualSourceNode.IsLink) { url = URLHelper.AddParameterToUrl(url, "sourcenodeid", actualSourceNode.NodeID.ToString()); } URLHelper.ResponseRedirect(url); } } else { ShowError(GetString("transman.notallowedcreate")); } } else { var url = GetEditUrl(Node); if (RequiresDialog) { // Reload new page after save url = URLHelper.AddParameterToUrl(url, "reloadnewpage", "true"); } URLHelper.ResponseRedirect(url); } }
void formUser_OnAfterSave(object sender, EventArgs e) { // Get user info from form UserInfo ui = (UserInfo)formUser.Data; // Add user prefix if settings is on // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(CurrentSiteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(ui.UserName, SiteContext.CurrentSite); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer); ui.UserCampaign = Service.Resolve <ICampaignService>().CampaignCode; ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None; // Fill optionally full user name if (String.IsNullOrEmpty(ui.FullName)) { ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, ui.MiddleName, ui.LastName); } // Ensure nick name if (ui.UserNickName.Trim() == String.Empty) { ui.UserNickName = Functions.GetFormattedUserName(ui.UserName, true); } ui.UserSettings.UserRegistrationInfo.IPAddress = RequestContext.UserHostAddress; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; ui.UserSettings.UserLogActivities = true; ui.UserSettings.UserShowIntroductionTile = true; // Check whether confirmation is required if (!ConfirmationRequired) { // If confirmation is not required check whether administration approval is required if (AdminApprovalRequired) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } // Get user password and save it in appropriate format after form save string password = ValidationHelper.GetString(ui.GetValue("UserPassword"), String.Empty); UserInfoProvider.SetPassword(ui, password); if (!ConfirmationRequired) { SendAdminNotification(ui); LogOMActivity(ui); } SendRegistrationEmail(ui); LogWebAnalytics(ui); AssignToRoles(ui); if (ui.Enabled) { // Authenticate currently created user AuthenticationHelper.AuthenticateUser(ui.UserName, true); } var displayMessage = DisplayMessage.Trim(); if (!String.IsNullOrEmpty(displayMessage)) { ShowInformation(displayMessage); } else { if (RedirectToURL != String.Empty) { URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL)); } string returnUrl = QueryHelper.GetString("ReturnURL", String.Empty); if (!String.IsNullOrEmpty(returnUrl) && (returnUrl.StartsWith("~", StringComparison.Ordinal) || returnUrl.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath"))) { URLHelper.Redirect(UrlResolver.ResolveUrl(HttpUtility.UrlDecode(returnUrl))); } } // Hide registration form pnlRegForm.Visible = false; }
public PageViewContextFactory(IContentLoader contentLoader, UrlResolver urlResolver) { _contentLoader = contentLoader; _urlResolver = urlResolver; }
/// <summary> /// Saves exchange rates. /// </summary> private void Save() { // Check permissions CheckConfigurationModification(); string errorMessage = new Validator().NotEmpty(txtExchangeTableDisplayName.Text.Trim(), GetString("general.requiresdisplayname")).Result; if ((errorMessage == "") && (plcRateFromGlobal.Visible)) { errorMessage = new Validator().NotEmpty(txtGlobalExchangeRate.Text.Trim(), GetString("ExchangeTable_Edit.DoubleFormatRequired")).Result; } if ((errorMessage == "") && (plcRateFromGlobal.Visible)) { if (!ValidationHelper.IsPositiveNumber(txtGlobalExchangeRate.Text.Trim()) || (ValidationHelper.GetDouble(txtGlobalExchangeRate.Text.Trim(), 0) == 0)) { errorMessage = GetString("ExchangeTable_Edit.errorRate"); } } // From/to date validation if (errorMessage == "") { if ((!dtPickerExchangeTableValidFrom.IsValidRange()) || (!dtPickerExchangeTableValidTo.IsValidRange())) { errorMessage = GetString("general.errorinvaliddatetimerange"); } if ((dtPickerExchangeTableValidFrom.SelectedDateTime != DateTime.MinValue) && (dtPickerExchangeTableValidTo.SelectedDateTime != DateTime.MinValue) && (dtPickerExchangeTableValidFrom.SelectedDateTime >= dtPickerExchangeTableValidTo.SelectedDateTime)) { errorMessage = GetString("General.DateOverlaps"); } } // Exchange rates validation if (errorMessage == String.Empty) { foreach (TextBox txt in mTextBoxes.Values) { string tmp = txt.Text.Trim(); if (tmp != String.Empty) { // Exchange rate must be double if (!ValidationHelper.IsDouble(tmp)) { errorMessage = GetString("ExchangeTable_Edit.DoubleFormatRequired"); break; } // Exchange rate must be positive double rate = ValidationHelper.GetDouble(tmp, 1); if (rate <= 0) { errorMessage = GetString("ExchangeTable_Edit.errorRate"); } } } } // Save changes if no validation error if (errorMessage == "") { // Truncate display name string displayName = txtExchangeTableDisplayName.Text.Trim().Truncate(txtExchangeTableDisplayName.MaxLength); ExchangeTableInfo exchangeTableObj = ExchangeTableInfoProvider.GetExchangeTableInfo(displayName, SiteInfoProvider.GetSiteName(ConfiguredSiteID)); // If exchangeTableName value is unique if ((exchangeTableObj == null) || (exchangeTableObj.ExchangeTableID == mExchangeTableId)) { // Get ExchangeTableInfo object by primary key exchangeTableObj = ExchangeTableInfoProvider.GetExchangeTableInfo(mExchangeTableId); if (exchangeTableObj == null) { // Create new item -> insert exchangeTableObj = new ExchangeTableInfo(); exchangeTableObj.ExchangeTableSiteID = ConfiguredSiteID; } exchangeTableObj.ExchangeTableValidFrom = dtPickerExchangeTableValidFrom.SelectedDateTime; exchangeTableObj.ExchangeTableDisplayName = displayName; exchangeTableObj.ExchangeTableValidTo = dtPickerExchangeTableValidTo.SelectedDateTime; exchangeTableObj.ExchangeTableRateFromGlobalCurrency = 0; if (plcRateFromGlobal.Visible) { exchangeTableObj.ExchangeTableRateFromGlobalCurrency = ValidationHelper.GetDouble(txtGlobalExchangeRate.Text.Trim(), 0); } // Save general exchange table information ExchangeTableInfoProvider.SetExchangeTableInfo(exchangeTableObj); // Save rates on edit if (mExchangeTableId > 0) { foreach (TextBox txt in mTextBoxes.Values) { if (mData[txt.ClientID] != null) { int rateCurrencyId = ValidationHelper.GetInteger(((DataRowView)mData[txt.ClientID])["CurrencyID"], 0); bool rateExists = mExchangeRates.ContainsKey(rateCurrencyId); if (rateExists) { ExchangeRateInfo rate = new ExchangeRateInfo(mExchangeRates[rateCurrencyId]); if (txt.Text.Trim() == String.Empty) { // Remove exchange rate ExchangeRateInfoProvider.DeleteExchangeRateInfo(rate); } else { rate.ExchangeRateValue = ValidationHelper.GetDouble(txt.Text.Trim(), 0); // Update rate ExchangeRateInfoProvider.SetExchangeRateInfo(rate); } } else { if (txt.Text.Trim() != String.Empty) { // Insert exchange rate var rate = new ExchangeRateInfo { ExchangeRateToCurrencyID = rateCurrencyId, ExchangeRateValue = ValidationHelper.GetDouble(txt.Text.Trim(), 0), ExchangeTableID = mExchangeTableId }; ExchangeRateInfoProvider.SetExchangeRateInfo(rate); } } } } } URLHelper.Redirect(UrlResolver.ResolveUrl("ExchangeTable_Edit.aspx?exchangeid=" + exchangeTableObj.ExchangeTableID + "&saved=1&siteId=" + SiteID)); } else { // Show error message ShowError(GetString("ExchangeTable_Edit.CurrencyNameExists")); } } else { // Show error message ShowError(errorMessage); } }
public MediaController(UrlResolver urlResolver) { _urlResolver = urlResolver; }
public PageViewContextFactory(IContentLoader contentLoader, UrlResolver urlResolver, IDatabaseMode databaseMode) { _contentLoader = contentLoader; _urlResolver = urlResolver; _databaseMode = databaseMode; }
/// <summary> /// Deletes document(s). /// </summary> private void Delete(object parameter) { if (parameter == null || nodeIds.Count < 1) { return; } if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Blogs, ObjectActionEnum.Edit)) { AddError(GetString("cmsdesk.blogdeletelicenselimitations", currentCulture)); return; } if (!LicenseHelper.LicenseVersionCheck(RequestContext.CurrentDomain, FeatureEnum.Documents, ObjectActionEnum.Edit)) { AddError(GetString("cmsdesk.documentdeletelicenselimitations", currentCulture)); return; } int refreshId = 0; TreeProvider tree = new TreeProvider(currentUser); tree.AllowAsyncActions = false; string[] parameters = ((string)parameter).Split(';'); bool allLevelsSelected = ValidationHelper.GetBoolean(parameters[3], false); try { string siteName = parameters[1]; bool isMultipleDelete = ValidationHelper.GetBoolean(parameters[2], false); // Prepare the where condition string where = new WhereCondition().WhereIn("NodeID", nodeIds).ToString(true); string columns = SqlHelper.MergeColumns(DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS, "NodeAliasPath, ClassName, DocumentCulture, NodeParentID"); bool combineWithDefaultCulture = false; string cultureCode = parameters[0]; switch (parameters[4]) { // Standard page deletion case "documentoptions": combineWithDefaultCulture = chkAllCultures.Checked; cultureCode = combineWithDefaultCulture ? TreeProvider.ALL_CULTURES : parameters[0]; break; // Root page deletion case "rootoptions": cultureCode = rblRoot.SelectedValue == "allpages" ? TreeProvider.ALL_CULTURES : parameters[0]; where = rblRoot.SelectedValue == "allculturepages" ? String.Empty : where; break; } // Begin log AddLog(GetString("ContentDelete.DeletingDocuments", currentCulture)); string orderBy = "NodeAliasPath DESC"; if (cultureCode == TreeProvider.ALL_CULTURES) { // Default culture has to be selected on last position string defaultCulture = CultureHelper.GetDefaultCultureCode(siteName); orderBy += ", CASE WHEN DocumentCulture = '" + SqlHelper.EscapeQuotes(defaultCulture) + "' THEN 1 ELSE 0 END"; } // Get the documents DataSet ds = tree.SelectNodes(siteName, "/%", cultureCode, combineWithDefaultCulture, null, where, orderBy, TreeProvider.ALL_LEVELS, false, 0, columns); if (!DataHelper.DataSourceIsEmpty(ds)) { string altPath = Convert.ToString(selAltPath.Value); TreeNode altNode = null; if (chkUseDeletedPath.Checked && !String.IsNullOrEmpty(altPath)) { altNode = tree.SelectNodes() .OnSite(siteName) .Path(altPath) .CombineWithAnyCulture() .TopN(1) .WithCoupledColumns() .FirstOrDefault(); // Check whether user is authorized to use alternating document if (altNode != null) { if (currentUser.IsAuthorizedPerDocument(altNode, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied) { throw new Exception(GetString("contentdelete.notallowedalternating")); } } else { // Do not allow to delete a page with specified redirection URL which is not valid throw new Exception(GetString("contentdelete.redirectionurlisnotvalid")); } } // Delete the documents foreach (DataRow nodeRow in ds.Tables[0].Rows) { // Get the current document string className = nodeRow["ClassName"].ToString(); string aliasPath = nodeRow["NodeAliasPath"].ToString(); string docCulture = nodeRow["DocumentCulture"].ToString(); refreshId = ValidationHelper.GetInteger(nodeRow["NodeParentID"], 0); if (refreshId == 0) { refreshId = ValidationHelper.GetInteger(nodeRow["NodeID"], 0); } TreeNode node = DocumentHelper.GetDocument(siteName, aliasPath, docCulture, false, className, null, null, TreeProvider.ALL_LEVELS, false, null, tree); if (node == null) { AddLog(String.Format(GetString("ContentRequest.DocumentNoLongerExists", currentCulture), HTMLHelper.HTMLEncode(aliasPath))); continue; } // Ensure current parent ID int parentId = node.NodeParentID; // Check if bound SKU can be deleted (if any) bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node); // Check delete permissions if (IsUserAuthorizedToDeleteDocument(node) && (CanDestroy(node) || !chkDestroy.Checked) && authorizedToDeleteSKU) { // Delete the document if (parentId <= 0) { parentId = node.NodeID; } // Prepare settings for delete var settings = new DeleteDocumentSettings(node, chkAllCultures.Checked, chkDestroy.Checked, tree); bool skip = false; // Add additional settings if alternating document is specified if (altNode != null) { var nodeAliasPath = node.NodeAliasPath; var altNodeAliasPath = altNode.NodeAliasPath; // Skip deletion for pages which have alternative node as their child or itself if (altNodeAliasPath.EqualsCSafe(nodeAliasPath, true) || altNodeAliasPath.StartsWithCSafe(nodeAliasPath.TrimEnd('/') + "/", true)) { AddError(String.Format(GetString("contentdelete.redirectionurltosamepage"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); skip = true; } else { settings.AlternatingDocument = altNode; settings.AlternatingDocumentCopyAllPaths = chkAltAliases.Checked; settings.AlternatingDocumentMaxLevel = chkAltSubNodes.Checked ? -1 : node.NodeLevel; } } // Delete document refreshId = !skip && DocumentHelper.DeleteDocument(settings) || isMultipleDelete ? parentId : node.NodeID; } // Access denied - not authorized to delete the document else { AddError(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument", currentCulture), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } } else { AddError(GetString("DeleteDocument.CultureNotExists", currentCulture)); } } catch (ThreadAbortException ex) { if (CMSThread.Stopped(ex)) { // When canceled base.ShowError(GetString("DeleteDocument.DeletionCanceled", currentCulture)); } else { // Log error LogExceptionToEventLog(ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex); } finally { if (String.IsNullOrEmpty(CurrentError)) { // Overwrite refreshId variable if sub-levels are visible if (allLevelsSelected && Parameters.ContainsKey("refreshnodeid")) { refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); } // Refresh tree or page (on-site editing) if (!RequiresDialog) { ctlAsyncLog.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");"; } else { // Go to the root by default string url = UrlResolver.ResolveUrl("~/"); // Update the refresh node id when set in the parent dialog if (Parameters != null) { int refreshNodeId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); if (refreshNodeId > 0) { refreshId = refreshNodeId; } } // Try go to the parent document if (refreshId > 0) { TreeProvider tp = new TreeProvider(MembershipContext.AuthenticatedUser); TreeNode tn = DocumentHelper.GetDocument(refreshId, TreeProvider.ALL_CULTURES, tp); if (tn != null) { url = UrlResolver.ResolveUrl(DocumentURLProvider.GetUrl(tn)); } } ctlAsyncLog.Parameter = "window.refreshPageOnClose = true; window.reloadPageUrl = " + ScriptHelper.GetString(url) + "; CloseDialog();"; } } else { ctlAsyncLog.Parameter = "RefreshTree(null, null);"; } } }
public FacetUrlService(DynamicDataStoreFactory dynamicDataStoreFactory, ISynchronizedObjectInstanceCache objectInstanceCache, UrlResolver urlResolver) { _dynamicDataStoreFactory = dynamicDataStoreFactory; _objectInstanceCache = objectInstanceCache; _urlResolver = urlResolver; }
private void btnCancel_Click(object sender, EventArgs e) { URLHelper.Redirect(UrlResolver.ResolveUrl(mGroupListUrl)); }
protected override void OnInit(EventArgs e) { base.OnInit(e); string contentUrl = "Product_List.aspx" + RequestContext.CurrentQueryString; // Display product list if display tree of product sections is not allowed if (ECommerceSettings.ProductsTree(SiteContext.CurrentSiteID) == ProductsTreeModeEnum.None) { URLHelper.Redirect(UrlResolver.ResolveUrl(contentUrl)); } contenttree.Values.AddRange(new[] { new UILayoutValue("NodeID", ResultNodeID), new UILayoutValue("ExpandNodeID", ExpandNodeID), new UILayoutValue("Culture", SelectedCulture) }); if (NodeID <= 0 || !IsAllowedInProductsStartingPath(NodeID)) { // Root string baseDoc = "/"; if (!string.IsNullOrEmpty(ProductsStartingPath)) { // Change to products root node baseDoc = ProductsStartingPath.TrimEnd('/'); } // Get the root node TreeNode rootNode = Tree.SelectSingleNode(SiteContext.CurrentSiteName, baseDoc, TreeProvider.ALL_CULTURES, false, null, false); if (rootNode != null) { string nodeString = rootNode.NodeID.ToString(); contentUrl = URLHelper.AddParameterToUrl(contentUrl, "nodeId", nodeString); // Set default live site URL in header link string liveURL = UrlResolver.ResolveUrl(rootNode.RelativeURL); liveURL = URLHelper.AddParameterToUrl(liveURL, "viewmode", ((int)ViewModeEnum.LiveSite).ToString()); ScriptHelper.RegisterStartupScript(this, typeof(string), "SetDefaultLiveSiteURL", ScriptHelper.GetScript("SetLiveSiteURL('" + liveURL + "');")); } } contentview.Src = contentUrl; ScriptHelper.RegisterScriptFile(Page, "~/CMSModules/Content/CMSDesk/Content.js"); // Override content functions AddScript( @" function SetMode(mode, passive) { if (!CheckChanges()) { return false; } SetSelectedMode(mode); if (!passive) { DisplayDocument(); } return true; } function DragOperation(nodeId, targetNodeId, operation) { window.PerformContentRedirect(null, 'drag', nodeId, '&action=' + operation + '&targetnodeid=' + targetNodeId + '&mode=productssection'); } "); }
protected object gridOrders_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName.ToLowerInvariant()) { case "grandtotal": DataRowView dr = (DataRowView)parameter; int currencyId = ValidationHelper.GetInteger(dr["OrderCurrencyID"], 0); var currency = CurrencyInfoProvider.GetCurrencyInfo(currencyId); // If order is not in main currency, show order price if (currency != null) { var orderTotalPrice = ValidationHelper.GetDecimal(dr["OrderGrandTotal"], 0); var priceFormatted = currency.FormatPrice(orderTotalPrice); // Formatted currency return(HTMLHelper.HTMLEncode(priceFormatted)); } return(string.Empty); case "invoice": return("<a target=\"_blank\" href=\"" + UrlResolver.ResolveUrl("~/CMSModules/Ecommerce/CMSPages/GetInvoice.aspx?orderid=" + ValidationHelper.GetInteger(parameter, 0)) + "\">" + GetString("general.view") + "</a>"); case "downloads": int orderId = ValidationHelper.GetInteger(parameter, 0); // Get order item SKU files for the order DataSet orderItemSkuFiles = OrderItemSKUFileInfoProvider.GetOrderItemSKUFiles(orderId); // If there are some downloads available for the order if (!DataHelper.DataSourceIsEmpty(orderItemSkuFiles)) { // Make download links column visible downloadLinksColumnVisible = true; // Show view action for this record string url = UrlResolver.ResolveUrl("~/CMSModules/Ecommerce/CMSPages/EProducts.aspx?orderid=" + orderId); return(String.Format("<a href=\"#\" onclick=\"{0} \">{1}</a>", ScriptHelper.GetModalDialogScript(url, "DownloadLinks", 700, 600), GetString("general.view"))); } return(String.Empty); case "ordertoshoppingcart": int id = ValidationHelper.GetInteger(parameter, 0); LinkButton addToCartButton = new LinkButton { OnClientClick = "return confirm(" + ScriptHelper.GetLocalizedString("myorders.addtocart") + ");", Text = GetString("myorders.reorder") }; addToCartButton.Click += (s, e) => AddToCart(id); return(addToCartButton); } return(parameter); }
public VideoFileController(UrlResolver urlResolver) { _urlResolver = urlResolver; }
public ImageFileController(UrlResolver urlResolver) { _urlResolver = urlResolver; }
/// <summary> /// Factory method for instantiating new QueryStringBuilder with provided URL. /// </summary> /// <param name="contentLink">Content for which to build query.</param> /// <returns>Instance of QueryStringBuilder.</returns> /// <param name="urlResolver">UrlResolver instance.</param> /// <param name="includeHost">Mark if include host name in the url.</param> public static QueryStringBuilder Create(ContentReference contentLink, UrlResolver urlResolver, bool includeHost = false) { return new QueryStringBuilder(contentLink, urlResolver, includeHost); }
public PreviewUrlResolver(UrlResolver defaultUrlResolver, IContentLoader contentLoader) { _defaultUrlResolver = defaultUrlResolver; _contentLoader = contentLoader; }
public ProductHeroBlockController(IContentLoader contentLoader, UrlResolver urlResolver) { _contentLoader = contentLoader; _urlResolver = urlResolver; }
public ImageDataFileProvider(UrlResolver urlResolver) { UrlResolver = urlResolver; }
/// <summary> /// Creates collection of tabs which should be displayed to the user. /// </summary> private void GetTabs() { UITabs tabControl = CurrentMaster.Tabs; bool checkUI = true; // Disable personalization for none-HTML editors if ((CustomOutputFormat == "copy") || (CustomOutputFormat == "move") || (CustomOutputFormat == "link") || (CustomOutputFormat == "relationship") || (CustomOutputFormat == "selectpath")) { checkUI = false; } else if (IsLiveSite) { // Ensure personalization of the HTML editor on the live site checkUI = ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CKEditor:PersonalizeToolbarOnLiveSite"], false); } if (checkUI) { if ((OutputFormat == OutputFormatEnum.HTMLMedia) && !MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.WYSIWYGEditor", "InsertImageOrMedia")) { ScriptHelper.RegisterStartupScript(this, typeof(string), "frameLoad", ScriptHelper.GetScript("if (window.parent.frames['insertContent']) { window.parent.frames['insertContent'].location= '" + UrlResolver.ResolveUrl(AdministrationUrlHelper.GetAccessDeniedUrl("CMS.WYSIWYGEditor", null, "InsertImageOrMedia")) + "';} ")); return; } if ((OutputFormat == OutputFormatEnum.HTMLLink) && !MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.WYSIWYGEditor", "InsertLink")) { ScriptHelper.RegisterStartupScript(this, typeof(string), "frameLoad", ScriptHelper.GetScript("if (window.parent.frames['insertContent']) { window.parent.frames['insertContent'].location= '" + UrlResolver.ResolveUrl(AdministrationUrlHelper.GetAccessDeniedUrl("CMS.WYSIWYGEditor", null, "InsertLink")) + "';} ")); return; } if ((CustomOutputFormat == "linkdoc") && !(MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "New.LinkExistingDocument") && MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "New"))) { ScriptHelper.RegisterStartupScript(this, typeof(string), "frameLoad", ScriptHelper.GetScript("if (window.parent.frames['insertContent']) { window.parent.frames['insertContent'].location= '" + UrlResolver.ResolveUrl(AdministrationUrlHelper.GetAccessDeniedUrl("CMS.Content", null, "New.LinkExistingDocument")) + "';} ")); return; } } // Attachments if ((CustomOutputFormat == "") && (!HasMetaFileObjectInfo) && !HideAttachments && (OutputFormat != OutputFormatEnum.NodeGUID) && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "AttachmentsTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("general.attachments"), RedirectUrl = GetFilePath("Tabs_Media.aspx", "source", CMSDialogHelper.GetMediaSource(MediaSourceEnum.DocumentAttachments)) }); if (SelectedTab == "attachments") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if ((CustomOutputFormat == "") && (HasMetaFileObjectInfo) && !HideAttachments && (OutputFormat != OutputFormatEnum.NodeGUID) && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "MetafilesTab"))) { // Metafile attachments tabControl.AddTab(new UITabItem() { Text = GetString("general.attachments"), RedirectUrl = GetFilePath("Tabs_Media.aspx", "source", CMSDialogHelper.GetMediaSource(MediaSourceEnum.MetaFile)) }); if (SelectedTab == "attachments") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if (SelectedTab == "attachments") { SelectedTab = "web"; } // Content if (!HideContent && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "ContentTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("general.content"), RedirectUrl = GetFilePath("Tabs_Media.aspx", "source", CMSDialogHelper.GetMediaSource(MediaSourceEnum.Content)) }); if (SelectedTab == "content") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if (SelectedTab == "content") { SelectedTab = "web"; } // Media libraries if ((CustomOutputFormat == "") && !HideMediaLibraries && (OutputFormat != OutputFormatEnum.NodeGUID) && ModuleManager.IsModuleLoaded(ModuleName.MEDIALIBRARY) && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "MediaLibrariesTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("dialogs.header.libraries"), RedirectUrl = GetMediaLibrariesPath() }); if (SelectedTab == "libraries") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if (SelectedTab == "libraries") { SelectedTab = "web"; } // Web if ((CustomOutputFormat == "") && !HideWeb && (OutputFormat != OutputFormatEnum.NodeGUID) && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "WebTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("dialogs.header.web"), RedirectUrl = (OutputFormat == OutputFormatEnum.BBLink) || (OutputFormat == OutputFormatEnum.HTMLLink) ? GetFilePath("Tabs_WebLink.aspx") : GetFilePath("Tabs_Web.aspx") }); if (SelectedTab == "web") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } // Anchor & E-mail if ((CustomOutputFormat == "") && ((OutputFormat == OutputFormatEnum.BBLink) || (OutputFormat == OutputFormatEnum.HTMLLink) || (OutputFormat == OutputFormatEnum.Custom))) { // Anchor if (!HideAnchor && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "AnchorTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("dialogs.header.anchor"), RedirectUrl = GetFilePath("Tabs_Anchor.aspx") }); if (SelectedTab == "anchor") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if (SelectedTab == "anchor") { SelectedTab = "web"; } // E-mail if (!HideEmail && (!checkUI || currentUser.IsAuthorizedPerUIElement("CMS.MediaDialog", "EmailTab"))) { tabControl.AddTab(new UITabItem() { Text = GetString("general.email"), RedirectUrl = GetFilePath("Tabs_Email.aspx") }); if (SelectedTab == "email") { mSelectedTabIndex = tabControl.TabItems.Count - 1; } } else if (SelectedTab == "email") { SelectedTab = "web"; } } string selectedUrl = ((mSelectedTabIndex > 0) ? tabControl.TabItems[mSelectedTabIndex].RedirectUrl : ((tabControl.TabItems.Count > 0) ? tabControl.TabItems[0].RedirectUrl : String.Empty)); if (!String.IsNullOrEmpty(selectedUrl)) { ScriptHelper.RegisterStartupScript(this, typeof(string), "frameLoad", ScriptHelper.GetScript("if (window.parent.frames['insertContent']) { window.parent.frames['insertContent'].location= '" + selectedUrl.Replace("&", "&").Replace("'", "%27") + "';} ")); } // No tab is displayed -> load UI Not available if (tabControl.TabItems.Count == 0) { ScriptHelper.RegisterStartupScript(this, typeof(string), "frameLoad", ScriptHelper.GetScript("if (window.parent.frames['insertContent']) { window.parent.frames['insertContent'].location= '" + UrlResolver.ResolveUrl(AdministrationUrlHelper.GetInformationUrl("uiprofile.uinotavailable")) + "';} ")); } else if (tabControl.TabItems.Count == 1) { tabControl.Visible = false; // Hide empty space because of hidden tab control ScriptHelper.RegisterStartupScript(this, typeof(string), "headerFrameHide", ScriptHelper.GetScript("parent.$cmsj('#rowsFrameset').attr('rows','" + CMSPage.TitleOnlyHeight + ", *, " + CMSPage.FooterFrameHeight + "')")); } }
public FavoritesController(UrlResolver urlResolver) { this.urlResolver = urlResolver; }
/// <summary> /// Stores data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (!selSite.UniSelector.HasData || !selectForm.HasData) { ShowError(GetString("srch.err.selectform")); return; } SearchIndexInfo sii = SearchIndexInfoProvider.GetSearchIndexInfo(ItemID); if (sii != null) { SearchIndexSettings sis = sii.IndexSettings; SearchIndexSettingsInfo sisi; var isInsert = false; if (ItemGUID != Guid.Empty) { // If we are updating existing Search Index Settings Info sisi = sis.GetSearchIndexSettingsInfo(ItemGUID); } else { // If we are creating new Search Index Settings Info isInsert = true; sisi = new SearchIndexSettingsInfo(); sisi.ID = Guid.NewGuid(); } // Save values if (sisi != null) { string formName = ValidationHelper.GetString(selectForm.Value, ""); sisi.SetValue("FormName", formName); sisi.WhereCondition = txtWhere.TextArea.Text.Trim(); sisi.SiteName = selSite.Value.ToString(); BizFormInfo bfi = BizFormInfoProvider.GetBizFormInfo(formName, sisi.SiteName); if (bfi != null) { sisi.SetValue("DisplayName", bfi.FormDisplayName); sisi.ClassNames = BizFormItemProvider.BIZFORM_ITEM_PREFIX + DataClassInfoProvider.GetClassName(bfi.FormClassID); } // Update settings item sis.SetSearchIndexSettingsInfo(sisi); // Update xml value sii.IndexSettings = sis; SearchIndexInfoProvider.SetSearchIndexInfo(sii); ItemGUID = sisi.ID; if (isInsert) { // Redirect to edit mode var editUrl = "SearchIndex_Content_Edit.aspx"; editUrl = URLHelper.AddParameterToUrl(editUrl, "indexId", sii.IndexID.ToString()); editUrl = URLHelper.AddParameterToUrl(editUrl, "guid", sisi.ID.ToString()); editUrl = URLHelper.AddParameterToUrl(editUrl, "saved", "1"); if (smartSearchEnabled) { editUrl = URLHelper.AddParameterToUrl(editUrl, "rebuild", "1"); } URLHelper.Redirect(UrlResolver.ResolveUrl(editUrl)); } ShowChangesSaved(); if (smartSearchEnabled) { // Show rebuild message ShowInformation(String.Format(GetString("srch.indexrequiresrebuild"), "<a href=\"javascript:" + Page.ClientScript.GetPostBackEventReference(this, "saved") + "\">" + GetString("General.clickhere") + "</a>")); } } // Error loading SearchIndexSettingsInfo else { ShowError(GetString("srch.err.loadingsisi")); } } // Error loading SearchIndexInfo else { ShowError(GetString("srch.err.loadingsii")); } }