Exemplo n.º 1
0
        private static XmlDocument GetRequest(Uri url, BlogConfigurationDto configuration)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(ms, Encoding.ASCII))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("methodCall");
                    writer.WriteElementString("methodName", "weblogUpdates.ping");
                    writer.WriteStartElement("params");
                    writer.WriteStartElement("param");
                    writer.WriteElementString("value", configuration.Name);
                    writer.WriteEndElement();
                    writer.WriteStartElement("param");
                    writer.WriteElementString("value", url.ToString());
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(ms);

                return(xmlDocument);
            }
        }
        public void Execute(IJobExecutionContext context)
        {
            this.logger.Debug("EmailNotificationJob executing.");

            IEnumerable <EmailMessageDto> emails = this.emailNotificationDataService.Peek(5);

            BlogConfigurationDto configuration = this.configurationDataService.GetConfiguration();

            foreach (EmailMessageDto email in emails)
            {
                try
                {
                    using (SmtpClient smtp = new SmtpClient(configuration.SmtpConfiguration.SmtpHost, configuration.SmtpConfiguration.Port))
                    {
                        smtp.EnableSsl   = configuration.SmtpConfiguration.UseSSL;
                        smtp.Credentials = new NetworkCredential(configuration.SmtpConfiguration.Username, configuration.SmtpConfiguration.Password);

                        using (MailMessage msg = email.ToMailMessage())
                        {
                            smtp.Send(msg);
                            this.logger.DebugFormat("Email sent! - Subject: {0} - To {1}", email.Subject, email.MailTo);
                        }

                        this.emailNotificationDataService.Dequeue(email);
                    }
                }
                catch (Exception e)
                {
                    this.logger.Error("Error occurred during sending the message.", e);
                    this.emailNotificationDataService.Queue(email);
                }
            }

            this.logger.Debug("EmailNotificationJob executed.");
        }
        private void BuildSyndicationFeed(object models, Stream stream, string contenttype)
        {
            List <PostDto> urls = new List <PostDto>();

            if (models is IEnumerable <ItemDto> )
            {
                urls.AddRange((IEnumerable <PostDto>)models);
            }
            else
            {
                urls.Add((PostDto)models);
            }

            BlogConfigurationDto config = DexterContainer.Resolve <IConfigurationService>().GetConfiguration();

            //Main info
            SyndicationFeed feed = new SyndicationFeed
            {
                Title       = new TextSyndicationContent(config.Name),
                Description = new TextSyndicationContent(config.SeoConfiguration.DefaultDescription ?? config.Name),
                Copyright   = new TextSyndicationContent(String.Format("{0} (c) {1}", config.SeoConfiguration.CopyRight, DateTime.Now.Year))
            };

            //Adding link
            feed.Links.Add(new SyndicationLink(this.UrlBuilder.Home));

            //Adding categoris
            config.SeoConfiguration.DefaultKeyWords.ForEach(keyword => feed.Categories.Add(new SyndicationCategory(keyword)));

            if (urls.Any())
            {
                feed.LastUpdatedTime = urls.OrderByDescending(model => model.PublishAt).First().PublishAt;

                //Adding authors
                urls.GroupBy(x => x.Author).Select(x => x.Key)
                .ForEach(author => feed.Authors.Add(new SyndicationPerson(null, author, this.UrlBuilder.Home)));
            }

            //Adding items
            List <SyndicationItem> items = new List <SyndicationItem>();

            urls.ForEach(item => items.Add(this.BuildSyndicationItem(item)));

            feed.Items = items;

            using (XmlWriter writer = XmlWriter.Create(stream))
            {
                if (string.Equals(contenttype, Atom))
                {
                    Atom10FeedFormatter atomformatter = new Atom10FeedFormatter(feed);
                    atomformatter.WriteTo(writer);
                }
                else
                {
                    Rss20FeedFormatter rssformatter = new Rss20FeedFormatter(feed);
                    rssformatter.WriteTo(writer);
                }
            }
        }
Exemplo n.º 4
0
        public void CreateSetupConfiguration(BlogConfigurationDto configurationDto)
        {
            if (this.GetConfiguration() != null)
            {
                throw new SecurityException("This method could be called only during the setup procedure");
            }

            this.SaveConfiguration(configurationDto);
        }
Exemplo n.º 5
0
        public BlogConfigurationDto GetConfiguration()
        {
            BlogConfigurationDto configuration = this.Session.Load <BlogConfigurationDto>(1);

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

            return(configuration);
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Trackback(int id, string title, string excerpt, string blog_name, string url, ItemType itemType = ItemType.Post)
        {
            if (!this.BlogConfiguration.Tracking.EnableTrackBackReceive)
            {
                this.Logger.Debug("Trackback Receive is disabled, returning 404.");
                throw new HttpException(404, "Page not found");
            }

            BlogConfigurationDto configuration = this.configurationService.GetConfiguration();

            if (!configuration.Tracking.EnableTrackBackReceive)
            {
                return(this.HttpNotFound());
            }

            if (url != null)
            {
                url = url.Split(',')[0];
            }

            if (url == null)
            {
                return(this.HttpNotFound());
            }

            TrackBackDto trackBackDto = new TrackBackDto
            {
                Url     = new Uri(url),
                Title   = title,
                Excerpt = excerpt
            };

            try
            {
                await this.trackbackService.SaveOrUpdateAsync(trackBackDto, itemType);

                this.HttpContext.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>");
                this.HttpContext.Response.End();
            }
            catch (DuplicateTrackbackException)
            {
                this.HttpContext.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>Trackback already registered</error></response>");
                this.HttpContext.Response.End();
            }
            catch (SpamException)
            {
                this.HttpContext.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>The source page does not contain the link</error></response>");
                this.HttpContext.Response.End();
            }

            return(new EmptyResult());
        }
Exemplo n.º 7
0
        public BlogConfigurationDto GetConfiguration()
        {
            BlogConfigurationDto result = this.cacheProvider.Get <BlogConfigurationDto>("dexter.blog.configurationDto");

            if (result == null)
            {
                result = this.configurationDataService.GetConfiguration();

                this.cacheProvider.Put("dexter.blog.configurationDto", result, TimeSpan.FromHours(3));
            }

            return(result);
        }
Exemplo n.º 8
0
        public static async Task NotifySites()
        {
            BlogConfigurationDto configuration = configurationDataService.GetConfiguration();
            IEnumerable <Uri>    pingSites     = pingDataService.GetPingSites();

            foreach (Uri pingSite in pingSites)
            {
                using (HttpClient client = new HttpClient())
                {
                    await client.PostAsXmlAsync(pingSite.ToString(), GetRequest(pingSite, configuration));
                }
            }
        }
        public BlogInfo[] GetUsersBlogs(string key, string username, string password)
        {
            this.ValidateUser(username, password);

            BlogConfigurationDto conf = this.configurationService.GetConfiguration();

            BlogInfo blogInfo = new BlogInfo
            {
                blogid   = "nothing",
                blogName = conf.Name,
                url      = this.urlBuilder.Home,
            };

            return(new[] { blogInfo });
        }
Exemplo n.º 10
0
        public void AddComment(CommentDto item, int itemId)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item", "The comment item must contain a valid instance.");
            }

            if (itemId < 1)
            {
                throw new ArgumentException("The item id must be greater than 0", "itemId");
            }

            BlogConfigurationDto configuration = this.configurationService.GetConfiguration();

            CommentStatus status = configuration.CommentSettings.EnablePremoderation ? CommentStatus.Pending : CommentStatus.IsApproved;

            this.commentDataService.AddComment(item, itemId, status);
        }
Exemplo n.º 11
0
        public static async Task <bool> Notify(ItemDto item, Uri uri)
        {
            BlogConfigurationDto configuration = configurationService.GetConfiguration();

            using (HttpClient client = new HttpClient())
            {
                string content = await client.GetStringAsync(uri);

                Uri trackbackUrl = GetTrackBackUrlFromPage(content);

                if (trackbackUrl != null)
                {
                    SiteUrl itemUrl = item is PostDto
                                                                  ? urlBuilder.Post.Permalink(item)
                                                                  : urlBuilder.Page.Permalink(item);

                    Dictionary <string, string> form = new Dictionary <string, string>
                    {
                        { "title", item.Title },
                        { "url", itemUrl.ToString() },
                        { "excerpt", item.Excerpt },
                        { "blog_name", configuration.Name }
                    };

                    try
                    {
                        await client.PostAsync(trackbackUrl.ToString(), new FormUrlEncodedContent(form));

                        return(true);
                    }
                    catch (Exception ex)
                    {
                        logger.WarnFormat("Unable to send trackback to '{0}'", ex, uri);
                    }

                    return(false);
                }

                return(false);
            }
        }
Exemplo n.º 12
0
        public static MvcHtmlString TrackBackRdf(this HtmlHelper helper, PostDto item)
        {
            IUrlBuilder          u = DexterContainer.Resolve <IUrlBuilder>();
            BlogConfigurationDto c = DexterContainer.Resolve <IConfigurationService>().GetConfiguration();

            if (!c.Tracking.EnableTrackBackReceive)
            {
                return(MvcHtmlString.Empty);
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<!--");
            sb.Append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">");
            sb.AppendLine();
            sb.AppendFormat("<rdf:Description rdf:about=\"{0}\" dc:identifier=\"{0}\" dc:title=\"{1}\" trackback:ping=\"{2}\" />", u.Post.Permalink(item), item.Title, u.Post.TrackBack(item));
            sb.AppendLine("</rdf:RDF>");
            sb.AppendLine("-->");

            return(MvcHtmlString.Create(sb.ToString()));
        }
Exemplo n.º 13
0
        public async Task InitializeAsync(Setup item)
        {
            string defaultPostPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data/Setup/defaultPost.dxt");

            var defaultPostTask = this.GetDefaultPostContent(defaultPostPath, item.SiteDomain.Host);
            var membershipTask  = this.CreateMembershipAndRole(item);

            BlogConfigurationDto configuration = new BlogConfigurationDto(item.BlogName, item.SiteDomain);

            configuration.TimeZone = TimeZoneInfo.FindSystemTimeZoneById("UTC");

            this.configurationDataService.CreateSetupConfiguration(configuration);
            this.logger.Debug("Created blog configuration.");

            //Creating default category
            this.categoryService.SaveOrUpdate(new CategoryDto
            {
                Name      = "Various",
                IsDefault = true
            });

            this.logger.Debug("Created default category.");

            PostDto defaultPost = new PostDto();

            defaultPost.Title         = "Welcome to Dexter!";
            defaultPost.Tags          = new[] { "Dexter" };
            defaultPost.Categories    = new[] { "Various" };
            defaultPost.Status        = ItemStatus.Published;
            defaultPost.PublishAt     = DateTimeOffset.Now.AsMinutes();
            defaultPost.Author        = item.AdminUsername;
            defaultPost.AllowComments = true;

            await Task.WhenAll(defaultPostTask, membershipTask);

            defaultPost.Content = defaultPostTask.Result;

            this.postDataService.SaveOrUpdate(defaultPost);
            this.logger.Debug("Created default post.");
        }
Exemplo n.º 14
0
        public ActionResult Configuration(BlogConfigurationBinder blogConfiguration)
        {
            if (!ModelState.IsValid)
            {
                BlogConfigurationViewModel model = new BlogConfigurationViewModel();
                model.TimesZones        = TimeZoneInfo.GetSystemTimeZones();
                model.BlogConfiguration = blogConfiguration;
            }

            try
            {
                BlogConfigurationDto currentConfiguration = this.BlogConfiguration;
                BlogConfigurationDto configuration        = this.BlogConfiguration.MapPropertiesToInstance <BlogConfigurationDto>(currentConfiguration);

                this.ConfigurationService.SaveOrUpdateConfiguration(configuration);

                return(this.urlBuilder.Admin.FeedbackPage(FeedbackType.Positive, "Configuration Saved", this.urlBuilder.Admin.EditSeoConfiguration()).Redirect());
            }
            catch (DexterException e)
            {
                this.Logger.ErrorFormat("Unable to save the specified category", e);
                return(this.urlBuilder.Admin.FeedbackPage(FeedbackType.Negative, "Configuration Not Saved", this.urlBuilder.Admin.EditSeoConfiguration()).Redirect());
            }
        }
Exemplo n.º 15
0
 public void SaveConfiguration(BlogConfigurationDto configurationDto)
 {
     this.Session.Store(configurationDto);
 }
        private string ProcessPostData(string blogId, string username, string password, Post post, int?postId)
        {
            string title = HttpUtility.HtmlDecode(post.title);
            string body  = post.description;

            PostDto newPost = !postId.HasValue || postId.Value < 1
                                                  ? new PostDto()
                                                  : this.postService.GetPostByKey(postId.Value);

            newPost.Title   = title;
            newPost.Slug    = post.wp_slug;
            newPost.Content = body;

            if (!string.IsNullOrEmpty(post.mt_excerpt))
            {
                newPost.Excerpt = post.mt_excerpt;
            }
            else
            {
                newPost.Excerpt = (!string.IsNullOrEmpty(post.description))
                                                          ? post.description.CleanHtmlText().Trim().Replace("&nbsp;", string.Empty).Cut(250)
                                                          : string.Empty;
            }
            if (newPost.IsTransient)
            {
                newPost.PublishAt = (post.dateCreated == DateTime.MinValue || post.dateCreated == DateTime.MaxValue)
                                                            ? DateTimeOffset.Now
                                                            : new DateTime(post.dateCreated.Ticks, DateTimeKind.Utc);
            }
            else
            {
                newPost.PublishAt = (post.dateCreated == DateTime.MinValue || post.dateCreated == DateTime.MaxValue)
                                                            ? newPost.PublishAt
                                                            : new DateTime(post.dateCreated.Ticks, DateTimeKind.Utc);
            }

            BlogConfigurationDto blogConfiguration = this.configurationService.GetConfiguration();

            newPost.Status = newPost.PublishAt.UtcDateTime <= TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), blogConfiguration.TimeZone)
                                                 ? ItemStatus.Published
                                                 : ItemStatus.Scheduled;

            if (post.categories != null)
            {
                IList <string> categories      = post.categories.ToList();
                IList <string> categoriesToAdd = new List <string>();

                IList <CategoryDto> allCategories = this.categoryService.GetCategories();

                foreach (string c in categories)
                {
                    CategoryDto cat = allCategories.FirstOrDefault(x => x.Name == c);
                    if (cat != null)
                    {
                        categoriesToAdd.Add(cat.Name);
                    }
                }

                newPost.Categories = categoriesToAdd.ToArray();
            }

            IEnumerable <string> tags = this.ExtractTags(post);

            if (tags != null && tags.Any())
            {
                newPost.Tags = tags.ToArray();
            }

            this.ConvertAllowCommentsForItem(post.mt_allow_comments, newPost);

            // set the author if specified, otherwise use the user that is authenticated by wlw
            // once a post is done, only the 'poster' can modify it
            if (!string.IsNullOrEmpty(post.wp_author_id))
            {
                // get the list of members
                WpAuthor[] authors  = this.WpGetAuthors(blogId, username, password);
                int        authorId = Convert.ToInt32(post.wp_author_id);
                string     author   = authors.First(a => a.user_id == authorId).user_login;
                newPost.Author = author;
            }
            else if (!string.IsNullOrEmpty(post.userid))
            {
                // get the list of members
                WpAuthor[] authors  = this.WpGetAuthors(blogId, username, password);
                int        authorId = Convert.ToInt32(post.userid);
                string     author   = authors.First(a => a.user_id == authorId).user_login;
                newPost.Author = author;
            }
            else
            {
                newPost.Author = username;
            }

            this.postService.SaveOrUpdate(newPost);

            return(newPost.Id.ToString(CultureInfo.InvariantCulture));
        }
Exemplo n.º 17
0
 public PublishedBackgroundTask(ItemDto item, IConfigurationDataService configurationDataService)
 {
     this.configuration = configurationDataService.GetConfiguration();
     this.item          = item;
 }
Exemplo n.º 18
0
 public void SaveOrUpdateConfiguration(BlogConfigurationDto item)
 {
     this.configurationDataService.SaveConfiguration(item);
 }
Exemplo n.º 19
0
        public SiteUrl PingbackUrl()
        {
            BlogConfigurationDto conf = this.Configuration;

            return(new SiteUrl(this.Domain, this.HttpPort, false, this.Home.Area, "Services", "Pingback", null, null));
        }