Example #1
0
        public void ProcessRequest(HttpContext context)
        {
            Guid pageId = Guid.Empty;

            if (context.Request["bid"] != null && Guid.TryParse(context.Request["bid"], out pageId))
            {
                bool   isGlobal    = Convert.ToBoolean(context.Request["IsGlobal"]);
                string cultureName = context.Request["cultureName"];
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = DataLocalizationFacade.DefaultLocalizationCulture.Name;
                }
                string cachedRssKey = string.Format(CacheRSSKeyTemplate, pageId, cultureName);
                if (context.Cache[cachedRssKey] == null)
                {
                    var cultureInfo = new CultureInfo(cultureName);
                    context.Response.ContentType = "text/xml";

                    using (var conn = new DataConnection(cultureInfo))
                    {
                        string pageUrl = BlogFacade.GetPageUrlById(pageId);
                        if (!string.IsNullOrEmpty(pageUrl))
                        {
                            pageUrl = BlogFacade.GetFullPath(pageUrl);
                            string pageTitle =
                                conn.Get <IPage>().Where(p => p.Id == pageId).Select(p => p.Title).Single();
                            var feed      = new SyndicationFeed(pageTitle, "", new Uri(pageUrl));
                            var blogItems =
                                conn.Get <Entries>()
                                .Where(b => isGlobal ? b.PageId != null : b.PageId == pageId)
                                .Select(b => new { b.Id, b.Title, b.TitleUrl, b.Date, b.Teaser, b.Tags, b.PageId })
                                .OrderByDescending(b => b.Date)
                                .ToList();

                            List <SyndicationItem> items = (from blog in blogItems
                                                            let blogUrl =
                                                                BlogFacade.GetBlogUrl(blog.Date, blog.TitleUrl, pageUrl)
                                                                select
                                                                new SyndicationItem(blog.Title, blog.Teaser,
                                                                                    new Uri(blogUrl), blog.Id.ToString(),
                                                                                    blog.Date)).ToList();

                            feed.Items = items;
                            context.Cache[cachedRssKey] = feed;
                        }
                    }
                }

                var syndicationFeed = (SyndicationFeed)context.Cache[cachedRssKey];

                using (XmlWriter writer = XmlWriter.Create(context.Response.OutputStream))
                {
                    syndicationFeed.SaveAsRss20(writer);
                }
            }
            else
            {
                context.Response.Write("The required query paramerer 'bid' (blog page GUID) is missing.");
            }
        }
        public PageUrlData GetPageUrlData(IDataReference instance)
        {
            if (!instance.IsSet || instance.ReferencedType != typeof(Entries))
            {
                return(null);
            }

            var entry = instance.Data as Entries;

            if (entry == null || entry.PageId == Guid.Empty)
            {
                return(null);
            }

            using (new DataScope(entry.DataSourceId.LocaleScope))
            {
                var page = PageManager.GetPageById(entry.PageId);
                if (page == null)
                {
                    return(null);
                }

                return(new PageUrlData(page)
                {
                    PathInfo = BlogFacade.GetBlogPath(entry)
                });
            }
        }
        public IDataReference GetData(PageUrlData pageUrlData)
        {
            string pathInfo = pageUrlData.PathInfo;

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

            string[] pathInfoParts = pathInfo.Split('/');
            if (pathInfoParts.Length != 5)
            {
                return(null);
            }

            var filter = BlogFacade.GetBlogFilter(pageUrlData.PageId, pathInfoParts);

            if (filter == null)
            {
                return(null);
            }

            var entry = DataFacade.GetData <Entries>().Where(filter).FirstOrDefault();

            return(entry != null?entry.ToDataReference() : null);
        }
Example #4
0
        public static List <BlogTagsByTypeModel> GetTagsByType(string entryTags)
        {
            var result = new List <BlogTagsByTypeModel>();

            using (var con = new DataConnection())
            {
                var types = con.Get <TagType>().ToList();
                foreach (var tagType in types)
                {
                    var tagsByType = con.Get <Tags>().Where(t => t.Type == tagType.Id).OrderBy(t => t.Position).Select(t => BlogFacade.Decode(t.Tag)).ToList();
                    var tags       = Enumerable.Intersect(entryTags.Split(','), tagsByType).ToList();
                    if (tags.Any())
                    {
                        result.Add(new BlogTagsByTypeModel()
                        {
                            TypeName = tagType.Name,
                            Tags     = string.Join(",", tags.ToArray())
                        });
                    }
                }
            }
            return(result);
        }
        public void Import(string rssPath, Guid pageId)
        {
            using (var conn = new DataConnection(PublicationScope.Unpublished))
            {
                var mapLinks = new Dictionary <string, string>();

                var       client = new WebClient();
                XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(rssPath));


                var feed = SyndicationFeed.Load(reader);
                reader.Close();

                var links         = feed.Links.Select(d => d.Uri.ToString()).ToList();
                var defaultAuthor = DataFacade.GetData <Authors>().Select(d => d.Name).TheOneOrDefault() ?? "Anonymous";
                var blogAuthor    = feed.Authors.Select(d => d.Name).FirstOrDefault()
                                    ?? feed.ElementExtensions.ReadElementExtensions <string>("creator", "http://purl.org/dc/elements/1.1/").FirstOrDefault();;


                foreach (var item in feed.Items)
                {
                    using (new DataScope(PublicationScope.Published))
                    {
                        var itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;
                        foreach (var itemLink in item.Links)
                        {
                            mapLinks[itemLink.Uri.OriginalString] = BlogFacade.BuildBlogInternalPageUrl(itemDate, item.Title.Text, pageId);
                        }
                    }
                }

                foreach (var item in feed.Items)
                {
                    try
                    {
                        var    content  = new XDocument();
                        string text     = null;
                        var    itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;



                        if (text == null && item.Content != null)
                        {
                            var syndicationContent = item.Content as TextSyndicationContent;
                            if (syndicationContent != null)
                            {
                                text = syndicationContent.Text;
                            }
                        }
                        if (text == null)
                        {
                            text = item.ElementExtensions.ReadElementExtensions <string>("encoded", "http://purl.org/rss/1.0/modules/content/")
                                   .FirstOrDefault();
                        }
                        if (text == null && item.Summary != null)
                        {
                            text = item.Summary.Text;
                        }

                        content = MarkupTransformationServices.TidyHtml(text).Output;

                        //somewhere empty <title></title> created
                        foreach (var title in content.Descendants(Namespaces.Xhtml + "title").ToList())
                        {
                            if (string.IsNullOrWhiteSpace(title.Value))
                            {
                                title.Remove();
                            }
                        }


                        foreach (var img in content.Descendants(Namespaces.Xhtml + "img"))
                        {
                            var src = img.GetAttributeValue("src");
                            if (!string.IsNullOrEmpty(src))
                            {
                                foreach (var link in links)
                                {
                                    if (src.StartsWith(link))
                                    {
                                        var newImage = ImportMedia(src, string.Format(FolderFormat, itemDate, item.Title.Text));
                                        if (newImage != null)
                                        {
                                            img.SetAttributeValue("src", MediaUrlHelper.GetUrl(newImage, true));
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        foreach (var a in content.Descendants(Namespaces.Xhtml + "a"))
                        {
                            var href = a.GetAttributeValue("href");
                            if (!string.IsNullOrEmpty(href))
                            {
                                foreach (var link in links)
                                {
                                    if (href.StartsWith(link))
                                    {
                                        if (mapLinks.ContainsKey(href))
                                        {
                                            a.SetAttributeValue("href", mapLinks[href]);
                                        }
                                        else
                                        {
                                            var extension = Path.GetExtension(href).ToLower();
                                            switch (extension)
                                            {
                                            case ".jpg":
                                            case ".png":
                                            case ".gif":
                                            case ".pdf":
                                            case ".doc":
                                            case ".docx":
                                                var newMedia = ImportMedia(href, string.Format(FolderFormat, itemDate, item.Title.Text));
                                                a.SetAttributeValue("href", MediaUrlHelper.GetUrl(newMedia, true));
                                                break;

                                            default:
                                                a.SetAttributeValue("href", new Uri(href).PathAndQuery);
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        var blogItem = DataFacade.BuildNew <Entries>();

                        var match = Regex.Match(item.Id, @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b", RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            var id = Guid.Empty;
                            Guid.TryParse(match.Groups[0].Value, out id);
                            if (id != Guid.Empty && !DataFacade.GetData <Entries>(d => d.Id == id).Any())
                            {
                                blogItem.Id = id;
                            }
                        }

                        blogItem.Title  = item.Title.Text;
                        blogItem.PageId = pageId;
                        blogItem.Teaser = string.Empty;

                        var blogItemAuthor = item.Authors.Select(d => d.Name ?? d.Email).FirstOrDefault() ??
                                             item.ElementExtensions.ReadElementExtensions <string>("creator",
                                                                                                   "http://purl.org/dc/elements/1.1/").FirstOrDefault();


                        blogItem.Author = ImportAuthor(blogItemAuthor ?? blogAuthor ?? defaultAuthor);

                        var tagType = DataFacade.GetData <TagType>().FirstOrDefault();
                        if (tagType == null)
                        {
                            tagType      = DataFacade.BuildNew <TagType>();
                            tagType.Name = "Categories";
                            DataFacade.AddNew(tagType);
                        }

                        foreach (var tag in item.Categories)
                        {
                            ImportTag(tag.Name, tagType.Id);
                        }
                        blogItem.Tags = string.Join(",", item.Categories.Select(d => d.Name));

                        blogItem.Content = content.ToString();
                        blogItem.Date    = itemDate;

                        blogItem.PublicationStatus = GenericPublishProcessController.Draft;
                        blogItem = DataFacade.AddNew(blogItem);
                        blogItem.PublicationStatus = GenericPublishProcessController.Published;
                        DataFacade.Update(blogItem);



                        //break;
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("Import Blog", ex);
                    }
                }

                //1st redirect
                var mapLinks2 = new Dictionary <string, string>();
                foreach (var maplink in mapLinks.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location]  = maplink.Value;
                                    mapLinks2[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }
                //2nd redirect
                foreach (var maplink in mapLinks2.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }


                var mapFile = PathUtil.Resolve(@"~\App_Data\RequestUrlRemappings.xml");
                var map     = new XElement("RequestUrlRemappings");
                if (File.Exists(mapFile))
                {
                    map = XElement.Load(mapFile);
                }

                map.Add(new XComment(" Imported Blog " + DateTime.Now));
                map.Add(
                    mapLinks.Select(d => new XElement("Remapping",
                                                      new XAttribute("requestPath", new Uri(d.Key).PathAndQuery),
                                                      new XAttribute("rewritePath", d.Value)
                                                      ))

                    );
                map.Add(new XComment(" "));

                map.Save(mapFile);
            }
        }