Пример #1
0
		public override void ProcessItemTemplate(Entry item, Control ContentPlaceHolder)
		{
			base.ProcessItemTemplate(item, ContentPlaceHolder);

			// add the trackback and pingback information
			string metaData = "";

			if (!this.IsAggregatedView)
			{
				if (this.SiteConfig.EnablePingbackService)
				{
					metaData = string.Format("<link ref=\"pingback\" href=\"{0}\">\n", new Uri(new Uri(this.SiteConfig.Root), "pingback.aspx"));
				}

				if (this.SiteConfig.EnableTrackbackService)
				{
					// we need to ensure that the URL we use in the identifier
					// is the same one used by the remote server or they will
					// not post a trackback since dasBlog supports many url
					// formats.
					string link = Request.Url.GetLeftPart(UriPartial.Authority) + Request.RawUrl.ToString();

					metaData += "\n<!--\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nxmlns:dc=\"http://purl.org/dc/elements/1.1/\"\nxmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">\n";
					metaData += string.Format("<rdf:Description\nrdf:about=\"{0}\"\ndc:identifier=\"{1}\"\ndc:title=\"{2}\"\ntrackback:ping=\"{3}\" />\n</rdf:RDF>\n-->\n\n", link, link, item.Title, SiteUtilities.GetTrackbackUrl(item.EntryId));
				}
			}

			ContentPlaceHolder.Controls.Add(new LiteralControl(metaData));
		}
Пример #2
0
        public string CreateEntry(Entry entry, string username, string password)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();
            if (!siteConfig.EnableEditService)
            {
                throw new ServiceDisabledException();
            }

            Authenticate(username, password);

            // ensure that the entryId was filled in
            //
            if (entry.EntryId == null || entry.EntryId.Length == 0)
            {
                entry.EntryId = Guid.NewGuid().ToString();
            }

            // ensure the dates were filled in, otherwise use NOW
            if (entry.CreatedUtc == DateTime.MinValue)
            {
                entry.CreatedUtc = DateTime.UtcNow;
            }
            if (entry.ModifiedUtc == DateTime.MinValue)
            {
                entry.ModifiedUtc = DateTime.UtcNow;
            }

            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

            SiteUtilities.SaveEntry(entry, string.Empty, null, siteConfig, logService, dataService);

            return entry.EntryId;
        }
Пример #3
0
        public IActionResult CreatePost(PostViewModel post, string submit)
        {
            NBR.Entry entry = null;

            modelViewCreator.AddAllLanguages(post);
            if (submit == Constants.BlogPostAddCategoryAction)
            {
                return(HandleNewCategory(post));
            }

            if (submit == Constants.UploadImageAction)
            {
                return(HandleImageUpload(post));
            }

            ValidatePostName(post);
            if (!ModelState.IsValid)
            {
                return(View(post));
            }
            if (!string.IsNullOrWhiteSpace(post.NewCategory))
            {
                ModelState.AddModelError(nameof(post.NewCategory),
                                         $"Please click 'Add' to add the category, \"{post.NewCategory}\" or clear the text before continuing");
                return(View(post));
            }

            try
            {
                entry = mapper.Map <NBR.Entry>(post);

                entry.Initialize();
                entry.Author    = httpContextAccessor.HttpContext.User.Identity.Name;
                entry.Language  = post.Language;
                entry.Latitude  = null;
                entry.Longitude = null;

                var sts = blogManager.CreateEntry(entry);
                if (sts != NBR.EntrySaveState.Added)
                {
                    post.EntryId = entry.EntryId;
                    ModelState.AddModelError("", "Failed to create blog post. Please check Logs for more details.");
                    return(View(post));
                }
            }
            catch (Exception ex)
            {
                logger.LogError(new EventDataItem(EventCodes.Error, null, "Blog post create failed: {0}", ex.Message));
                ModelState.AddModelError("", "Failed to edit blog post. Please check Logs for more details.");
            }

            if (entry != null)
            {
                logger.LogInformation(new EventDataItem(EventCodes.EntryAdded, null, "Blog post created: {0}", entry.Title));
            }

            BreakSiteCache();

            return(View("views/blogpost/editPost.cshtml", post));
        }
Пример #4
0
		public void VerifySaveEntry()
		{
			Guid entryId = Guid.NewGuid();
			Entry entry = new Entry();
			entry.Initialize();
			entry.CreatedUtc = new DateTime(2004, 1, 1);
			entry.Title = "Happy New ear";
			entry.Content = "The beginning of a new year.";
			entry.Categories = "Test";
			entry.EntryId = entryId.ToString();
			entry.Description = "The description of the entry.";
			entry.Author = "Inigo Montoya";
			// TODO:  Update so private entries will work as well.
			entry.IsPublic = true;
			entry.Language = "C#";
			entry.Link = "http://mark.michaelis.net/blog";
			entry.ModifiedUtc = entry.CreatedUtc;
			entry.ShowOnFrontPage = false;
			BlogDataService.SaveEntry( entry );

			entry = BlogDataService.GetEntry(entryId.ToString());
			Assert.IsNotNull(entry, "Unable to retrieve the specified entry.");
			Assert.AreEqual(entryId.ToString(), entry.EntryId);
			Assert.AreEqual(new DateTime(2004, 1, 1), entry.CreatedUtc);
			Assert.AreEqual("Happy New ear", entry.Title);
			Assert.AreEqual("The beginning of a new year.", entry.Content);
			Assert.AreEqual("Test", entry.Categories);
			Assert.AreEqual("The description of the entry.", entry.Description);
			Assert.AreEqual("Inigo Montoya", entry.Author);
			Assert.AreEqual(true, entry.IsPublic);
			Assert.AreEqual("C#", entry.Language);
			Assert.AreEqual("http://mark.michaelis.net/blog", entry.Link);
			Assert.AreEqual(entry.CreatedUtc, entry.ModifiedUtc);
			Assert.AreEqual(false, entry.ShowOnFrontPage);
		}
Пример #5
0
        protected override EntryCollection LoadEntries()
        {
            Entry e = new Entry();

            e.Title = resmgr.GetString("text_send_an_email");

            TitleOverride = e.Title;

            return new EntryCollection(new Entry[] { e });
        }
Пример #6
0
        public void CopyEntry()
        {
            Entry entry = new Entry();
            entry.Initialize();

            Entry same = entry;
            Assert.AreSame(entry, same);

            Entry copy = entry.Clone();
            bool equals = entry.Equals(copy);
            Assert.IsTrue(!equals);
        }
Пример #7
0
        public IActionResult Comment(string posttitle, string day, string month, string year)
        {
            ListPostsViewModel lpvm = null;

            NBR.Entry entry    = null;
            var       postguid = Guid.Empty;

            var uniquelinkdate = ValidateUniquePostDate(year, month, day);

            entry = blogManager.GetBlogPost(posttitle, uniquelinkdate);

            if (entry == null && Guid.TryParse(posttitle, out postguid))
            {
                entry = blogManager.GetBlogPostByGuid(postguid);

                var pvm = mapper.Map <PostViewModel>(entry);

                return(RedirectPermanent(dasBlogSettings.GetCommentViewUrl(pvm.PermaLink)));
            }

            if (entry != null)
            {
                lpvm = new ListPostsViewModel
                {
                    Posts = new List <PostViewModel> {
                        mapper.Map <PostViewModel>(entry)
                    }
                };

                if (dasBlogSettings.SiteConfiguration.EnableComments)
                {
                    var lcvm = new ListCommentsViewModel
                    {
                        Comments = blogManager.GetComments(entry.EntryId, false)
                                   .Select(comment => mapper.Map <CommentViewModel>(comment)).ToList(),
                        PostId        = entry.EntryId,
                        PostDate      = entry.CreatedUtc,
                        CommentUrl    = dasBlogSettings.GetCommentViewUrl(posttitle),
                        ShowComments  = true,
                        AllowComments = entry.AllowComments
                    };

                    lpvm.Posts.First().Comments = lcvm;
                }
            }

            return(SinglePostView(lpvm));
        }
Пример #8
0
        public IActionResult CommentError(AddCommentViewModel comment, List <string> errors)
        {
            ListPostsViewModel lpvm = null;

            NBR.Entry entry    = null;
            var       postguid = Guid.Parse(comment.TargetEntryId);

            entry = blogManager.GetBlogPostByGuid(postguid);
            if (entry != null)
            {
                lpvm = new ListPostsViewModel
                {
                    Posts = new List <PostViewModel> {
                        mapper.Map <PostViewModel>(entry)
                    }
                };

                if (dasBlogSettings.SiteConfiguration.EnableComments)
                {
                    var lcvm = new ListCommentsViewModel
                    {
                        Comments = blogManager.GetComments(entry.EntryId, false)
                                   .Select(comment => mapper.Map <CommentViewModel>(comment)).ToList(),
                        PostId        = entry.EntryId,
                        PostDate      = entry.CreatedUtc,
                        CommentUrl    = dasBlogSettings.GetCommentViewUrl(comment.TargetEntryId),
                        ShowComments  = true,
                        AllowComments = entry.AllowComments
                    };

                    if (comment != null)
                    {
                        lcvm.CurrentComment = comment;
                    }
                    lpvm.Posts.First().Comments = lcvm;
                    if (errors != null && errors.Count > 0)
                    {
                        lpvm.Posts.First().ErrorMessages = errors;
                    }
                }
            }

            return(SinglePostView(lpvm));
        }
Пример #9
0
		public static Entry CreateEntry (string title, int lineCount, int paragraphCount)
		{
			Entry entry = new Entry();
			entry.Initialize();
			entry.Title = title;

			StringBuilder lines = new StringBuilder(Sentence.Length * lineCount + 6);
			lines.Append("<p>");
			for (int i = 0; i < lineCount; i++)
			{
				lines.Append(Sentence);
			}
			lines.Append("</p>");

			StringBuilder paragraphs = new StringBuilder(Sentence.Length * lines.Length * paragraphCount);
			for (int i = 0; i < paragraphCount; i++)
			{
				paragraphs.Append(lines.ToString());
			}

			entry.Content = paragraphs.ToString();

			return entry;
		}
Пример #10
0
		/// <summary>
		/// Returns true if the entry is in the categoryName specified.
		/// </summary>
		/// <param name="entry">The entry to check for category</param>
		/// <param name="categoryName">
		/// The name of the category to check.  If categoryName is null or empty check
		/// whether the entry has no categories,
		/// </param>
		/// <returns>
		/// A value of true indicates the entry is in the category specified or, if the categoryName
		/// is null or empty, return true if the entry is assigned no categories
		/// </returns>
		public static bool IsInCategory(Entry entry, string categoryName)
		{
			bool categoryFound = false;

			if (String.IsNullOrEmpty(categoryName))
			{
				categoryFound = String.IsNullOrEmpty(entry.Categories);
			}
			else
			{
				foreach (string entryCategory in entry.GetSplitCategories())
				{
					if (String.Equals(entryCategory, categoryName, StringComparison.InvariantCultureIgnoreCase))
					{
						categoryFound = true;
						break;
					}
				}
			}

			return categoryFound;
		}
Пример #11
0
		/// <summary>
		/// Delegate callback used to filter itmes that are not front page items.
		/// </summary>
		/// <param name="entry"></param>
		/// <returns></returns>
		public static bool ShowOnFrontPageEntry(Entry entry)
		{
			return entry.ShowOnFrontPage;
		}
Пример #12
0
		/// <summary>
		/// Delegate callback used to filter items that are not public.
		/// </summary>
		/// <param name="entry"></param>
		/// <returns></returns>
		public static bool IsPublicEntry(Entry entry)
		{
			return entry.IsPublic;
		}
Пример #13
0
        public static int Import(string from, string to)
        {
			if(from == null || from.Length == 0)
			{
				throw new ArgumentException("The source directory is required.");
			}
			else if(to == null || to.Length == 0)
			{
				throw new ArgumentException("The content directory is required.");
			}
			else if(!Directory.Exists(from))
			{
				throw new ArgumentException(
					string.Format("The source directory, '{0}' does not exist.", from));
			}
			else if(!Directory.Exists(to))
			{
				throw new ArgumentException(
					string.Format("The content directory, '{0}' does not exist.", to));
			}

			IBlogDataService dataService = BlogDataServiceFactory.GetService(to,null);

            ArrayList tables = new ArrayList();

            XmlDocument masterDoc = new XmlDocument();
            StringBuilder sb = new StringBuilder();
            sb.Append("<tables>");

            foreach (FileInfo file in new DirectoryInfo(from).GetFiles("*.xml"))
            {
                XmlDocument entry = new XmlDocument();
                entry.Load(file.FullName);
                sb.Append(entry.FirstChild.NextSibling.OuterXml);
            }
            sb.Append("</tables>");

            masterDoc.Load(new StringReader(sb.ToString()));

            foreach (XmlNode node in masterDoc.FirstChild)
            {
                EntryTable table = new EntryTable();
                table.Name = node.Attributes["name"].Value;
                foreach (XmlNode child in node)
                {
                    switch (child.Name)
                    {
                        case "date":
                            table.Data[child.Attributes["name"].Value] = DateTime.Parse(child.Attributes["value"].Value);
                            break;
                        case "boolean":
                            table.Data[child.Attributes["name"].Value] = bool.Parse(child.Attributes["value"].Value);
                            break;
                        case "string":
                            table.Data[child.Attributes["name"].Value] = child.Attributes["value"].Value;
                            break;
                        case "table":
                            if (child.Attributes["name"].Value == "categories")
                            {
                                foreach (XmlNode catNode in child)
                                {
                                    if (catNode.Name == "boolean" && catNode.Attributes["value"].Value == "true")
                                    {
                                        if (table.Data.Contains("categories"))
                                        {
                                            table.Data["categories"] = (string)table.Data["categories"] + ";" + catNode.Attributes["name"].Value;
                                        }
                                        else
                                        {
                                            table.Data["categories"] = catNode.Attributes["name"].Value;
                                        }
                                    }
                                }
                            }
                            break;
                        case "link":
                            table.Data[child.Attributes["name"].Value] = child.Attributes["value"].Value;
                            break;
						case "flNotOnHomePage":
							table.Data[child.Attributes["name"].Value] = child.Attributes["value"].Value;
							break;
                    }
                }
                tables.Add(table);
            }

            foreach (EntryTable table in tables)
            {
                Entry entry = new Entry();
                entry.CreatedUtc = table.When;
                entry.Title = table.Title;
                entry.Link = table.Link;
                entry.Content = table.Text;
                entry.Categories = table.Categories;
                entry.EntryId = table.UniqueId;
				entry.ShowOnFrontPage = !table.NotOnHomePage;
                dataService.SaveEntry( entry );
            }

			Console.WriteLine("{0} entrys were imported", tables.Count);
            return 0;
        }
Пример #14
0
		public void ProcessRequest( HttpContext context )
		{
			 if (!SiteSecurity.IsValidContributor()) 
			{
				context.Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
			}

			SiteConfig siteConfig = SiteConfig.GetSiteConfig();

			string entryId = "";
			string author = "";
			string title = "";
			string textToSave = "";
			string redirectUrl = SiteUtilities.GetStartPageUrl();


			System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(context.Request.InputStream);
			try
			{
				while (!xtr.EOF)
				{
					xtr.Read();
					if (xtr.Name=="entryid")
					{
						entryId = xtr.ReadInnerXml();
					}
					if (xtr.Name=="author")
					{
						author = xtr.ReadInnerXml();
					}
					if (xtr.Name=="title" && xtr.NodeType == System.Xml.XmlNodeType.Element)
					{
						// Ensure this is the start element before moving forward to the CDATA.
						xtr.Read();  // Brings us to the CDATA inside "title"
						title = xtr.Value;
					}
					if (xtr.Name=="posttext" && xtr.NodeType == System.Xml.XmlNodeType.Element)
					{
						xtr.Read();
						textToSave = xtr.Value;
					}
				}
			}
			finally
			{
				xtr.Close();
			}


			// make sure the entry param is there
			if (entryId == null || entryId.Length == 0) 
			{
				context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
				return;
			}
			else
			{
				ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
				IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService );
			
				// First, attempt to get the entry.  If the entry exists, then get it for editing 
				// and save.  If not, create a brand new entry and save it instead.
				Entry entry = dataService.GetEntry(entryId);
				if ( entry != null )
				{
					entry = dataService.GetEntryForEdit( entryId );
					Entry modifiedEntry = entry.Clone();
					modifiedEntry.Content = textToSave;
					modifiedEntry.Title = title;
					modifiedEntry.Author = author;
					modifiedEntry.Syndicated = false;
					modifiedEntry.IsPublic = false;
					modifiedEntry.ModifiedUtc = DateTime.Now.ToUniversalTime();
					modifiedEntry.Categories = "";
					dataService.SaveEntry(modifiedEntry, null);

					//context.Request.Form["textbox1"];
					
					logService.AddEvent(
						new EventDataItem( 
						EventCodes.EntryChanged, entryId, 
						context.Request.RawUrl));
				}
				else
				{
					// This is a brand new entry.  Create the entry and save it.
					entry = new Entry();
					entry.EntryId = entryId;
					entry.CreatedUtc = DateTime.Now.ToUniversalTime();
					entry.ModifiedUtc = DateTime.Now.ToUniversalTime();
					entry.Title = title;
					entry.Author = author;
					entry.Content = textToSave;
					entry.Syndicated = false;
					entry.IsPublic = false;
					dataService.SaveEntry(entry, null);

					//context.Request.Form["textbox1"];
					
					logService.AddEvent(
						new EventDataItem( 
						EventCodes.EntryAdded, entryId, 
						context.Request.RawUrl));
				}
			}
		}
Пример #15
0
 public static EntrySaveState UpdateEntry(Entry entry, string trackbackUrl, CrosspostInfoCollection crosspostList, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
 {
     return SiteUtilities.UpdateEntry(entry,trackbackUrl,crosspostList,siteConfig,logService,dataService);
 }
Пример #16
0
		/// <summary>
		/// Returns true if the specified Entry is within the same month as <c>month</c>;
		/// </summary>
		/// <param name="entry"></param>
		/// <param name="timeZone"></param>
		/// <param name="month"></param>
		/// <returns></returns>
		public static bool OccursInMonth(Entry entry, TimeZone timeZone,
		                                 DateTime month)
		{
			DateTime startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
			DateTime endOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0);
			endOfMonth = endOfMonth.AddMonths(1);
			endOfMonth = endOfMonth.AddSeconds(-1);
			//TimeSpan offset = timeZone.GetUtcOffset(endOfMonth);
			//endOfMonth = endOfMonth.AddHours(offset.Negate().Hours);
			return (OccursBetween(entry, timeZone, startOfMonth, endOfMonth));
		}
Пример #17
0
		public FooMacros(SharedBasePage page, Entry item)
		{
			requestPage = page;
			currentItem = item;
		}
Пример #18
0
 public override void ProcessItemTemplate(newtelligence.DasBlog.Runtime.Entry item, Control ContentPlaceHolder)
 {
     base.ProcessItemTemplate(item, ContentPlaceHolder);
 }
Пример #19
0
        protected void HandleCrosspost(CrosspostInfo ci, Entry entry)
        {
            try
            {
                BloggerAPIClientProxy proxy = new BloggerAPIClientProxy();
                UriBuilder uriBuilder = new UriBuilder("http", ci.Site.HostName, ci.Site.Port, ci.Site.Endpoint);
                proxy.Url = uriBuilder.ToString();
                proxy.UserAgent = this.UserAgent;

                if (ci.IsAlreadyPosted)
                {
                    try
                    {
                        if (ci.Site.ApiType == "metaweblog")
                        {
                            mwPost existingPost = new mwPost();
                            existingPost.link = "";
                            existingPost.permalink = "";
                            existingPost.categories = ci.Categories.Split(';');
                            existingPost.postid = ci.TargetEntryId;
                            existingPost.dateCreated = entry.CreatedLocalTime;
                            existingPost.title = entry.Title;
                            existingPost.description = entry.Content + ci.GetTrackingSnippet(entry.EntryId);

                            proxy.metaweblog_editPost(ci.TargetEntryId, ci.Site.Username, ci.Site.Password, existingPost, true);

                            Crosspost cp = new Crosspost();
                            cp.TargetEntryId = ci.TargetEntryId;
                            cp.ProfileName = ci.Site.ProfileName;
                            cp.Categories = ci.Categories;
                            entry.Crossposts.Add(cp);

                        }
                        else if (ci.Site.ApiType == "blogger")
                        {
                            proxy.blogger_editPost("", ci.TargetEntryId, ci.Site.Username, ci.Site.Password, entry.Content + ci.GetTrackingSnippet(entry.EntryId), true);

                            Crosspost cp = new Crosspost();
                            cp.TargetEntryId = ci.TargetEntryId;
                            cp.ProfileName = ci.Site.ProfileName;
                            entry.Crossposts.Add(cp);
                        }

                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.CrosspostChanged, ci.Site.HostName, null));
                        }

                    }
                    catch (XmlRpcFaultException xrfe)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, xrfe);
                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.Error,
                                xrfe.Message,
                                String.Format("Updating cross-post entry {0} on {1}; Failed with server-fault code, {2} \"{3}\"", ci.TargetEntryId, ci.Site.ProfileName, xrfe.FaultCode, xrfe.FaultString)));
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.Error,
                                e.ToString().Replace("\n", "<br />"),
                                String.Format("Updating cross-post entry {0} on {1}", ci.TargetEntryId, ci.Site.ProfileName)));
                        }
                    }
                }
                else
                {
                    try
                    {

                        if (ci.Site.ApiType == "metaweblog")
                        {
                            mwPost newPost = new mwPost();
                            newPost.link = "";
                            newPost.permalink = "";
                            newPost.postid = "";
                            newPost.categories = ci.Categories.Split(';');
                            newPost.dateCreated = entry.CreatedLocalTime;
                            newPost.description = entry.Content + ci.GetTrackingSnippet(entry.EntryId);
                            newPost.title = entry.Title;
                            newPost.postid = proxy.metaweblog_newPost(ci.Site.BlogId,
                                ci.Site.Username,
                                ci.Site.Password,
                                newPost, true);
                            Crosspost cp = new Crosspost();
                            cp.TargetEntryId = newPost.postid;
                            cp.ProfileName = ci.Site.ProfileName;
                            cp.Categories = ci.Categories;
                            entry.Crossposts.Add(cp);
                        }
                        else if (ci.Site.ApiType == "blogger")
                        {
                            Crosspost cp = new Crosspost();
                            cp.TargetEntryId = proxy.blogger_newPost("", ci.Site.BlogId, ci.Site.Username, ci.Site.Password, entry.Content + ci.GetTrackingSnippet(entry.EntryId), true);
                            cp.ProfileName = ci.Site.ProfileName;
                            entry.Crossposts.Add(cp);
                        }

                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.CrosspostAdded, ci.Site.HostName, null));
                        }
                    }
                    catch (XmlRpcFaultException xrfe)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, xrfe);
                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.Error,
                                xrfe.Message,
                                String.Format("Adding cross-post entry to {0}; Failed with server-fault code, {1} \"{2}\"", ci.Site.ProfileName, xrfe.FaultCode, xrfe.FaultString)));
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, e);
                        if (loggingService != null)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(EventCodes.Error,
                                e.ToString().Replace("\n", "<br />"),
                                String.Format("Adding cross-post entry to {0}", ci.Site.ProfileName)));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(TraceLevel.Error, e);
                if (loggingService != null)
                {
                    loggingService.AddEvent(
                        new EventDataItem(EventCodes.Error,
                        e.ToString().Replace("\n", "<br />"),
                        String.Format("HandleCrosspost to {0}", ci.Site.ProfileName)));
                }
            }

        }
Пример #20
0
 internal CrosspostJob(object info, Entry entry, IBlogDataService dataService)
 {
     this.info = info;
     this.entry = entry;
     this.dataService = dataService;
 }
Пример #21
0
 internal TrackbackJob(TrackbackInfo info, Entry entry)
 {
     this.info = info;
     this.entry = entry;
 }
Пример #22
0
 internal PingbackJob(PingbackInfo info, Entry entry)
 {
     this.info = info;
     this.entry = entry;
 }
Пример #23
0
        EntrySaveState IBlogDataService.SaveEntry(Entry entry, params object[] trackingInfos)
        {
            bool found = false;

            if (entry.EntryId == null || entry.EntryId.Length == 0)
                return EntrySaveState.Failed;

            DayEntry day = InternalGetDayEntry(entry.CreatedUtc.Date);
            Entry currentEntry = day.Entries[entry.EntryId];

            // OmarS: now that all the entries are returned from a cache, and not desrialized
            // for each request, users who call GetEntry() will get the current entry in the runtime.
            // That entry can be modified freely, and changes will not be commited till day.Save()
            // is called. However, since they have made changes, and passed in that entry, currentEntry
            // and entry are the same objects (reference the same object) and now the changes are in the day
            // but they haven't been saved. This can cause weird problems, and the runtime may have data
            // that is not commited, and it will be lost if day.Save() is never called.
            if (entry == null)
            {
                throw new ArgumentNullException("Entry is null");
            }

            if (entry.Equals(currentEntry))
            {
                throw new ArgumentException("You have modified an existing entry and are passing that in. You need to call GetEntryForEdit to get a copy of the entry before modifying it");
            }

            //There's a possibility that they've changed the CreatedLocalTime of the entry
            // which means it CURRENTLY lives in one DayEntry file but will soon live in another.
            // We need to find the old version, if it exists, and if the CreatedLocalTime is different
            // than the one being saved now, blow it away.
            Entry originalEntry = this.InternalGetEntry(entry.EntryId);
            DayExtra originalExtra = null;

            //Get the comments and trackings for the original entry
            CommentCollection originalComments = null;
            TrackingCollection originalTrackings = null;

            //If we found the original and they DID change the CreatedLocalTime
            if (currentEntry == null && originalEntry != null && originalEntry.CreatedLocalTime != entry.CreatedLocalTime)
            {
                //get the comments and trackings
                originalExtra = data.GetDayExtra(originalEntry.CreatedUtc.Date);
                if (originalExtra != null)
                {
                    originalComments = originalExtra.GetCommentsFor(originalEntry.EntryId, data);
                    originalTrackings = originalExtra.GetTrackingsFor(originalEntry.EntryId, data);

                    //O^n slow...
                    foreach (Comment c in originalComments)
                    {
                        originalExtra.Comments.Remove(c);
                    }

                    //O^n slow...be nice if they were hashed
                    foreach (Tracking t in originalTrackings)
                    {
                        originalExtra.Trackings.Remove(t);
                    }
                    originalExtra.Save(data);
                }


                //Get that original's day and delete the entry
                DayEntry originalDay = InternalGetDayEntry(originalEntry.CreatedUtc.Date);
                originalDay.Entries.Remove(originalEntry);
                originalDay.Save(data);
            }


            // we need to check to see if the two objects are equal so that we avoid trasing
            // data like Crossposts.Clear() which will remove the crosspostInfo from both entries
            if (currentEntry != null && !currentEntry.Equals(entry))
            {
                // we will only change the mod date if there has been a change to a few things
                if (currentEntry.CompareTo(entry) == 1)
                {
                    currentEntry.ModifiedUtc = DateTime.Now.ToUniversalTime();
                }

                currentEntry.Categories = entry.Categories;
                currentEntry.Syndicated = entry.Syndicated;
                currentEntry.Content = entry.Content;
                currentEntry.CreatedUtc = entry.CreatedUtc;
                currentEntry.Description = entry.Description;
                currentEntry.anyAttributes = entry.anyAttributes;
                currentEntry.anyElements = entry.anyElements;

                currentEntry.Author = entry.Author;
                currentEntry.IsPublic = entry.IsPublic;
                currentEntry.Language = entry.Language;
                currentEntry.AllowComments = entry.AllowComments;
                currentEntry.Link = entry.Link;
                currentEntry.ShowOnFrontPage = entry.ShowOnFrontPage;
                currentEntry.Title = entry.Title;
				currentEntry.Latitude = entry.Latitude;
				currentEntry.Longitude = entry.Longitude;

                currentEntry.Crossposts.Clear();
                currentEntry.Crossposts.AddRange(entry.Crossposts);
                currentEntry.Attachments.Clear();
                currentEntry.Attachments.AddRange(entry.Attachments);

                day.Save(data);
                data.lastEntryUpdate = currentEntry.ModifiedUtc;
                data.IncrementEntryChange();
                found = true;
            }
            else
            {
                day.Entries.Add(entry);
                day.Save(data);
                data.lastEntryUpdate = entry.CreatedUtc;
                data.IncrementEntryChange();
                found = false;
            }

            //Now, move the comments and trackings to the new Date
            if (originalEntry != null && originalComments != null && originalExtra != null)
            {
                DayExtra newExtra = data.GetDayExtra(entry.CreatedUtc.Date);
                newExtra.Comments.AddRange(originalComments);
                newExtra.Trackings.AddRange(originalTrackings);
                newExtra.Save(data);
            }


            if (trackingInfos != null && entry.IsPublic)
            {
                foreach (object trackingInfo in trackingInfos)
                {
                    if (trackingInfo != null)
                    {
                        if (trackingInfo is WeblogUpdatePingInfo)
                        {
                            ThreadPool.QueueUserWorkItem(
                                new WaitCallback(this.PingWeblogsWorker),
                                (WeblogUpdatePingInfo)trackingInfo);
                        }
                        else if (trackingInfo is PingbackInfo)
                        {
                            PingbackJob pingbackJob = new PingbackJob((PingbackInfo)trackingInfo, entry);

                            ThreadPool.QueueUserWorkItem(
                                new WaitCallback(this.PingbackWorker),
                                pingbackJob);
                        }
                        else if (trackingInfo is PingbackInfoCollection)
                        {
                            PingbackInfoCollection pic = trackingInfo as PingbackInfoCollection;
                            foreach (PingbackInfo pi in pic)
                            {
                                PingbackJob pingbackJob = new PingbackJob(pi, entry);

                                ThreadPool.QueueUserWorkItem(
                                    new WaitCallback(this.PingbackWorker),
                                    pingbackJob);
                            }
                        }
                        else if (trackingInfo is TrackbackInfo)
                        {
                            ThreadPool.QueueUserWorkItem(
                                new WaitCallback(this.TrackbackWorker),
                                new TrackbackJob((TrackbackInfo)trackingInfo, entry));
                        }
                        else if (trackingInfo is TrackbackInfoCollection)
                        {
                            TrackbackInfoCollection tic = trackingInfo as TrackbackInfoCollection;
                            foreach (TrackbackInfo ti in tic)
                            {
                                ThreadPool.QueueUserWorkItem(
                                    new WaitCallback(this.TrackbackWorker),
                                    new TrackbackJob(ti, entry));
                            }
                        }
                        else if (trackingInfo is CrosspostInfo ||
                            trackingInfo is CrosspostInfoCollection)
                        {
                            ThreadPool.QueueUserWorkItem(
                                new WaitCallback(this.CrosspostWorker),
                                new CrosspostJob(trackingInfo, entry, this));
                        }
                    }
                }
            }
            return found ? EntrySaveState.Updated : EntrySaveState.Added;
        }
Пример #24
0
		/// <summary>
		/// Returns true if the entry is in the categoryName specified.
		/// </summary>
		/// <param name="entry">The entry to check for category</param>
		/// <param name="timeZone">The time zone.</param>
		/// <param name="dateTime">The latest date and time the entry can occur.</param>
		/// <returns>
		/// A value of true indicates the entry is in the category specified or, if the categoryName
		/// is null or empty, return true if the entry is assigned no categories
		/// </returns>
		public static bool OccursBefore(Entry entry, TimeZone timeZone, DateTime dateTime)
		{
			return (timeZone.ToLocalTime(entry.CreatedUtc) <= dateTime);
		}
Пример #25
0
		public static bool OccursBetween(Entry entry, TimeZone timeZone,
		                                 DateTime startDateTime, DateTime endDateTime)
		{
			return ((timeZone.ToLocalTime(entry.CreatedUtc) >= startDateTime)
			        && (timeZone.ToLocalTime(entry.CreatedUtc) <= endDateTime));
		}
Пример #26
0
		public void ProcessTemplate(SharedBasePage page, Entry entry, string templateString, Control contentPlaceHolder, Macros macros)
		{
			int lastIndex = 0;

			MatchCollection matches = templateFinder.Matches(templateString);
			foreach( Match match in matches )
			{
				if ( match.Index > lastIndex )
				{
					contentPlaceHolder.Controls.Add(new LiteralControl(templateString.Substring(lastIndex,match.Index-lastIndex)));
				}
				Group g = match.Groups["macro"];
				Capture c = g.Captures[0];
				
				Control ctrl = null;
				object targetMacroObj = macros;
				string captureValue = c.Value;
				
				//Check for a string like: <%foo("bar", "bar")|assemblyConfigName%>
				int assemblyNameIndex = captureValue.IndexOf(")|");
				if (assemblyNameIndex != -1) //use the default Macros
				{
					//The QN minus the )| 
					string macroAssemblyName = captureValue.Substring(assemblyNameIndex+2);
					//The method, including the )
					captureValue = captureValue.Substring(0,assemblyNameIndex+1);

					try
					{
						targetMacroObj = MacrosFactory.CreateCustomMacrosInstance(page, entry, macroAssemblyName);
					}
					catch (Exception ex)
					{
						string ExToString = ex.ToString();
						if (ex.InnerException != null)
						{
							ExToString += ex.InnerException.ToString();
						}
						page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,String.Format("Error executing Macro: {0}",ExToString),string.Empty));
					}
				}

				try
				{
					ctrl = InvokeMacro(targetMacroObj,captureValue) as Control;
					if (ctrl != null)
					{
						contentPlaceHolder.Controls.Add(ctrl);
					}
					else 
					{
						page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,String.Format("Error executing Macro: {0} returned null.",captureValue),string.Empty));
					}
				}
				catch (Exception ex)
				{
					string error = String.Format("Error executing macro: {0}. Make sure it you're calling it in your BlogTemplate with parentheses like 'myMacro()'. Macros with parameter lists and overloads must be called in this way. Exception: {1}",c.Value, ex.ToString());
					page.LoggingService.AddEvent(new EventDataItem(EventCodes.Error,error,string.Empty));
				}
				lastIndex = match.Index+match.Length;
			}
			if ( lastIndex < templateString.Length)
			{
				contentPlaceHolder.Controls.Add(new LiteralControl(templateString.Substring(lastIndex,templateString.Length-lastIndex)));
			}
		}
Пример #27
0
		/// <summary>
		/// Returns true if the specified entry has is an accepted language.
		/// </summary>
		/// <param name="entry">The entry whose Language property is checked.</param>
		/// <param name="acceptLanguages">A comma separated list of accepted languages.</param>
		/// <returns>
		/// Returns true if the entry's language is in the acceptedLanguages list or 
		/// else acceptedLanguages is null/empty and the entry's language is null/empty.
		/// </returns>
		public static bool IsInAcceptedLanguages(Entry entry, string acceptLanguages)
		{
			bool languageFound = false;

			// If acceptLanguages is empty or null then check to see
			// whether the entry has no languages.
			if (String.IsNullOrEmpty(acceptLanguages))
			{
				languageFound = String.IsNullOrEmpty(entry.Language);
			}
			else
			{
				foreach (string eachLanguageElement in acceptLanguages.Split(','))
				{
					string language = eachLanguageElement.Split(';')[0];
					if (language.ToUpper().StartsWith(entry.Language.ToUpper()))
					{
						languageFound = true;
						break;
					}
				}
			}

			return languageFound;
		}
Пример #28
0
        public string UpdateEntry(Entry entry, string username, string password)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();
            if (!siteConfig.EnableEditService)
            {
                throw new ServiceDisabledException();
            }

            Authenticate(username, password);

            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

            EntrySaveState val = SiteUtilities.UpdateEntry(entry, null, null, siteConfig, logService, dataService);

            string rtn = string.Empty;
            if (val.Equals(EntrySaveState.Updated))
                rtn = entry.EntryId;
            else
                rtn = val.ToString();

            return rtn;
        }
Пример #29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;
            siteConfig = SiteConfig.GetSiteConfig();

            resmgr = ApplicationResourceTable.Get();

            imageUpload.Accept = "image/jpeg,image/gif,image/png";
            editControl.Width = Unit.Percentage(99d);
            editControl.Height = Unit.Pixel(400);
            editControl.Text = "<p></p>";

            // TODO: OmarS need to get rid of this
            isDHTMLEdit = true;

            editControl.SetLanguage(CultureInfo.CurrentUICulture.Name);
            editControl.SetTextDirection(requestPage.ReadingDirection);

            if (!requestPage.SiteConfig.EnableCrossposts)
            {
                gridCrossposts.Visible = false;
                labelCrosspost.Visible = false;
            }

            if (!SiteSecurity.IsValidContributor())
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            CrosspostInfoCollection crosspostSiteInfo = new CrosspostInfoCollection();

            if (!IsPostBack)
            {
                foreach (CrosspostSite site in requestPage.SiteConfig.CrosspostSites)
                {
                    CrosspostInfo ci = new CrosspostInfo(site);
                    ci.TrackingUrlBase = SiteUtilities.GetCrosspostTrackingUrlBase(requestPage.SiteConfig);
                    crosspostSiteInfo.Add(ci);
                }

                // set up categories
                foreach (CategoryCacheEntry category in requestPage.DataService.GetCategories())
                {
                    this.categoryList.Items.Add(category.Name);
                }

                // get the cultures
                CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);

                // setup temp store for listitem items, for sorting
                List<ListItem> cultureList = new List<ListItem>(cultures.Length);

                foreach (CultureInfo ci in cultures)
                {
                    string langName = (ci.NativeName != ci.EnglishName) ? ci.NativeName + " / " + ci.EnglishName : ci.NativeName;

                    if (langName.Length > 55)
                    {
                        langName = langName.Substring(0, 55) + "...";
                    }

                    cultureList.Add( new ListItem(langName, ci.Name));
                }

                // setup the sort culture
                string rssCulture = requestPage.SiteConfig.RssLanguage;

                CultureInfo sortCulture;

                try{
                    sortCulture = ( rssCulture != null && rssCulture.Length > 0 ? new CultureInfo( rssCulture ) : CultureInfo.CurrentCulture);
                }catch(ArgumentException){
                    // default to the culture of the server
                    sortCulture = CultureInfo.CurrentCulture;
                }

                // sort the list
                cultureList.Sort(delegate(ListItem x, ListItem y)
                {
                    // actual comparison
                    return String.Compare(x.Text, y.Text, true, sortCulture);
                });

                // add to the languages listbox
                ListItem[] cultureListItems = cultureList.ToArray();

                listLanguages.Items.AddRange(cultureListItems);

                listLanguages.SelectedValue = "";

                if (requestPage != null && requestPage.WeblogEntryId != "")
                {
                    Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] = Request.UrlReferrer;
                    Entry entry = requestPage.DataService.GetEntryForEdit(requestPage.WeblogEntryId);

                    if (entry != null)
                    {
                        CurrentEntry = entry;
                        entryTitle.Text = entry.Title;
                        entryAbstract.Text = entry.Description;

                        textDate.SelectedDate = entry.CreatedLocalTime;

                        if (isDHTMLEdit)
                        {
                            editControl.Text = entry.Content;
                        }

                        foreach (string s in entry.GetSplitCategories())
                        {
                            categoryList.Items.FindByText(s).Selected = true;
                        }

                        this.checkBoxAllowComments.Checked = entry.AllowComments;
                        this.checkBoxPublish.Checked = entry.IsPublic;
                        this.checkBoxSyndicated.Checked = entry.Syndicated;

                        // GeoRSS.
                        this.txtLat.Text = String.Format(CultureInfo.InvariantCulture, "{0}", entry.Latitude);
                        this.txtLong.Text = String.Format(CultureInfo.InvariantCulture, "{0}", entry.Longitude);

                        if (entry.Attachments.Count > 0)
                        {
                            foreach (Attachment enclosure in entry.Attachments)
                            {
                                enclosure.Url = SiteUtilities.GetEnclosureLinkUrl(requestPage.SiteConfig, entry.EntryId, enclosure);
                            }

                            this.enclosureUpload.Visible = false;
                            this.buttonRemove.Visible = true;
                            this.labelEnclosureName.Visible = true;
                            this.labelEnclosureName.Text = entry.Attachments[0].Name;
                        }

                        listLanguages.SelectedValue = entry.Language == null ? "" : entry.Language;

                        // merge the crosspost config with the crosspost data
                        foreach (CrosspostInfo cpi in crosspostSiteInfo)
                        {
                            foreach (Crosspost cp in entry.Crossposts)
                            {
                                if (cp.ProfileName == cpi.Site.ProfileName)
                                {
                                    cpi.IsAlreadyPosted = true;
                                    cpi.TargetEntryId = cp.TargetEntryId;
                                    cpi.Categories = cp.Categories;
                                    break;
                                }
                            }
                        }
                        // if the entry is not public yet but opened for editing, then we can setup autosave.
                        // (If the entry was already published publically and then autosave was used, the
                        // entry's status would change to non-public and then no longer be accessible!)
                        if (requestPage.SiteConfig.EnableAutoSave && !entry.IsPublic)
                        {
                            SetupAutoSave();
                        }

                        if (requestPage.SiteConfig.EnableGoogleMaps)
                        {
                            AddGoogleMapsApi();
                        }

                    }
                }
                else // This is a brand new entry, so setup the AutoSave script if it's enabled.
                {
                    if (requestPage.SiteConfig.EnableAutoSave)
                    {
                        SetupAutoSave();
                    }

                    if (requestPage.SiteConfig.EnableGoogleMaps)
                    {
                        AddGoogleMapsApi();
                    }

                    txtLat.Text = String.Format(CultureInfo.InvariantCulture, "{0}", siteConfig.DefaultLatitude);
                    txtLong.Text = String.Format(CultureInfo.InvariantCulture, "{0}", siteConfig.DefaultLongitude);
                }

                gridCrossposts.DataSource = crosspostSiteInfo;
                DataBind();
            }
        }
Пример #30
0
 /// <summary>
 /// Send an email notification that an entry has been made.
 /// </summary>
 /// <param name="siteConfig">The page making the request.</param>
 /// <param name="entry">The entry being added.</param>
 internal static void SendEmail(Entry entry, SiteConfig siteConfig, ILoggingDataService logService)
 {
     SiteUtilities.SendEmail(entry,siteConfig,logService);
 }
Пример #31
0
        static int Main(string[] args)
        {
            Console.WriteLine("BlogWorksXML Importer");
            Console.WriteLine("(import supports BlogWorks version 1.1 and above)");

            foreach (string arg in args)
            {
                if (arg.Length > 6 && arg.ToLower().StartsWith("/from:"))
                {
                    from = arg.Substring(6).Trim();
                    if (from[0] == '\"' && from[from.Length] == '\"')
                    {
                        from = from.Substring(1, from.Length - 2);
                    }
                }
                else if (arg.Length > 6 && arg.ToLower().StartsWith("/id:")) {
                    id = arg.Substring(4).Trim();
                }
                else if (arg.Length > 6 && arg.ToLower().StartsWith("/to:"))
                {
                    to = arg.Substring(4).Trim();
                    if (to[0] == '\"' && to[from.Length] == '\"')
                    {
                        to = to.Substring(1, to.Length - 2);
                    }
                }
                else
                {
                    break;
                }
            }

            if (from == null || to == null || id == null || from.Length == 0 || to.Length == 0 || id.Length == 0)
            {
                Console.WriteLine("Usage: impbwxml /from:<blogworks data directory> [/id:<blogworks blog id, e.g. 001>] /to:<output directory>");
                Console.WriteLine("");
                return -1;
            }

            IBlogDataService dataService = BlogDataServiceFactory.GetService(to,null);

            Console.WriteLine("Importing entries from...");

            ArrayList tables = new ArrayList();
            ArrayList comments = new ArrayList();
            Hashtable commentRefs = new Hashtable();

            XmlDocument masterDoc = new XmlDocument();
            StringBuilder sb = new StringBuilder();
            sb.Append("<tables>");

            foreach (FileInfo file in new DirectoryInfo(from).GetFiles("*archive"+id+".xml"))
            {
                Console.Write("  * " + file.Name);
                XmlDocument doc = new XmlDocument();
                doc.Load(file.FullName);
                foreach (XmlNode n in doc.SelectNodes("/baef/blog")) {
                    sb.Append(n.OuterXml);
                }
                Console.WriteLine(" ... done.");
            }
            sb.Append("</tables>");

            masterDoc.Load(new StringReader(sb.ToString()));

            foreach (XmlNode node in masterDoc.FirstChild)
            {
                BlogWorksTable table = new BlogWorksTable();
                table.Name = node.Attributes["id"].Value;

                foreach (XmlNode child in node)	//  author with authorname, authormail childs
                {
                    switch (child.Name) {
                        case "author":
                            break;	// ignore. dasBlog is not yet multiuser enabled
                        case "information":
                            foreach (XmlNode infoNode in child) {	//  commentthread; timestamp; language; categories
                                // how about commentthread ?
                                switch (infoNode.Name) {
                                    case "commentthread":
                                        // save the reference for later use
                                        commentRefs.Add(infoNode.InnerText, table.Name);
                                        break;
                                    case "timestamp":
                                        table.Data[infoNode.Name] = UnixToHuman(infoNode.InnerText);
                                        break;
                                    case "language":
                                        if (infoNode.InnerText != "en")
                                            table.Data[infoNode.Name] = infoNode.InnerText;
                                        break;
                                    case "categories":
                                        foreach (XmlNode catNode in infoNode) {
                                            if (catNode.InnerText.Length > 0) {
                                                if (table.Data.Contains("categories")) {
                                                    table.Data["categories"] = (string)table.Data["categories"] + ";" + catNode.InnerText;
                                                }
                                                else {
                                                    table.Data["categories"] = catNode.InnerText;
                                                }
                                            }
                                        }
                                        break;
                                }
                            }
                            if (!table.Data.Contains("categories")) {
                                table.Data["categories"] = "General";
                            }
                            break;

                        case "text":	// blogtitle (entry title); blogbody (entry body)
                            foreach (XmlNode textNode in child) {
                                switch (textNode.Name) {
                                    case "blogtitle":
                                        table.Data[textNode.Name] = textNode.InnerText;
                                        break;
                                    case "blogbody":
                                        table.Data[textNode.Name] = textNode.InnerText;
                                        break;
                                }
                            }
                            break;
                    }
                }
                tables.Add(table);
            }

            Console.WriteLine("Now writing entries....");

            foreach (BlogWorksTable table in tables)
            {
                Entry entry = new Entry();
                entry.CreatedUtc = table.When;
                entry.Title = table.Title;
                entry.Content = table.Text;
                entry.Categories = table.Categories;
                entry.EntryId = table.UniqueId;
                entry.Language = table.Language;
                dataService.SaveEntry( entry );
            }

            Console.WriteLine("Finished. Start reading comments...");

            masterDoc = new XmlDocument();
            sb = new StringBuilder();
            sb.Append("<comments>");

            foreach (FileInfo file in new DirectoryInfo(from).GetFiles("*comment"+id+".xml")) {
                Console.Write("  * " + file.Name);
                XmlDocument doc = new XmlDocument();
                doc.Load(file.FullName);
                foreach (XmlNode n in doc.SelectNodes("/comments/thread")) {
                    sb.Append(n.OuterXml);
                }
                Console.WriteLine(" ... done.");
            }
            sb.Append("</comments>");

            masterDoc.Load(new StringReader(sb.ToString()));

            foreach (XmlNode node in masterDoc.FirstChild) {

                string threadId = node.Attributes["id"].Value;

                if (!commentRefs.Contains(threadId))
                    continue;

                foreach (XmlNode cmtNode in node) {	//  comment's per thread

                    BlogWorksComment comment = new BlogWorksComment();
                    comment.Name = (string)commentRefs[threadId];	// get corresponding entry Id

                    foreach (XmlNode child in cmtNode) {	//  comment elements

                        switch (child.Name) {
                            case "name":
                                comment.Data[child.Name] = child.InnerText;	// Author
                                break;
                            case "datetime":
                                comment.Data[child.Name] = DateTime.Parse(child.InnerText);
                                break;
                            case "email":
                                comment.Data[child.Name] = child.InnerText;
                                break;
                            case "uri":
                                if (child.InnerText.Length > 7 /* "http://".Length */)
                                    comment.Data[child.Name] = child.InnerText;
                                break;
                            case "text":
                                comment.Data[child.Name] = child.InnerText;
                                break;
                            case "ip":
                                comment.Data[child.Name] = child.Clone();	// anyElement
                                break;
                        }
                    }//child
                    comments.Add(comment);
                }//cmtNode

            }

            Console.WriteLine("Now writing comment entries....");

            foreach (BlogWorksComment cmt in comments) {
                Comment comment = new Comment();
                comment.Content = cmt.Text;
                comment.Author = cmt.Author;
                comment.TargetEntryId = cmt.UniqueId;
                comment.AuthorHomepage = cmt.AuthorHomepage;
                comment.AuthorEmail = cmt.AuthorEmail;
                comment.CreatedLocalTime = cmt.When;
                comment.CreatedUtc = cmt.When.ToUniversalTime();
                comment.anyElements = new XmlElement[]{cmt.Ip};

                dataService.AddComment(comment);
            }

            Console.WriteLine("Finished. Start reading comments...");

            Console.WriteLine("Finished successfully.");
            return 0;
        }
Пример #32
0
        protected void save_Click(object sender, EventArgs e)
        {
            SharedBasePage requestPage = this.Page as SharedBasePage;

            if (SiteSecurity.IsValidContributor())
            {
                //Catch empty posts!
                if (!editControl.HasText())
                {
                    return;
                }

                CrosspostInfoCollection crosspostList = new CrosspostInfoCollection();
                Entry entry;

                if (CurrentEntry == null)
                {
                    entry = new Entry();
                    entry.Initialize();
                }
                else
                {
                    entry = CurrentEntry;
                }

                //Try a culture specific parse...
                // TODO: Come up with a shiny javascript datetime picker

                if(textDate.SelectedDateFormatted.Length > 0)
                {
                    try
                    {
                        DateTime createdLocalTime = new DateTime(textDate.SelectedDate.Year,
                            textDate.SelectedDate.Month,
                            textDate.SelectedDate.Day,
                            entry.CreatedLocalTime.Hour,
                            entry.CreatedLocalTime.Minute,
                            entry.CreatedLocalTime.Second,
                            entry.CreatedLocalTime.Millisecond);

                        entry.CreatedLocalTime = createdLocalTime;
                    }
                    catch(FormatException fex)
                    {
                        Trace.Write("Bad DateTime string creating new Entry: " + fex.ToString());
                    }
                }

                // see if we need to delete any old Enclosures
                if (entry.Enclosure	!= null)
                {
                    if (this.enclosureUpload.Visible == true && this.buttonRemove.Visible == false)
                    {
                        DeleteEnclosures();
                    }
                }

                // upload the attachment
                if (enclosureUpload.Value != null && enclosureUpload.Value != String.Empty)
                {
                    try
                    {
                        long numBytes;
                        string type;
                        string baseFileName = HandleUpload(enclosureUpload, entry.EntryId, out type, out numBytes);
                        entry.Attachments.Add(new Attachment(baseFileName, type, numBytes, AttachmentType.Enclosure));
                    }
                    catch (Exception exc)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, exc);
                    }
                }

                entry.Language = listLanguages.SelectedValue == "" ? null : listLanguages.SelectedValue;
                entry.Title = entryTitle.Text;
                entry.Description = entryAbstract.Text;
                entry.Author = requestPage.User.Identity.Name;
                entry.AllowComments = checkBoxAllowComments.Checked;
                entry.IsPublic = checkBoxPublish.Checked;
                entry.Syndicated = checkBoxSyndicated.Checked;

                // GeoRSS.
                if (siteConfig.EnableGeoRss)
                {
                    double latitude, longitude;
                    if (double.TryParse(txtLat.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out latitude))
                    {
                        entry.Latitude = latitude;
                    }
                    else
                    {
                        entry.Latitude = null;
                    }

                    if (double.TryParse(txtLong.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out longitude))
                    {
                        entry.Longitude = longitude;
                    }
                    else
                    {
                        entry.Longitude = null;
                    }
                }

                if (isDHTMLEdit)
                {
                    entry.Content = editControl.Text;
                }

                // handle categories
                string categories = "";

                StringBuilder sb = new StringBuilder();
                bool needSemi = false;

                foreach (ListItem listItem in categoryList.Items)
                {
                    if (listItem.Selected)
                    {
                        if (needSemi) sb.Append(";");
                        sb.Append(listItem.Text);
                        needSemi = true;
                    }
                }

                categories = sb.ToString();
                entry.Categories = categories;

                // handle crosspostSiteInfo
                CrosspostInfoCollection crosspostSiteInfo = new CrosspostInfoCollection();

                // we need to reload the crosspostinfo as it contains sensitive data like password
                foreach (CrosspostSite site in requestPage.SiteConfig.CrosspostSites)
                {
                    CrosspostInfo ci = new CrosspostInfo(site);
                    ci.TrackingUrlBase = SiteUtilities.GetCrosspostTrackingUrlBase(requestPage.SiteConfig);
                    crosspostSiteInfo.Add(ci);
                }

                // merge the crosspost config with the crosspost data
                foreach (CrosspostInfo cpi in crosspostSiteInfo)
                {
                    foreach (Crosspost cp in entry.Crossposts)
                    {
                        if (cp.ProfileName == cpi.Site.ProfileName)
                        {
                            cpi.IsAlreadyPosted = true;
                            cpi.TargetEntryId = cp.TargetEntryId;
                            cpi.Categories = cp.Categories;
                            break;
                        }
                    }
                }

                foreach (DataGridItem item in gridCrossposts.Items)
                {
                    CheckBox checkSite = item.FindControl("checkSite") as CheckBox;
                    if (checkSite.Checked)
                    {
                        TextBox textSiteCategory = item.FindControl("textSiteCategory") as TextBox;
                        foreach (CrosspostInfo cpi in crosspostSiteInfo)
                        {
                            if (cpi.Site.ProfileName == checkSite.Text)
                            {
                                cpi.Categories = textSiteCategory.Text;
                                crosspostList.Add(cpi);
                                break;
                            }
                        }
                    }
                }

                try
                {
                    // prevent SaveEntry from happenning twice
                    if (crosspostList.Count == 0) crosspostList = null;

                    if (CurrentEntry == null) // new entry
                    {

                        SiteUtilities.SaveEntry(entry, this.textTrackback.Text, crosspostList, requestPage.SiteConfig, requestPage.LoggingService, requestPage.DataService);
                    }
                    else // existing entry
                    {
                        SiteUtilities.UpdateEntry(entry, this.textTrackback.Text, crosspostList, requestPage.SiteConfig, requestPage.LoggingService, requestPage.DataService);
                    }
                }
                catch (Exception ex)
                {
                    //SDH: Changed to ex.ToString as the InnerException is often null, which causes another error in this catch!
                    StackTrace st = new StackTrace();
                    requestPage.LoggingService.AddEvent(
                        new EventDataItem(EventCodes.Error, ex.ToString() + Environment.NewLine + st.ToString(), SiteUtilities.GetPermaLinkUrl(entry)));

                    // if we created a new entry, and there was an error, delete the enclosure folder
                    DeleteEnclosures();

                    requestPage.Redirect("FormatPage.aspx?path=SiteConfig/pageerror.format.html");
                }

                entryTitle.Text = "";
                entryAbstract.Text = "";
                categoryList.Items.Clear();

                if (Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] != null)
                {
                    Uri originalReferrer = Session["newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer"] as Uri;
                    Session.Remove("newtelligence.DasBlog.Web.EditEntryBox.OriginalReferrer");
                    Redirect(originalReferrer.AbsoluteUri);
                }
                else
                {
                    Redirect(SiteUtilities.GetAdminPageUrl(requestPage.SiteConfig));
                }
            }
        }
Пример #33
0
        private static string GetMetaTags(string metaTags, Entry entry)
        {
            // Canonical Tag
            metaTags += string.Format(CanonicalLinkPattern, SiteUtilities.GetPermaLinkUrl(entry));

            // Meta Description
            string blogPostDescription;
            string twitterImage;
            string twitterVideo;

            if (string.IsNullOrEmpty(entry.Description) || entry.Description.Length < 20)
            {
                blogPostDescription = entry.Content;
            }
            else
            {
                blogPostDescription = entry.Description;
            }

            //This is dangerous stuff, don't freak out if it doesn't work.
            try
            {
                twitterImage = FindFirstImage(blogPostDescription);
                twitterVideo = FindFirstYouTubeVideo(blogPostDescription);
            }
            catch(Exception ex)
            {
                Trace.WriteLine("Exception looking for Images and Video: " + ex.ToString());
                twitterImage = string.Empty;
                twitterVideo = string.Empty;
            }
            blogPostDescription = HttpUtility.HtmlDecode(blogPostDescription);
            blogPostDescription = blogPostDescription.RemoveLineBreaks();
            blogPostDescription = blogPostDescription.StripHtml();
            blogPostDescription = blogPostDescription.RemoveDoubleSpaceCharacters();
            blogPostDescription = blogPostDescription.Trim();
            blogPostDescription = blogPostDescription.CutLongString(160);
            blogPostDescription = blogPostDescription.RemoveQuotationMarks();

            var smt = new SeoMetaTags();
            smt = smt.GetMetaTags();

            if (blogPostDescription.Length == 0)
                blogPostDescription = smt.MetaDescription;

            metaTags += string.Format(MetaDescriptionTagPattern, blogPostDescription);

            // Meta Keywords
            if (!string.IsNullOrEmpty(entry.Categories))
            {
                metaTags += string.Format(MetaKeywordTagPattern, entry.Categories.Replace(';', ','));
            }

            //Twitter SEO Integration
            metaTags += string.Format(MetaTwitterCardPattern, smt.TwitterCard);
            metaTags += string.Format(MetaTwitterSitePattern, smt.TwitterSite);
            metaTags += string.Format(MetaTwitterCreatorPattern, smt.TwitterCreator);
            metaTags += string.Format(MetaTwitterTitlePattern, entry.Title);
            metaTags += string.Format(MetaTwitterDescriptionPattern, blogPostDescription.CutLongString(120));

            if (twitterImage.Length > 0)
            {
                metaTags += string.Format(MetaTwitterImagePattern, twitterImage);
            }
            else if(twitterVideo.Length > 0)
            {
                metaTags += string.Format(MetaTwitterImagePattern, twitterVideo);
            }
            else
            {
                metaTags += string.Format(MetaTwitterImagePattern, smt.TwitterImage);
            }

            //FaceBook OG Integration
            metaTags += string.Format(MetaFaceBookUrlPattern, SiteUtilities.GetPermaLinkUrl(entry));
            metaTags += string.Format(MetaFaceBookTitlePattern, entry.Title);

            if (twitterImage.Length > 0)
            {
                metaTags += string.Format(MetaFaceBookImagePattern, twitterImage);
            }
            else if (twitterVideo.Length > 0)
            {
                metaTags += string.Format(MetaFaceBookImagePattern, twitterVideo);
            }
            else
            {
                metaTags += string.Format(MetaFaceBookImagePattern, smt.TwitterImage);
            }

            metaTags += string.Format(MetaFaceBookDescriptionPattern, blogPostDescription.CutLongString(120));
            metaTags += MetaFaceBookTypePattern;
            metaTags += string.Format(MetaFaceBookAdminsPattern, smt.FaceBookAdmins);
            metaTags += string.Format(MetaFaceBookAppIDPattern, smt.FaceBookAppID);

            //Scheme.org meta data integration
            metaTags += MetaSchemeOpenScript;
            metaTags += MetaSchemeContext;
            metaTags += MetaSchemeType;
            metaTags += string.Format(MetaSchemeHeadline, entry.Title);
            metaTags += string.Format(MetaSchemeDatePublished, entry.CreatedUtc.ToString("yyyy-MM-dd"));
            metaTags += string.Format(MetaSchemeDescription, blogPostDescription.CutLongString(240));
            metaTags += string.Format(MetaSchemeUrl, SiteUtilities.GetPermaLinkUrl(entry));
            metaTags += string.Format(MetaSchemeImage, twitterImage);
            metaTags += MetaSchemeCloseScript;

            return metaTags;
        }
Пример #34
0
        private void SetupAutoSave()
        {
            if (! Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(),"AutoSaveScript"))
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<script language='javascript' type='text/javascript' runat='server'> " + "\n");

                sb.Append("function StartInterval() " + "\n");
                sb.Append("{ " + "\n");
                sb.Append("	interval = window.setInterval('AutoSaveTimer()',60000);" + "\n");
                sb.Append("} " + "\n");

                sb.Append("function StopInterval() " + "\n");
                sb.Append("{ " + "\n");
                sb.Append("	window.clearInterval(interval);" + "\n");
                sb.Append("} " + "\n");

                string autoSaveText = resmgr.GetString("text_autosave");

                //To do create method using the old
                //function(result) to set the autosave
                //time and success message on return.
                // add the javascript to allow deletion of the entry
                sb.Append("function AutoSaveTimer()\n");
                sb.Append("{\n");
                //sb.Append("alert('before from ajax'); \n");
                sb.Append("		var url = 'autoSaveEntry.ashx';");//?entryId=" +  CurrentEntry.EntryId + "';");

                // Justice Gray: To properly save this entry we need to create the data required to post to our
                // handler.  Both the entry ID and the text inside the edit box need to be passed.

                sb.AppendFormat("var editTextBox = document.getElementById('{0}');", this.editControl.Control.ClientID);
                sb.AppendFormat("var titleBox = document.getElementById('{0}');", this.entryTitle.ClientID);
                // If our entry does not exist yet, create a new one and use that for the autosave.
                if (CurrentEntry == null)
                {
                    Entry ourAutosavedEntry = new Entry();
                    ourAutosavedEntry.Initialize();
                    CurrentEntry = ourAutosavedEntry;
                }
                sb.AppendFormat("var ajax = new AjaxDelegate(url, AutoSaveResult, '{0}', titleBox.value, '{1}', editTextBox.value);",
                                    CurrentEntry.EntryId, this.Context.User.Identity.Name);

            //				sb.Append("		var ajax = new AjaxDelegate(url, AutoSaveResult); \n");
                sb.Append("		ajax.Fetch(); \n");
                sb.Append("}\n");

                sb.Append("function AutoSaveResult(url, response)  " + "\n");
                sb.Append("{ \n");
                //sb.Append("		var result = eval(response); \n");
                sb.Append("		var dt = new Date(); \n");
                sb.Append("		document.getElementById('" + this.autoSaveLabel.ClientID + "').innerHTML = '" + autoSaveText + " ' + dt.toLocaleString(); \n");
                sb.Append("} \n");
                sb.Append("</script> \n");

                sb.Append("<script> " + "\n");
                sb.Append("StartInterval(); " + "\n");
                //sb.Append("var entryId;" + "\n");
                sb.Append("</script> " + "\n");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"AutoSaveScript", sb.ToString());
            }
        }