public override void Apply(T ruleContext) { if (!ID.IsID(DatasourceRootId)) { return; } var matchingRoot = ruleContext.Args.DatasourceRoots.FirstOrDefault(x => x.ID.ToString() == DatasourceRootId); if (matchingRoot != null) { Log.Debug(string.Format("Removing {0} from datasource roots for rendering {1} ({2}).", matchingRoot.DisplayName, ruleContext.Args.RenderingItem.DisplayName, ruleContext.Args.RenderingItem.ID), this); ruleContext.Args.DatasourceRoots.Remove(matchingRoot); if (!matchingRoot.HasChildren) { using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system") ?? new SiteContext(new SiteInfo(new StringDictionary())))) using (new EventDisabler()) matchingRoot.Delete(); } } }
public virtual IEnumerable <SiteUrl> GetUrlsForItem(Item item) { Assert.IsNotNull(item, "item != null"); var retVal = new List <SiteUrl>(); var validSites = Sitecore.Sites.SiteManager.GetSites().Where(s => Sites.Contains(s.Name.ToLower())); foreach (var site in validSites) { using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(site.Name))) { string url = ""; url = item.Paths.IsMediaItem ? GetMediaUrl(item) : GetItemUrl(item); retVal.Add(new SiteUrl { SiteName = site.Name, Url = url }); } } return(retVal); }
/// <inheritdoc /> /// <summary> /// Required by IHttpHandler, this is called by ASP.NET when an appropriate URL match is found. /// </summary> /// <param name="context">The current request context.</param> public void ProcessRequest(HttpContext context) { var builder = new StringBuilder(); builder.AppendLine("User-agent: *"); if (!RobotsTxtConfiguration.Current.Allowed) { builder.AppendLine("Disallow: /"); } else { var globalDisallows = RobotsTxtConfiguration.Current.GlobalDisallows; foreach (var disallow in globalDisallows) { builder.AppendLine($"Disallow: {disallow}"); } var site = SiteContextFactory.GetSiteContext(context.Request.Url.Host, context.Request.Url.LocalPath, context.Request.Url.Port); if (RobotsTxtConfiguration.Current.SiteDisallows.ContainsKey(site.Name)) { var disallows = RobotsTxtConfiguration.Current.SiteDisallows[site.Name]; foreach (var disallow in disallows) { builder.AppendLine($"Disallow: {disallow}"); } } builder.AppendLine(); builder.AppendLine("Sitemap: " + context.Request.Url.GetLeftPart(System.UriPartial.Authority) + "/sitemap.xml"); } context.Response.Clear(); context.Response.ContentType = "text"; context.Response.Write(builder.ToString()); context.Response.End(); }
protected virtual string GetRedirectUrl(Item redirectItem) { LinkField item = redirectItem.Fields[Templates.Redirect.Fields.RedirectUrl]; string str = null; if (item != null) { if (!item.IsInternal || item.TargetItem == null) { str = (!item.IsMediaLink || item.TargetItem == null ? item.Url : ((MediaItem)item.TargetItem).GetMediaUrl(null)); } else { SiteInfo siteInfo = Context.Site.SiteInfo; UrlOptions defaultOptions = UrlOptions.DefaultOptions; defaultOptions.Site = SiteContextFactory.GetSiteContext(siteInfo.Name); defaultOptions.AlwaysIncludeServerUrl = true; str = string.Concat(LinkManager.GetItemUrl(item.TargetItem, defaultOptions), (string.IsNullOrEmpty(item.QueryString) ? "" : string.Concat("?", item.QueryString))); } } return(str); }
public void Process(GetRenderingDatasourceArgs args) { Assert.IsNotNull(args, "args"); Sitecore.Data.Items.RenderingItem rendering = new Sitecore.Data.Items.RenderingItem(args.RenderingItem); UrlString urlString = new UrlString(rendering.Parameters); var contentFolder = urlString.Parameters[CONTENT_FOLDER_TEMPLATE_PARAM]; if (string.IsNullOrEmpty(contentFolder)) { return; } if (!ID.IsID(contentFolder)) { Log.Warn(string.Format("{0} for Rendering {1} contains improperly formatted ID: {2}", CONTENT_FOLDER_TEMPLATE_PARAM, args.RenderingItem.Name, contentFolder), this); return; } string text = args.RenderingItem["Datasource Location"]; if (!string.IsNullOrEmpty(text)) { if (text.StartsWith("./") && !string.IsNullOrEmpty(args.ContextItemPath)) { var itemPath = args.ContextItemPath + text.Remove(0, 1); var item = args.ContentDatabase.GetItem(itemPath); var contextItem = args.ContentDatabase.GetItem(args.ContextItemPath); if (item == null && contextItem != null) { string itemName = text.Remove(0, 2); //if we create an item in the current site context, the WebEditRibbonForm will see an ItemSaved event and think it needs to reload the page using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system"))) { contextItem.Add(itemName, new TemplateID(ID.Parse(contentFolder))); } } } } }
public void Process(CreateCommentArgs args) { Assert.IsNotNull(args.CommentItem, "Comment Item cannot be null"); if (!string.IsNullOrEmpty(_commentSettings.AkismetAPIKey) && !string.IsNullOrEmpty(_commentSettings.CommentWorkflowCommandSpam)) { var workflow = args.Database.WorkflowProvider.GetWorkflow(args.CommentItem); if (workflow != null) { var api = _akismetApi; if (api == null) { api = new Akismet(); } var version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; var blogItem = _blogManager.GetCurrentBlog(args.CommentItem); var url = _linkManager.GetAbsoluteItemUrl(blogItem); api.Init(_commentSettings.AkismetAPIKey, url, "WeBlog/" + version); 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(_commentSettings.CommentWorkflowCommandSpam, args.CommentItem, "Akismet classified this comment as spam", false, new object[0]); } args.AbortPipeline(); } } } }
public override JObject GetJsonForItem(Item item) { UrlOptions urlOptions = UrlOptions.DefaultOptions; urlOptions.AlwaysIncludeServerUrl = true; urlOptions.SiteResolving = true; urlOptions.Language = item.Language; urlOptions.Site = SiteContextFactory.GetSiteContext("website"); JObject j = new JObject(); j.Add("objectID", base.GetObjectId(item)); j.Add("url", LinkManager.GetItemUrl(item, urlOptions)); Dictionary <string, object> indexable = this.ItemParser.GetIndexable(item); foreach (var pair in indexable) { j.Add(pair.Key, JToken.FromObject(pair.Value)); } return(j); }
static string GetRedirectUrl(Item item) { var linkField = (LinkField)item.Fields[Templates.Redirect.Fields.RedirectUrl]; if (linkField != null) { if (linkField.IsInternal && linkField.TargetItem != null) { var siteInfo = linkField.TargetItem.GetSite(); var urlOptions = UrlOptions.DefaultOptions; urlOptions.Site = SiteContextFactory.GetSiteContext(siteInfo.Name); urlOptions.AlwaysIncludeServerUrl = true; return(LinkManager.GetItemUrl(linkField.TargetItem, urlOptions) + (string.IsNullOrEmpty(linkField.QueryString) ? string.Empty : $"?{linkField.QueryString}")); } else { return(linkField.Url); } } return(null); }
protected Item BuildNewDatasourceRoot(string datasourceFolderPath, TemplateItem template, Item contextItem, string folderDisplayNamePattern, TemplateItem datasourceTemplate) { NewDatasourceRoot = contextItem.Axes.SelectSingleItem(datasourceFolderPath); if (NewDatasourceRoot != null) { return(NewDatasourceRoot); } NewDatasourceRoot = BuildPath(contextItem, datasourceFolderPath, template); if (datasourceTemplate == null) { return(NewDatasourceRoot); } using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system") ?? new SiteContext(new SiteInfo(new StringDictionary())))) using (new EditContext(NewDatasourceRoot)) { NewDatasourceRoot.Appearance.DisplayName = string.Format(folderDisplayNamePattern, datasourceTemplate.DisplayName); NewDatasourceRoot.Appearance.Icon = datasourceTemplate.Icon; } return(NewDatasourceRoot); }
//protected override string UnsubscribeContact(ContactIdentifier contactIdentifier, Guid messageID) //{ // this.Logger.LogInfo("UnsubscribeContact started"); // SupportUnsubscribeMessage unsubscribeMessage = new SupportUnsubscribeMessage // { // AddToGlobalOptOutList = false, // ContactIdentifier = contactIdentifier, // MessageId = messageID, // MessageLanguage = LanguageName // }; // this.Logger.LogInfo($"UnsubscribeContact before call ClientApiService. Language {LanguageName}"); // base.ClientApiService.Unsubscribe(unsubscribeMessage); // this.Logger.LogInfo("UnsubscribeContact ended"); // return (ExmContext.Message.ManagerRoot.GetConfirmativePageUrl() ?? "/"); //} protected override string VerifyContactSubscriptions(ContactIdentifier contactIdentifier, Guid messageID) { this.Logger.LogInfo("VerifyContactSubscriptions started"); 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 = 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); } this.Logger.LogInfo("VerifyContactSubscriptions ended"); return(itemUrl); #endregion }
protected virtual Item BuildNewDatasourceRoot(string datasourceFolderPath, TemplateItem template, Item contextItem, string folderDisplayNamePattern, TemplateItem datasourceTemplate) { NewDatasourceRoot = contextItem.Axes.SelectSingleItem(datasourceFolderPath); if (NewDatasourceRoot != null) { return(NewDatasourceRoot); } NewDatasourceRoot = BuildPath(contextItem, datasourceFolderPath, template); if (datasourceTemplate == null) { return(NewDatasourceRoot); } using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("system") ?? new SiteContext(new SiteInfo(new StringDictionary())))) using (new EditContext(NewDatasourceRoot)) { var pluralizer = System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(CultureInfo.CurrentCulture); NewDatasourceRoot.Appearance.DisplayName = string.Format(folderDisplayNamePattern, pluralizer.Pluralize(datasourceTemplate.DisplayName)); NewDatasourceRoot.Appearance.Icon = datasourceTemplate.Icon; } return(NewDatasourceRoot); }
protected virtual void PasteProfileValues(MembershipUser updatedUser, SyncUser serializedUser, List <UserUpdate> changes) { foreach (var name in SiteContextFactory.GetSiteNames()) { var siteContext = SiteContextFactory.GetSiteContext(name); siteContext?.Caches.RegistryCache.RemoveKeysContaining(updatedUser.UserName); } var user = User.FromName(serializedUser.UserName, true); var propertiesAreUpdated = false; // load custom properties var knownCustomProperties = new HashSet <string>(); foreach (var customProperty in serializedUser.ProfileProperties.Where(property => property.IsCustomProperty)) { knownCustomProperties.Add(customProperty.Name); // check if we need to change the value var existingValue = user.Profile.GetCustomProperty(customProperty.Name); if (existingValue != null && existingValue.Equals((string)customProperty.Content, StringComparison.Ordinal)) { continue; } propertiesAreUpdated = true; user.Profile.SetCustomProperty(customProperty.Name, (string)customProperty.Content); changes.Add(new UserUpdate(customProperty.Name, existingValue, (string)customProperty.Content)); } // cull orphan custom properties foreach (var existingCustomProperty in user.Profile.GetCustomPropertyNames()) { if (!knownCustomProperties.Contains(existingCustomProperty)) { propertiesAreUpdated = true; changes.Add(new UserUpdate(existingCustomProperty, user.Profile.GetCustomProperty(existingCustomProperty), "Deleted", true)); user.Profile.RemoveCustomProperty(existingCustomProperty); } } // load standard properties foreach (var standardProperty in serializedUser.ProfileProperties.Where(property => !property.IsCustomProperty)) { // check if we need to change the value var existingValue = user.Profile.GetPropertyValue(standardProperty.Name); if (existingValue != null && (existingValue.GetType().IsPrimitive || existingValue is string)) { if (existingValue.Equals(standardProperty.Content)) { continue; // no changes, skip } propertiesAreUpdated = true; user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content); changes.Add(new UserUpdate(standardProperty.Name, existingValue.ToString(), standardProperty.Content.ToString())); } else { // a custom serialized type. No good way to compare as we don't know if it is at all comparable. // we'll go with a quiet always update here propertiesAreUpdated = true; user.Profile.SetPropertyValue(standardProperty.Name, standardProperty.Content); if (existingValue == null) { changes.Add(new UserUpdate(standardProperty.Name, "null", standardProperty.Content.ToString())); } } } // note: we cannot cull orphan standard properties because we cannot enumerate the keys if (propertiesAreUpdated) { user.Profile.Save(); CacheManager.GetUserProfileCache().RemoveUser(updatedUser.UserName); } }
private static void ProcessScript(HttpContext context, string script, Dictionary <string, Stream> streams, string cliXmlArgs = null, bool rawOutput = false, string sessionId = null, bool persistentSession = false) { if (string.IsNullOrEmpty(script)) { context.Response.StatusCode = 404; context.Response.StatusDescription = "The specified script is invalid."; return; } var session = ScriptSessionManager.GetSession(sessionId, ApplicationNames.RemoteAutomation, false); if (Context.Database != null) { var item = Context.Database.GetRootItem(); if (item != null) { session.SetItemLocationContext(item); } } context.Response.ContentType = "text/plain"; if (streams != null) { var scriptArguments = new Hashtable(); foreach (var param in context.Request.QueryString.AllKeys) { var paramValue = HttpContext.Current.Request.QueryString[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } scriptArguments[param] = paramValue; } foreach (var param in context.Request.Params.AllKeys) { var paramValue = context.Request.Params[param]; if (string.IsNullOrEmpty(param)) { continue; } if (string.IsNullOrEmpty(paramValue)) { continue; } if (session.GetVariable(param) == null) { session.SetVariable(param, paramValue); } } session.SetVariable("requestStreams", streams); session.SetVariable("scriptArguments", scriptArguments); session.ExecuteScriptPart(script, true); context.Response.Write(session.Output.ToString()); } else { // Duplicate the behaviors of the original RemoteAutomation service. var requestUri = WebUtil.GetRequestUri(); var site = SiteContextFactory.GetSiteContext(requestUri.Host, Context.Request.FilePath, requestUri.Port); Context.SetActiveSite(site.Name); if (!string.IsNullOrEmpty(cliXmlArgs)) { session.SetVariable("cliXmlArgs", cliXmlArgs); session.ExecuteScriptPart("$params = ConvertFrom-CliXml -InputObject $cliXmlArgs", false, true); script = script.TrimEnd(' ', '\t', '\n'); } var outObjects = session.ExecuteScriptPart(script, false, false, false) ?? new List <object>(); var response = context.Response; if (rawOutput) { // In this output we want to give raw output data. No type information is needed. Error streams are lost. if (outObjects.Any()) { foreach (var outObject in outObjects) { response.Write(outObject.ToString()); } } if (session.LastErrors != null && session.LastErrors.Any()) { var convertedObjects = new List <object>(); convertedObjects.AddRange(session.LastErrors); session.SetVariable("results", convertedObjects); session.Output.Clear(); session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results"); response.Write("<#messages#>"); foreach (var outputBuffer in session.Output) { response.Write(outputBuffer.Text); } } } else { // In this output we want to preserve type information. Ideal for objects with a small output content. if (session.LastErrors != null && session.LastErrors.Any()) { outObjects.AddRange(session.LastErrors); } if (outObjects.Any()) { session.SetVariable("results", outObjects); session.Output.Clear(); session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results"); foreach (var outputBuffer in session.Output) { response.Write(outputBuffer.Text); } } } } if (session.Output.HasErrors) { context.Response.StatusCode = 424; context.Response.StatusDescription = "Method Failure"; } if (string.IsNullOrEmpty(sessionId) || !persistentSession) { ScriptSessionManager.RemoveSession(session); } }
public void Process(CreateCommentArgs args) { Assert.ArgumentNotNull(args, "args cannot be null"); Assert.IsNotNull(args.Database, "Database cannot be null"); Assert.IsNotNull(args.Comment, "Comment cannot be null"); Assert.IsNotNull(args.EntryID, "Entry ID cannot be null"); Assert.IsNotNull(args.Language, "Language cannot be null"); var entryItem = args.Database.GetItem(args.EntryID, args.Language); if (entryItem != null) { var blogItem = BlogManager.GetCurrentBlog(entryItem); if (blogItem != null) { var template = args.Database.GetTemplate(blogItem.BlogSettings.CommentTemplateID); var itemName = ItemUtil.ProposeValidItemName(string.Format("Comment at {0} by {1}", GetDateTime().ToString("yyyyMMdd HHmmss"), args.Comment.AuthorName)); if (itemName.Length > 100) { itemName = itemName.Substring(0, 100); } // verify the comment item name is unique for this entry var query = BuildFastQuery(entryItem, itemName); var num = 1; var nondupItemName = itemName; while (entryItem.Database.SelectSingleItem(query) != null) { nondupItemName = itemName + " " + num; num++; query = BuildFastQuery(entryItem, nondupItemName); } // need to create the comment within the shell site to ensure workflow is applied to comment var shellSite = SiteContextFactory.GetSiteContext(Sitecore.Constants.ShellSiteName); SiteContextSwitcher siteSwitcher = null; try { if (shellSite != null) { siteSwitcher = new SiteContextSwitcher(shellSite); } using (new SecurityDisabler()) { var newItem = entryItem.Add(nondupItemName, template); var newComment = new CommentItem(newItem); newComment.BeginEdit(); newComment.Name.Field.Value = args.Comment.AuthorName; newComment.Email.Field.Value = args.Comment.AuthorEmail; newComment.Comment.Field.Value = args.Comment.Text; foreach (var entry in args.Comment.Fields) { newComment.InnerItem[entry.Key] = entry.Value; } newComment.EndEdit(); args.CommentItem = newComment; } } finally { siteSwitcher?.Dispose(); } } else { var message = "Failed to find blog for entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Logger.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } } else { var message = "Failed to find blog entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Logger.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } }
/// <summary> /// This method gets called from a scheduled task command. /// You define a scheduled task command by navigating to /// /System/Tasks/Commands and inserting a new command /// </summary> /// <param name="items">Items to publish</param> /// <param name="command">Command Info</param> /// <param name="schedule">Schedule Item</param> public void Run(Item[] items, Tasks.CommandItem command, Tasks.ScheduleItem schedule) { DateTime dtPublishDate = DateTime.UtcNow; using (new SecurityDisabler()) { try { Database master = Sitecore.Configuration.Factory.GetDatabase(Constants.MasterDatabaseName); Sitecore.Globalization.Language[] languages = master.Languages; // make sure workflows states are considered using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext("shell"))) { // for each existing target Item publishingTargetsFolder = master.GetItem(Constants.PublishingTargetsFolder); Sitecore.Collections.ChildList publishingTargets = publishingTargetsFolder.Children; foreach (Item publishingTarget in publishingTargets) { if (publishingTarget != null) { string targetDBName = publishingTarget[Constants.TargetDatabase]; if (string.IsNullOrEmpty(targetDBName) == false) { Database targetDb = Sitecore.Configuration.Factory.GetDatabase(targetDBName); if (targetDb != null) { // for each existing language foreach (Sitecore.Globalization.Language language in languages) { foreach (Item actItem in items) { ID itemToPublishId = actItem.ID; Item itemToPublish = master.GetItem(itemToPublishId, language); bool bPublish = false; Sitecore.Data.Fields.MultilistField targets = itemToPublish.Fields[Sitecore.FieldIDs.PublishingTargets]; if (targets != null) { Item[] itemToPublishTargets = targets.GetItems(); if (itemToPublishTargets.Length > 0) { foreach (Item itemToPublishTarget in itemToPublishTargets) { if (string.Equals(itemToPublishTarget.Name, publishingTarget.Name, StringComparison.CurrentCultureIgnoreCase) == true) { bPublish = true; break; } } } else { bPublish = true; } } else { bPublish = true; } if (bPublish == true) { try { string strMessage = string.Format(System.Globalization.CultureInfo.CurrentCulture, "Item '{0}' Target '{1}' Language '{2}': Automated Publisher Schedule Item '{3}'", itemToPublish.ID.ToString(), publishingTarget.Name, language.Name, schedule.Name); Log.Info(strMessage, this); } catch { Log.Error(Constants.ErrorFormattingString, this); } PublishOptions publishOptions = new PublishOptions(master, targetDb, PublishMode.Full, language, dtPublishDate); publishOptions.Deep = true; publishOptions.RootItem = itemToPublish; Publisher publisher = new Publisher(publishOptions); publisher.Publish(); } else { string strMessage = string.Format(System.Globalization.CultureInfo.CurrentCulture, "Item '{0}' Target '{1}' Language '{2}': No publishing targets were selected in Automated Publisher", itemToPublish.ID.ToString(), publishingTarget.Name, language.Name); Log.Error(strMessage, this); } } } } } } } } schedule.Remove(); } catch (Exception ex) { Log.Error("Error Publishing in Automated Publisher", ex, this); } } }
public void ProcessRequest(HttpContext context) { try { var urlRewriteProcessor = new InboundRewriteProcessor(); var requestArgs = new HttpRequestArgs(context, HttpRequestType.Begin); var requestUri = context.Request.Url; var siteContext = SiteContextFactory.GetSiteContext(requestUri.Host, requestUri.AbsolutePath, requestUri.Port); if (siteContext != null) { using (new SiteContextSwitcher(siteContext)) { urlRewriteProcessor.Process(requestArgs); } } } catch (ThreadAbortException) { // swallow this exception because we may have called Response.End } catch (HttpException) { // we want to throw http exceptions, but we don't care about logging them in Sitecore throw; } catch (Exception ex) { if (ex is HttpException || ex is ThreadAbortException) { return; } // log it in sitecore Log.Error(this, ex, "Error in UrlRewriteHandler."); // throw; // don't re-throw the error, but instead let it fall through } // if we have come this far, the url rewrite processor didn't match on anything so the request is passed to the static request handler // Serve static content: IHttpHandler staticFileHanlder = null; try { var systemWebAssemblyName = GetType() .Assembly.GetReferencedAssemblies() .First(assembly => assembly.FullName.StartsWith("System.Web, ")); var systemWeb = AppDomain.CurrentDomain.Load(systemWebAssemblyName); var staticFileHandlerType = systemWeb.GetType("System.Web.StaticFileHandler", true); staticFileHanlder = Activator.CreateInstance(staticFileHandlerType, true) as IHttpHandler; } catch (Exception) { } if (staticFileHanlder != null) { try { staticFileHanlder.ProcessRequest(context); } catch (HttpException httpException) { if (httpException.GetHttpCode() == 404) { HandleNotFound(context); } else { throw; } } } }
public override void Process(PublishItemContext context) { Database sourceDB = context.PublishOptions.SourceDatabase; Item item = context.PublishOptions.TargetDatabase.GetItem(context.ItemId); if (item == null) { return; } foreach (SiteInfo current in Settings.Sites) { if (!Config.IgnoredSites.Contains(current.Name, StringComparer.OrdinalIgnoreCase) && item.Paths.ContentPath.StartsWith(current.StartItem, StringComparison.OrdinalIgnoreCase)) { SiteContext siteContext = SiteContextFactory.GetSiteContext(current.Name); string homeItemPath = siteContext.StartPath.ToString(); Item startItem = sourceDB.GetItem(homeItemPath); ID homeItemID = startItem.ID; ID publishedItemID = item.ID; string text = ""; if (publishedItemID != homeItemID) { text = LinkManager.GetItemUrl(context.PublishOptions.TargetDatabase.GetItem(context.ItemId), GetItemUrlOptions(siteContext)); } else { text = LinkManager.GetItemUrl(context.PublishOptions.TargetDatabase.GetItem(context.ItemId), GetHomeUrlOptions(siteContext)); } if (text.StartsWith("://")) { text = "http" + text; } string localPath; try { Uri uri = new Uri(text); localPath = uri.LocalPath; } catch (UriFormatException innerException) { throw new ApplicationException(string.Format("Redirect Manager failed parsing item url generated by linkmanager. Url : {0} ItemId : {1}, ", text, context.ItemId), innerException); } if (!Redirector.Provider.Exists(localPath)) { Redirector.Provider.CreateRedirect(localPath, context.ItemId.ToString(), true); } else { Redirector.Provider.DeleteRedirect(localPath); Redirector.Provider.CreateRedirect(localPath, context.ItemId.ToString(), true); } } } }
public static DateRangeSearchParam GetSearchSettings(List <SearchStringModel> currentSearchString, string locationFilter) { var locationSearch = locationFilter; var refinements = new SafeDictionary <string>(); refinements = GetTagRefinements(currentSearchString); var author = SearchHelper.GetAuthor(currentSearchString); var languages = SearchHelper.GetLanguages(currentSearchString); if (languages.Length > 0) { refinements.Add("_language", languages); } var references = SearchHelper.GetReferences(currentSearchString); var custom = SearchHelper.GetCustom(currentSearchString); if (custom.Length > 0) { var customSearch = custom.Split('|'); if (customSearch.Length > 0) { try { refinements.Add(customSearch[0], customSearch[1]); } catch (Exception exc) { Log.Error("Could not parse the custom search query", exc); } } } var search = SearchHelper.GetField(currentSearchString); if (search.Length > 0) { var customSearch = search; refinements.Add(customSearch, SearchHelper.GetText(currentSearchString)); } var fileTypes = SearchHelper.GetFileTypes(currentSearchString); if (fileTypes.Length > 0) { refinements.Add("extension", SearchHelper.GetFileTypes(currentSearchString)); } var s = SearchHelper.GetSite(currentSearchString); if (s.Length > 0) { SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name); var db = Context.ContentDatabase ?? Context.Database; var startItemId = db.GetItem(siteContext.StartPath); locationSearch = startItemId.ID.ToString(); } var location = SearchHelper.GetLocation(currentSearchString, locationSearch); var rangeSearch = new DateRangeSearchParam { ID = SearchHelper.GetID(currentSearchString).IsEmpty() ? SearchHelper.GetRecent(currentSearchString) : SearchHelper.GetID(currentSearchString), ShowAllVersions = false, FullTextQuery = SearchHelper.GetText(currentSearchString), Refinements = refinements, RelatedIds = references.Any() ? references : string.Empty, TemplateIds = SearchHelper.GetTemplates(currentSearchString), LocationIds = location, Language = languages, Author = author == string.Empty ? string.Empty : author, ItemName = SearchHelper.GetItemName(currentSearchString), Ranges = GetDateRefinements(SearchHelper.GetStartDate(currentSearchString), SearchHelper.GetEndDate(currentSearchString)) }; return(rangeSearch); }
/// <inheritdoc /> /// <summary> /// Required by IHttpHandler, this is called by ASP.NET when an appropriate URL match is found. /// </summary> /// <param name="context">The current request context.</param> public void ProcessRequest(HttpContext context) { var site = SiteContextFactory.GetSiteContext(context.Request.Url.Host, context.Request.Url.LocalPath, context.Request.Url.Port); var builder = new StringBuilder(); builder.AppendLine("User-agent: *"); var globalRules = RobotsTxtConfiguration.Current.GlobalRules; var defaultRules = RobotsTxtConfiguration.Current.DefaultRules; var siteRules = defaultRules; // in case the site does not have its own custom rules. if (RobotsTxtConfiguration.Current.SiteRules.ContainsKey(site.Name)) { siteRules = RobotsTxtConfiguration.Current.SiteRules[site.Name]; // load the site's custom rules. } var includeSitemap = true; foreach (var rule in globalRules) { switch (rule.Permission) { case RobotsTxtRule.RulePermission.Allow: builder.AppendLine($"Allow: {rule.Path}"); break; case RobotsTxtRule.RulePermission.Deny: builder.AppendLine($"Disallow: {rule.Path}"); if (rule.Path.Equals("/", StringComparison.InvariantCultureIgnoreCase)) { includeSitemap = false; } break; } } foreach (var rule in siteRules) { switch (rule.Permission) { case RobotsTxtRule.RulePermission.Allow: builder.AppendLine($"Allow: {rule.Path}"); break; case RobotsTxtRule.RulePermission.Deny: builder.AppendLine($"Disallow: {rule.Path}"); if (rule.Path.Equals("/", StringComparison.InvariantCultureIgnoreCase)) { includeSitemap = false; } break; } } if (includeSitemap) { builder.AppendLine(); builder.AppendLine($"Sitemap: {context.Request.Url.GetLeftPart(System.UriPartial.Authority)}/sitemap.xml"); } context.Response.Clear(); context.Response.ContentType = "text"; context.Response.Write(builder.ToString()); context.Response.End(); }
public void Process(CreateCommentArgs args) { Assert.IsNotNull(args.Database, "Database cannot be null"); Assert.IsNotNull(args.Comment, "Comment cannot be null"); Assert.IsNotNull(args.EntryID, "Entry ID cannot be null"); var entryItem = args.Database.GetItem(args.EntryID, args.Language); if (entryItem != null) { var blogItem = ManagerFactory.BlogManagerInstance.GetCurrentBlog(entryItem); if (blogItem != null) { var template = args.Database.GetTemplate(blogItem.BlogSettings.CommentTemplateID); var itemName = ItemUtil.ProposeValidItemName(string.Format("Comment at {0} by {1}", DateTime.Now.ToString("yyyyMMdd HHmmss"), args.Comment.AuthorName)); // verify the comment item name is unique for this entry var query = "{0}//{1}".FormatWith(entryItem.Paths.FullPath, itemName); #if !SC62 query = "fast:" + query; #endif var num = 1; var nondupItemName = itemName; while (entryItem.Database.SelectSingleItem(query) != null) { nondupItemName = itemName + " " + num; num++; query = "fast:{0}//{1}".FormatWith(entryItem.Paths.FullPath, nondupItemName); } //need to emulate creation within shell site to ensure workflow is applied to comment using (new SiteContextSwitcher(SiteContextFactory.GetSiteContext(Sitecore.Constants.ShellSiteName))) { using (new SecurityDisabler()) { var newItem = entryItem.Add(nondupItemName, template); var newComment = new CommentItem(newItem); newComment.BeginEdit(); newComment.Name.Field.Value = args.Comment.AuthorName; newComment.Email.Field.Value = args.Comment.AuthorEmail; newComment.Comment.Field.Value = args.Comment.Text; foreach (var entry in args.Comment.Fields) { newComment.InnerItem[entry.Key] = entry.Value; } newComment.EndEdit(); args.CommentItem = newComment; } } } else { var message = "Failed to find blog for entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Log.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } } else { var message = "Failed to find blog entry {0}\r\nIgnoring comment: name='{1}', email='{2}', commentText='{3}'"; Log.Error(string.Format(message, args.EntryID, args.Comment.AuthorName, args.Comment.AuthorEmail, args.Comment.Text), typeof(CreateCommentItem)); } }
public static DateRangeSearchParam GetBaseQuery(List <SearchStringModel> _searchQuery, string locationFilter) { var startDate = DateTime.Now; var endDate = DateTime.Now.AddDays(1); var locationSearch = locationFilter; var refinements = new SafeDictionary <string>(); var searchStringModels = GetTags(_searchQuery); if (searchStringModels.Count > 0) { foreach (var ss in searchStringModels) { var query = ss.Value; if (query.Contains("tagid=")) { query = query.Split('|')[1].Replace("tagid=", string.Empty); } var db = Context.ContentDatabase ?? Context.Database; refinements.Add("_tags", db.GetItem(query).ID.ToString()); } } var author = GetAuthor(_searchQuery); var languages = GetLanguages(_searchQuery); if (languages.Length > 0) { refinements.Add("_language", languages); } var references = GetReferences(_searchQuery); var custom = GetCustom(_searchQuery); if (custom.Length > 0) { var customSearch = custom.Split('|'); if (customSearch.Length > 0) { try { refinements.Add(customSearch[0], customSearch[1]); } catch (Exception exc) { Log.Error("Could not parse the custom search query", exc); } } } var search = GetField(_searchQuery); if (search.Length > 0) { var customSearch = search; refinements.Add(customSearch, GetText(_searchQuery)); } var fileTypes = GetFileTypes(_searchQuery); if (fileTypes.Length > 0) { refinements.Add("extension", GetFileTypes(_searchQuery)); } var s = GetSite(_searchQuery); if (s.Length > 0) { var siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name); var db = Context.ContentDatabase ?? Context.Database; var startItemId = db.GetItem(siteContext.StartPath); locationSearch = startItemId.ID.ToString(); } var culture = CultureInfo.CreateSpecificCulture("en-US"); var startFlag = true; var endFlag = true; if (GetStartDate(_searchQuery).Any()) { if (!DateTime.TryParse(GetStartDate(_searchQuery), culture, DateTimeStyles.None, out startDate)) { startDate = DateTime.Now; } startFlag = false; } if (GetEndDate(_searchQuery).Any()) { if (!DateTime.TryParse(GetEndDate(_searchQuery), culture, DateTimeStyles.None, out endDate)) { endDate = DateTime.Now.AddDays(1); } endFlag = false; } var returnResult = new DateRangeSearchParam { ID = GetID(_searchQuery), ShowAllVersions = false, FullTextQuery = GetText(_searchQuery), Refinements = refinements, RelatedIds = references.Any() ? references : string.Empty, TemplateIds = GetTemplates(_searchQuery), LocationIds = GetLocation(_searchQuery, locationFilter), Language = languages, IsFacet = true, Author = author == string.Empty ? string.Empty : author, }; if (!startFlag || !endFlag) { returnResult.Ranges = new List <DateRangeSearchParam.DateRangeField> { new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate) { InclusiveStart = true, InclusiveEnd = true } }; } return(returnResult); }
/// <summary> /// Using a strongly types List of SearchStringModel, you can run a search based off a JSON String /// </summary> /// <param name="itm"> /// The itm. /// </param> /// <param name="currentSearchString"> /// The current Search String. /// </param> /// <param name="hitCount"> /// The hit Count. /// </param> /// <param name="indexName"> /// The index Name. /// </param> /// <param name="sortField"> /// The sort Field. /// </param> /// <param name="sortDirection"> /// The sort Direction. /// </param> /// <param name="pageSize"> /// The page Size. /// </param> /// <param name="pageNumber"> /// The page Number. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <returns> /// IEnumreable List of Results that have been typed to a smaller version of the Item Object /// </returns> public static IEnumerable <SitecoreItem> FullSearch(this Item itm, List <SearchStringModel> currentSearchString, out int hitCount, string indexName = "itembuckets_buckets", string sortField = "", string sortDirection = "", int pageSize = 0, int pageNumber = 0, object[] parameters = null) { var startDate = DateTime.Now; var endDate = DateTime.Now.AddDays(1); var locationSearch = LocationFilter; var refinements = new SafeDictionary <string>(); var searchStringModels = SearchHelper.GetTags(currentSearchString); if (searchStringModels.Count > 0) { foreach (var ss in searchStringModels) { var query = ss.Value; if (query.Contains("tagid=")) { query = query.Split('|')[1].Replace("tagid=", string.Empty); } var db = Context.ContentDatabase ?? Context.Database; refinements.Add("_tags", db.GetItem(query).ID.ToString()); } } var author = SearchHelper.GetAuthor(currentSearchString); var languages = SearchHelper.GetLanguages(currentSearchString); if (languages.Length > 0) { refinements.Add("_language", languages); } var references = SearchHelper.GetReferences(currentSearchString); var custom = SearchHelper.GetCustom(currentSearchString); if (custom.Length > 0) { var customSearch = custom.Split('|'); if (customSearch.Length > 0) { try { refinements.Add(customSearch[0], customSearch[1]); } catch (Exception exc) { Log.Error("Could not parse the custom search query", exc); } } } var search = SearchHelper.GetField(currentSearchString); if (search.Length > 0) { var customSearch = search; refinements.Add(customSearch, SearchHelper.GetText(currentSearchString)); } var fileTypes = SearchHelper.GetFileTypes(currentSearchString); if (fileTypes.Length > 0) { refinements.Add("extension", SearchHelper.GetFileTypes(currentSearchString)); } var s = SearchHelper.GetSite(currentSearchString); if (s.Length > 0) { SiteContext siteContext = SiteContextFactory.GetSiteContext(SiteManager.GetSite(s).Name); var db = Context.ContentDatabase ?? Context.Database; var startItemId = db.GetItem(siteContext.StartPath); locationSearch = startItemId.ID.ToString(); } var culture = CultureInfo.CreateSpecificCulture("en-US"); var startFlag = true; var endFlag = true; if (SearchHelper.GetStartDate(currentSearchString).Any()) { if (!DateTime.TryParse(SearchHelper.GetStartDate(currentSearchString), culture, DateTimeStyles.None, out startDate)) { startDate = DateTime.Now; } startFlag = false; } if (SearchHelper.GetEndDate(currentSearchString).Any()) { if (!DateTime.TryParse(SearchHelper.GetEndDate(currentSearchString), culture, DateTimeStyles.None, out endDate)) { endDate = DateTime.Now.AddDays(1); } endFlag = false; } using (var searcher = new IndexSearcher(indexName)) { var location = SearchHelper.GetLocation(currentSearchString, locationSearch); var locationIdFromItem = itm != null?itm.ID.ToString() : string.Empty; var rangeSearch = new DateRangeSearchParam { ID = SearchHelper.GetID(currentSearchString).IsEmpty() ? SearchHelper.GetRecent(currentSearchString) : SearchHelper.GetID(currentSearchString), ShowAllVersions = false, FullTextQuery = SearchHelper.GetText(currentSearchString), Refinements = refinements, RelatedIds = references.Any() ? references : string.Empty, SortDirection = sortDirection, TemplateIds = SearchHelper.GetTemplates(currentSearchString), LocationIds = location == string.Empty ? locationIdFromItem : location, Language = languages, SortByField = sortField, PageNumber = pageNumber, PageSize = pageSize, Author = author == string.Empty ? string.Empty : author, }; if (!startFlag || !endFlag) { rangeSearch.Ranges = new List <DateRangeSearchParam.DateRangeField> { new DateRangeSearchParam.DateRangeField(SearchFieldIDs.CreatedDate, startDate, endDate) { InclusiveStart = true, InclusiveEnd = true } }; } var returnResult = searcher.GetItems(rangeSearch); hitCount = returnResult.Key; return(returnResult.Value); } }
public virtual SiteContext GetSiteContext([NotNull] string name) { return(SiteContextFactory.GetSiteContext(name)); }