コード例 #1
0
        public ProcessInboundRulesResult GetUrlResults(string url, Database database, NameValueCollection serverVariables = null)
        {
            var rewriter = new InboundRewriter();

            var rulesEngine  = new RulesEngine(database);
            var inboundRules = rulesEngine.GetInboundRules();

            var requestUri  = new Uri(url);
            var siteContext = SiteContextFactory.GetSiteContext(requestUri.Host, requestUri.AbsolutePath,
                                                                requestUri.Port);

            rewriter.RequestServerVariables = serverVariables ?? new NameValueCollection();

            if (!rewriter.RequestServerVariables.AllKeys.Contains("HTTP_HOST"))
            {
                rewriter.RequestServerVariables.Add("HTTP_HOST", requestUri.Host);
            }

            if (!rewriter.RequestServerVariables.AllKeys.Contains("HTTPS"))
            {
                rewriter.RequestServerVariables.Add("HTTPS", requestUri.Scheme.Equals(Uri.UriSchemeHttps) ? "on" : "off");
            }

            if (!rewriter.RequestServerVariables.AllKeys.Contains("QUERY_STRING") && requestUri.Query.Length > 0)
            {
                rewriter.RequestServerVariables.Add("QUERY_STRING", requestUri.Query.Remove(0, 1));
            }

            var results = rewriter.ProcessRequestUrl(requestUri, inboundRules, siteContext, database);

            return(results);
        }
コード例 #2
0
ファイル: AkismetSpamCheck.cs プロジェクト: phaniav/WeBlog
        public void Process(CreateCommentArgs args)
        {
            Assert.IsNotNull(args.CommentItem, "Comment Item cannot be null");

            if (!string.IsNullOrEmpty(Settings.AkismetAPIKey) && !string.IsNullOrEmpty(Settings.CommentWorkflowCommandSpam))
            {
                var workflow = args.Database.WorkflowProvider.GetWorkflow(args.CommentItem);

                if (workflow != null)
                {
                    var api    = new Akismet(Settings.AkismetAPIKey, ManagerFactory.BlogManagerInstance.GetCurrentBlog().SafeGet(x => x.Url), "WeBlog/2.1");
                    var isSpam = api.CommentCheck(args.CommentItem);

                    if (isSpam)
                    {
                        //Need to switch to shell website to execute workflow
                        using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(Sitecore.Constants.ShellSiteName)))
                        {
                            workflow.Execute(Settings.CommentWorkflowCommandSpam, args.CommentItem, "Akismet classified this comment as spam", false, new object[0]);
                        }

                        args.AbortPipeline();
                    }
                }
            }
        }
コード例 #3
0
        //protected override string UnsubscribeContact(ContactIdentifier contactIdentifier, Guid messageID)
        //{
        //  SupportUnsubscribeMessage unsubscribeMessage = new SupportUnsubscribeMessage
        //  {
        //    AddToGlobalOptOutList = true,
        //    ContactIdentifier = contactIdentifier,
        //    MessageId = messageID,
        //    MessageLanguage = LanguageName
        //  };
        //  base.ClientApiService.Unsubscribe(unsubscribeMessage);
        //  return (ExmContext.Message.ManagerRoot.GetConfirmativePageUrl() ?? "/");
        //}

        protected override string VerifyContactSubscriptions(ContactIdentifier contactIdentifier, Guid messageID)
        {
            var result = base.VerifyContactSubscriptions(contactIdentifier, messageID);

            if (string.IsNullOrEmpty(result))
            {
                return(result);
            }

            #region Sitecore.Support.224113

            string   alreadyItemPath = ExmContext.Message.ManagerRoot.Settings.AlreadyUnsubscribedPage;
            Item     alreadyItem     = Database.GetDatabase("web").GetItem(alreadyItemPath);
            string   itemUrl         = String.Empty;
            SiteInfo site            = null;
            var      siteInfoList    = Sitecore.Configuration.Factory.GetSiteInfoList();
            foreach (SiteInfo siteInf in siteInfoList)
            {
                if (siteInf.RootPath.ToLowerInvariant().Trim() != "" && siteInf.StartItem.ToLowerInvariant().Trim() != "" && alreadyItem.Paths.FullPath.ToLowerInvariant().Trim().Contains(siteInf.RootPath.ToLowerInvariant().Trim() + siteInf.StartItem.ToLowerInvariant().Trim()))
                {
                    site = siteInf;
                }
            }

            using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(site.Name)))
            {
                itemUrl = LinkManager.GetItemUrl(alreadyItem);
            }
            return(itemUrl);

            #endregion
        }
コード例 #4
0
        /// <summary>
        /// Resolves the <see cref="Sitecore.Sites.SiteContext"/> based on the current rawurl. There are several steps to check for a valid site:
        /// <list type="number">
        /// <item>Check for querystring parameter <c>sc_site</c></item>
        /// <item>Check for querystring parameter <c>site</c></item>
        /// <item>Check for site in the path</item>
        /// </list>
        /// </summary>
        /// <param name="lang">The current language.</param>
        /// <returns>Site if it could be resolved from the rawUrl, the context site otherwise.</returns>
        public static SiteContext ResolveSite(Language lang)
        {
            SiteContext siteContext = null;

            string querystring = Sitecore.Web.WebUtil.ExtractUrlParm("sc_site", Sitecore.Web.WebUtil.GetRawUrl());

            if (!string.IsNullOrEmpty(querystring))
            {
                siteContext = SiteContextFactory.GetSiteContext(querystring);
                if (siteContext != null)
                {
                    return(siteContext);
                }
            }

            querystring = Sitecore.Web.WebUtil.ExtractUrlParm("site", Sitecore.Web.WebUtil.GetRawUrl());
            if (!string.IsNullOrEmpty(querystring))
            {
                siteContext = SiteContextFactory.GetSiteContext(querystring);
                if (siteContext != null)
                {
                    return(siteContext);
                }
            }

            siteContext = SiteContextFactory.GetSiteContext(Sitecore.Web.WebUtil.GetHostName(), Sitecore.Web.WebUtil.GetRawUrl().Replace("/" + lang + "/", "/"));
            if (siteContext != null)
            {
                return(siteContext);
            }

            return(Sitecore.Context.Site);
        }
コード例 #5
0
        public virtual BusinessCatalogSettings GetSiteSettings([NotNull] ItemUri siteItemUri)
        {
            Assert.ArgumentNotNull(siteItemUri, "siteItemUri");

            Item contextItem = Database.GetItem(siteItemUri);

            Assert.IsNotNull(contextItem, "Unable to resolve catalog's context item.");

            string siteName = SiteUtils.GetSiteByItem(contextItem);

            Assert.IsNotNullOrEmpty(siteName, "Unable to resolve catalog's website context.");

            SiteContext site = SiteContextFactory.GetSiteContext(siteName);

            Assert.IsNotNull(site, "Unable to resolve catalog's website context.");

            BusinessCatalogSettings settings;
            Database database = Configuration.Factory.GetDatabase(siteItemUri.DatabaseName);

            using (new SiteContextSwitcher(site))
            {
                using (new SiteIndependentDatabaseSwitcher(database))
                {
                    settings = Context.Entity.GetConfiguration <BusinessCatalogSettings>();
                }
            }

            return(settings);
        }
        /// <summary>
        /// Resolves the site context.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns></returns>
        protected virtual SiteContext ResolveSiteContext(HttpRequestArgs args, Item aliasItem)
        {
            SiteContext siteContext;
            string      queryString = WebUtil.GetQueryString("sc_site");

            if (queryString.Length > 0)
            {
                siteContext = SiteContextFactory.GetSiteContext(queryString);
                Assert.IsNotNull(siteContext, string.Concat("Site from query string was not found: ", queryString));
                return(siteContext);
            }
            if (Settings.EnableSiteConfigFiles)
            {
                string[] directoryName = new string[] { Path.GetDirectoryName(args.Url.FilePath) };
                string   str           = StringUtil.GetString(directoryName);
                string   str1          = FileUtil.MakePath(FileUtil.NormalizeWebPath(str), "site.config");
                if (FileUtil.Exists(str1))
                {
                    siteContext = SiteContextFactory.GetSiteContextFromFile(str1);
                    Assert.IsNotNull(siteContext, string.Concat("Site from site.config was not found: ", str1));
                    return(siteContext);
                }
            }
            Uri requestUri = WebUtil.GetRequestUri();

            siteContext = SiteContextFactory.GetSiteContext(requestUri.Host, aliasItem.Paths.FullPath.Replace(Sitecore.Context.Site.RootPath, string.Empty), requestUri.Port);
            Assert.IsNotNull(siteContext, string.Concat("Site from host name and path was not found. Host: ", requestUri.Host, ", path: ", args.Url.FilePath));
            return(siteContext);
        }
コード例 #7
0
        /// <summary>
        /// Called when the item has deleted.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public virtual void OnItemDeleted([NotNull] ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            foreach (Item item in this.GetItems(args))
            {
                if (item.TemplateID == this.orderTemplateId)
                {
                    return;
                }

                if (item.TemplateID != this.orderLineTemplateId)
                {
                    continue;
                }

                string site = SiteUtils.GetSiteByItem(item.Parent);
                if (string.IsNullOrEmpty(site))
                {
                    return;
                }

                SiteContext siteContext = SiteContextFactory.GetSiteContext(site);
                using (new SiteContextSwitcher(siteContext))
                {
                    DomainModel.Orders.Order order = this.GetOrder(item.Parent);
                    order.OrderLines.Remove(order.OrderLines.Where(ol => ol.Id == item.ID.ToString()).FirstOrDefault());

                    this.RecalculateOrder(order);
                }
            }
        }
コード例 #8
0
        //TODO - share this with RedirectItemResolver
        protected virtual string GetRedirectUrl(Item redirectItem)
        {
            LinkField redirectLinkField = redirectItem.Fields[Templates.AdvancedRedirect.Fields.Target];
            string    redirectUrl       = null;

            if (redirectLinkField != null)
            {
                if (!redirectLinkField.IsInternal || redirectLinkField.TargetItem == null)
                {
                    redirectUrl = (!redirectLinkField.IsMediaLink || redirectLinkField.TargetItem == null ? redirectLinkField.Url : ((MediaItem)redirectLinkField.TargetItem).GetMediaUrl(null));
                }
                else
                {
                    //TODO - get site of taret item, not context, to support cross site resolving
                    SiteInfo siteInfo = Context.Site.SiteInfo;

                    //get the base options from the link provider
                    ItemUrlBuilderOptions defaultOptions = new DefaultItemUrlBuilderOptions();

                    defaultOptions.Site = SiteContextFactory.GetSiteContext(siteInfo.Name);
                    defaultOptions.AlwaysIncludeServerUrl = true;
                    defaultOptions.SiteResolving          = true;

                    //inject option for languageembedding
                    defaultOptions.LanguageEmbedding = LanguageEmbedding.Never;

                    redirectUrl = LinkManager.GetItemUrl(redirectLinkField.TargetItem, defaultOptions);
                }
            }

            return(redirectUrl);
        }
コード例 #9
0
ファイル: OrderUpdate.svc.cs プロジェクト: writele/training
        public void UpdateOrderShipped(string orderNumber, string trackingUrl)
        {
            try
            {
                var siteContext     = SiteContextFactory.GetSiteContext(ShopContext);
                var databaseContext = Database.GetDatabase(DatabaseContext);
                using (new ShopContextSwitcher(siteContext, databaseContext))
                {
                    var statesRepository = Sitecore.Ecommerce.Context.Entity.Resolve <IOrderStatesRepository>();
                    var endState         = statesRepository.GetStates().Single(state => state.Code == EndStatus);

                    var orderManager = Sitecore.Ecommerce.Context.Entity.Resolve <Orders.Management.IOrderManager <Order> >();
                    var order        = orderManager.GetOrder(orderNumber);
                    if (order == null)
                    {
                        throw new Exception(string.Format("Order {0} not found", orderNumber));
                    }
                    order.State = endState;
                    order.DefaultDelivery.TrackingID = trackingUrl;
                    orderManager.Save();
                }
            }
            catch (Exception e)
            {
                Sitecore.Diagnostics.Log.Error("Error during order update service call", e, this);
                throw;
            }
        }
コード例 #10
0
        private string getSiteIdFromName(string name)
        {
            SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(name).Name);
            var         db          = Context.ContentDatabase ?? Context.Database;

            return(db.GetItem(siteContext.StartPath).ID.ToString());
        }
コード例 #11
0
ファイル: SiteContext.cs プロジェクト: aokour/NimbleSearch
        public virtual SiteContext GetSiteContext(Item item)
        {
            var itemPath = item?.Paths.FullPath;

            if (string.IsNullOrEmpty(itemPath))
            {
                return(null);
            }

            itemPath = itemPath.EnsurePrefix("/").EnsureSuffix("/").ToUpperInvariant();

            foreach (var site in SiteContextFactory.Sites)
            {
                // skip system sites
                if (Abstractions.Constants.SystemSites.IndexOf(site.Name) >= 0)
                {
                    continue;
                }

                // skip sites without a path
                if (site.RootPath.Length == 0)
                {
                    continue;
                }

                var startpath = site.RootPath.EnsurePrefix("/").EnsureSuffix("/").ToUpperInvariant();
                // not adding +site.StartItem; -- so it can match for shared content items too
                if (itemPath.StartsWith(startpath))
                {
                    return(SiteContextFactory.GetSiteContext(site.Name));
                }
            }
            return(null);
        }
コード例 #12
0
 private static SiteContext ResolveSiteContext(Item item)
 {
     return((
                from site in SiteManager.GetSites()
                where !Config.IgnoredSites.Contains(site.Name)
                select SiteContextFactory.GetSiteContext(site.Name) into sc
                where sc != null && item.Paths.Path.StartsWith(sc.StartPath, StringComparison.OrdinalIgnoreCase)
                select sc).FirstOrDefault <SiteContext>());
 }
コード例 #13
0
        public string ExecuteScriptBlock2(string userName, string password, string script, string cliXmlArgs,
                                          string sessionId)
        {
            var requestUri = WebUtil.GetRequestUri();
            var site       = SiteContextFactory.GetSiteContext(requestUri.Host, Sitecore.Context.Request.FilePath,
                                                               requestUri.Port);

            return(ExecuteScriptBlockinSite2(userName, password, script, cliXmlArgs, site.Name, sessionId));
        }
        public new void Run(ClientPipelineArgs args)
        {
            var hostName = WebUtil.GetHostName();
            var site     = SiteContextFactory.GetSiteContext(hostName, "/");
            var siteName = site?.Name ?? Settings.Preview.DefaultSite;

            using (new SettingsSwitcher(DefaultSiteSetting, siteName))
            {
                base.Run(args);
            }
        }
コード例 #15
0
        protected virtual Item BuildPath(Item contextItem, string localDsQuery, TemplateItem templateItem)
        {
            var folders = new Queue <string>(localDsQuery.Trim('.', '/')
                                             .Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries));

            using (new SecurityDisabler())
                using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system") ?? new SiteContext(new SiteInfo(new StringDictionary()))))
                {
                    return(BuildPath(contextItem, folders, templateItem));
                }
        }
コード例 #16
0
        public void RenderFieldOverride()
        {
            var    obj      = _sitecore.CreateClass <Super>(false, false, _item);
            string rendered = null;

            using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("website")))
            {
                rendered = _html.Editable <Super>(obj, x => x.Integer);
            }
            Assert.AreEqual(_numberContent, rendered);
        }
コード例 #17
0
        public void RenderFieldComplexInheritance()
        {
            var    obj      = _sitecore.CreateClass <Super>(false, false, _item);
            string rendered = null;

            using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("website")))
            {
                rendered = _html.Editable <Super>(obj, x => x.SingleLineText);
            }
            Assert.AreEqual(_sltContent, rendered);
        }
        private string ResolveSiteFromUrl()
        {
            var uri = HttpContext.Current?.Request?.Url;

            if (uri == null)
            {
                return(null);
            }
            var hostNameSite = SiteContextFactory.GetSiteContext(uri.Host, "/", uri.Port);

            return(!IsValidSite(hostNameSite.SiteInfo) ? null : hostNameSite.Name);
        }
コード例 #19
0
        public static XmlDocument Generate(HttpRequest request, bool useCachedCopyIfAvailable)
        {
            // Every Site in the installation will get its own sitemap.xml document.
            var key = request.Url.GetLeftPart(UriPartial.Path);

            var doc = HttpRuntime.Cache.Get(key) as XmlDocument;

            if (doc == null || !useCachedCopyIfAvailable)
            {
                doc = InitializeDocument();
                var site = SiteContextFactory.GetSiteContext(request.Url.Host, request.Url.LocalPath, request.Url.Port);

                // Regardless of whether we find a site, we will return a document, it will be empty if Sitecore can't figure out what host to map to.
                if (site != null)
                {
                    var siteCrawler = site.Properties["sitemapXmlCrawlerType"];

                    Type usethiscrawler;

                    if (!string.IsNullOrEmpty(siteCrawler))
                    {
                        usethiscrawler = Type.GetType(siteCrawler);
                    }
                    else
                    {
                        usethiscrawler = SitemapXmlHandlerConfiguration.Current.DefaultCrawlerType;
                    }

                    // start recursing through the site's items
                    // ReSharper disable once AssignNullToNotNullAttribute
                    var mycrawler = Activator.CreateInstance(usethiscrawler) as ICrawler;
                    // ReSharper disable PossibleNullReferenceException
                    mycrawler.Crawl(site, doc);
                    // ReSharper restore PossibleNullReferenceException
                }

                /*
                 * Because crawlers are fairly arbitrary and the document provides internal recommendations for freshness,
                 * we can use a simpler absolute timeout rather than slaving to Sitecore Publishing.
                 */

                if (!int.TryParse(site.Properties["sitemapXmlCacheTimeout"], out var cacheTime))
                {
                    cacheTime = SitemapXmlHandlerConfiguration.Current.DefaultCacheTimeout;
                }

                HttpRuntime.Cache.Insert(key, doc, null, DateTime.Now.AddMinutes(cacheTime), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return(doc);
        }
コード例 #20
0
 protected virtual void OnSubmit(object sender, EventArgs e)
 {
     try {
         using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(SiteName))) {
             Item   item    = Database.GetDatabase("master").GetItem(tbxItemID.Text);
             string itemUrl = LinkManager.GetItemUrl(item);
             string value   = UrlGenerationTokenValueExtractor.Current.ExtractTokenValue(tbxPattern.Text, item);
             tbxResult.Text     = value;
             tbxCurrentUrl.Text = itemUrl;
         }
     } catch (Exception ex) {
         tbxResult.Text = ex.ToString();
     }
 }
コード例 #21
0
        private static Item AddDataFolderItem(string datasourceLocation, Item parent)
        {
            var itemName = datasourceLocation.Remove(0, 2);

            using (new SecurityDisabler())
            {
                using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system")))
                {
                    var newItem = parent.Add(itemName, LocalDataFolderTemplateId);
                    newItem["SortOrder"] = "-9999";
                    return(newItem);
                }
            }
        }
コード例 #22
0
        public static SiteContext GetSiteContextByItem(Item item)
        {
            if (item == null)
            {
                return(null);
            }
            var siteName = GetSiteNameByItemPath(item.Paths.FullPath);

            if (string.IsNullOrWhiteSpace(siteName))
            {
                return(null);
            }
            return(SiteContextFactory.GetSiteContext(siteName));
        }
コード例 #23
0
        protected virtual SiteContext GetSiteContext()
        {
            if (string.IsNullOrEmpty(ddlSites.SelectedValue))
            {
                throw new ArgumentException("Please select a site.");
            }
            var siteContext = SiteContextFactory.GetSiteContext(ddlSites.SelectedValue);

            if (siteContext == null)
            {
                throw new Exception("Failed to get site context for selected site.");
            }
            return(siteContext);
        }
コード例 #24
0
        protected override void InitItemProperties(Item item)
        {
            base.InitItemProperties(item);
            // on load of the form
            string pageUrl = System.Web.HttpContext.Current.Request.Headers.GetValues("Referer").FirstOrDefault();
            var    url     = new Uri(pageUrl);

            // Obtain a SiteContext for the host and virtual path
            var siteContext = SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery);

            // Get the path to the Home item
            var homePath = siteContext.StartPath;

            if (!homePath.EndsWith("/"))
            {
                homePath += "/";
            }

            // Get the path to the item, removing virtual path if any
            var itemPath = url.AbsolutePath.ToLower();

            if (itemPath.StartsWith(siteContext.VirtualFolder))
            {
                itemPath = itemPath.Remove(0, siteContext.VirtualFolder.Length);
            }

            // Obtain the item
            var fullPath    = homePath + itemPath.Replace("-", " ");
            var contextItem = siteContext.Database.GetItem(fullPath);

            if (contextItem != null)
            {
                FileField downloadField = contextItem.Fields[new ID(SitecoreItemsConstants.FILE_URL_FIELD_ID)];

                if (downloadField.MediaItem != null)
                {
                    //var downloadItem = new MediaItem(downloadField.MediaItem);
                    FileUrl = StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(downloadField.MediaItem));
                }
                else
                {
                    FileUrl = String.Empty;
                }
            }
            else
            {
                FileUrl = String.Empty;
            }
        }
コード例 #25
0
        public ReportContext(string userName = "******", string siteName = "shell", string databaseName = "master", string language = null)
        {
            var user = User.FromName(userName, false);

            _userSwitcher     = new UserSwitcher(user);
            _databaseSwitcher = new DatabaseSwitcher(Sitecore.Configuration.Factory.GetDatabase(databaseName));

            if (!string.IsNullOrEmpty(language))
            {
                _languageSwitcher = new LanguageSwitcher(language);
            }

            _siteContextSwitcher = new SiteContextSwitcher(SiteContextFactory.GetSiteContext(siteName));
            _securityDisabler    = new SecurityDisabler();
        }
コード例 #26
0
        /// <summary>
        /// Recalculates the order.
        /// </summary>
        /// <param name="item">The item.</param>
        protected virtual void RecalculateOrder([NotNull] Item item)
        {
            Assert.ArgumentNotNull(item, "item");

            if (item.TemplateID.ToString().ToLower() == Settings.GetSetting("Ecommerce.Order.OrderItemTempalteId").ToLower() || item.TemplateID.ToString().ToLower() == Settings.GetSetting("Ecommerce.Order.OrderLineItemTempalteId").ToLower())
            {
                string      site        = SiteUtils.GetSiteByItem(item);
                SiteContext siteContext = SiteContextFactory.GetSiteContext(site);
                using (new SiteContextSwitcher(siteContext))
                {
                    DomainModel.Orders.Order order = this.GetOrder(item);
                    this.RecalculateOrder(order);
                }
            }
        }
コード例 #27
0
        public FakeSiteContextSwitcher(SiteContext site) : base(site)
        {
            if (site == null)
            {
                throw new ArgumentNullException("site");
            }

            _pocket.AddRange(SiteContextFactory.Sites);
            //SiteContextFactory stores cashed data in _searchTable so clearing .Sites is not enough
            SiteContextFactory.Reset();
            //Returning back all sites except Context to avoid duplication
            AddOnlyNew(SiteContextFactory.Sites, _pocket.Where(t => t.Name != site.Name));

            SiteContextFactory.Sites.Add(new SiteInfo(new StringDictionary(ToDictionary(site.Properties))));
        }
コード例 #28
0
        private static RenderFieldResult RenderLink(ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            string result = args.Result;
            string value  = args.Parameters["itemid"];
            string name   = args.Parameters["language"];
            string value2 = args.Parameters["version"];
            string value3 = args.Parameters["fieldid"];
            Item   item   = Context.ContentDatabase.GetItem(ID.Parse(value), Language.Parse(name),
                                                            Sitecore.Data.Version.Parse(value2));

            if (item == null)
            {
                SheerResponse.Alert("The item was not found.\n\nIt may have been deleted by another user.");
                new RenderFieldResult();
            }

            Field field = item.Fields[ID.Parse(value3)];

            using (FieldRenderer fieldRenderer = new FieldRenderer())
            {
                string text = args.Parameters["webeditparams"];
                SafeDictionary <string> parameters = new SafeDictionary <string>();
                if (!string.IsNullOrEmpty(text))
                {
                    parameters = WebUtil.ParseQueryString(text);
                }

                fieldRenderer.Item       = item;
                fieldRenderer.FieldName  = field.Name;
                fieldRenderer.Parameters = WebUtil.BuildQueryString(parameters, xhtml: false);
                fieldRenderer.OverrideFieldValue(result);
                fieldRenderer.DisableWebEditing = true;
                string formValue = WebUtil.GetFormValue("scSite");
                if (!string.IsNullOrEmpty(formValue))
                {
                    SiteContext siteContext = SiteContextFactory.GetSiteContext(formValue);
                    Assert.IsNotNull(siteContext, "siteContext");
                    using (new SiteContextSwitcher(siteContext))
                    {
                        return(fieldRenderer.RenderField());
                    }
                }

                return(fieldRenderer.RenderField());
            }
        }
コード例 #29
0
        private static Item AddDatasourceItem(GetRenderingDatasourceArgs args, Item datasourceFolder)
        {
            var datasourceTemplate     = args.RenderingItem["Datasource Template"];
            var datasourceTemplateItem = (TemplateItem)args.ContentDatabase.GetItem(datasourceTemplate);
            var count = datasourceFolder.Children.Count(c => c.TemplateID.Equals(datasourceTemplateItem.ID));

            using (new SecurityDisabler())
            {
                using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system")))
                {
                    using (new LanguageSwitcher(args.ContentLanguage))
                    {
                        return(datasourceFolder.Add(FormattableString.Invariant($"{datasourceTemplateItem.Name} {count + 1}"), datasourceTemplateItem));
                    }
                }
            }
        }
コード例 #30
0
ファイル: WorkflowSubmit.cs プロジェクト: trowpa/WeBlog
        public void Process(CreateCommentArgs args)
        {
            if (!string.IsNullOrEmpty(Settings.CommentWorkflowCommandCreated))
            {
                var workflow = args.Database.WorkflowProvider.GetWorkflow(args.CommentItem);

                if (workflow != null)
                {
                    //Need to switch to shell website to execute workflow
                    using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(Sitecore.Constants.ShellSiteName)))
                    {
                        workflow.Execute(Settings.CommentWorkflowCommandCreated, args.CommentItem, "WeBlog automated submit", false, new object[0]);
                    }
                    //workflow should take care of publishing the item following this, if it's configured to do so
                }
            }
        }