Programmatically create new posts

Topics: ASP.NET 2.0, Business Logic Layer
Jul 12, 2010 at 3:54 PM

I have a need to create a few blogposts programmatically. What steps would I have to take to generate the blog-post?

I know that blog posts are created with a guid-filename and xml extension. I have tried to create such a file myself, by copying an existing blog post and but giving it a different [guid].xml filename. Unfortunately, the new post does not show up on my blog. I tried to reset IIS, but that didn't help.

Looking forward to help and/or suggestions.

Many thanks in advance!

Jul 12, 2010 at 10:10 PM
The easiest approach would be to use the BE object model to create the posts -- just like BE uses. If you look at the btnSave_Click code in the Add_entry.aspx.cs file in the admin\Pages folder, you can see what's going on.
Jul 13, 2010 at 7:44 AM
Thank you Ben, I have found the code for saving a post, but it is not quite clear to me how it knows where to save the data. I have been looking at BlogEngine.Core.Datastore, but it doesn't make sense to me very much. Can you give me some pointers? Thank you very much in advance!
Jul 13, 2010 at 9:05 AM
Edited Jul 13, 2010 at 9:05 AM
Maybe I should be more specific with what I am doing. Like I said in my initial post, I want to add posts to my blog programmatically and I am using Visual Basic for that. It's not a problem to generate the XML file that is equal XML files created by adding entries on the admin page. Also, the GUID I can create programmatically. I have taken the following steps: 1. I have added a reference to BlogEngine.Core 2. I can create a new post instance this way: dim Post as new BlogEngine.Core.Post Then I am going to fill some of the 'Post' properties: 1. 'Post.CreatedDate' can be filled with a date/time value 2. 'Post.Author' can be filled with a string value 3. 'Post.Title' can be filled with a string value Next step is to fill the content, the following line throws an 'A first chance exception of type 'System.NullReferenceException' occurred in BlogEngine.Core.dll' exception. Post.Content = "test" Below the exception details: System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="BlogEngine.Core" StackTrace: at BlogEngine.Core.Post.set_Content(String value) in C:\Data\Development\BlogEngine.NET\BlogEngine\DotNetSlave.BusinessLogic\Post.cs:line 110 at AddProductToBlog.Module1.makePost(String Title, String Content, String Description) in Z:\Visual Studio 2008\Projects\AddProductToBlog\AddProductToBlog\Module1.vb:line 19 at AddProductToBlog.Module1.Main() in Z:\Visual Studio 2008\Projects\AddProductToBlog\AddProductToBlog\Module1.vb:line 8 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: Obviously, line 110 in 'Post.cs' is causing the error. That line contains the following code: HttpContext.Current.Cache.Remove("content_" + this.Id); Since my project is a simple console application, it doesn't know anything about HttpContext and that causes the error. I think I am stuck here. My only option would be to just place the xml-file (with a valid name) into the App_data directory, I guess. Looking forward to comments...
Jul 13, 2010 at 9:07 AM
wow... my post is really messed up... it's not readable anymore... I hope someone can make something out of it.
Jul 13, 2010 at 9:59 AM

Yes, that makes sense that because there is no HttpContext, you're getting that error.

Two possible solutions come to mind.  One solution would be to create a web service (.asmx file) within the BE website.  You could then call that web service from your console application, passing to it the values for the post (title, date, content, etc).  The web service would take that information and create a new Post using the BE object model.

The other possibility is to create the XML files, like you've brought up.  Each XML file represents a single post.  You should be able to make a copy of the XML file, and give the new XML file a different GUID filename.  If you do this, the new post won't show up right away because the posts are read in from the App_Data folder when the BE app starts, and BE doesn't look at the App_Data folder anymore (they're cached in memory).  When you manually put a new post in the App_Data\posts folder, BE in unaware a new post is there.  You can get BE to reload the posts by either re-starting the BE application (for example, make any change to the web.config file), or there's also a Post.Reload() method that you could call.  But you would need to call Post.Reload() on the website -- not from your console application.

Just a couple of ideas...

Jul 13, 2010 at 10:27 AM
Thank you for your new suggestions! I think I will go with the 2nd option. i found some older code from you in this thread and that is what I am going to use: I will report back! Thanks again.
Jul 13, 2010 at 12:11 PM

Ok, I copied the code the older thread into the default.aspx.cs and made a copy of an existing post and gave it a new GUID name. After a refresh I get a Server 500 error and below that a page that only shows these weird characters:



Þ6ñöîÞ1©´cÃ�WUJíS×>åö©iÿ(¥Ò»¤ÐŽ Ê;ß,Êß®&“ë·|B°·ß¸ÅÂíŸ,fyµ­`÷™Î·ONžnOù#‚}²Ÿzïç2„TÕÄî]‘ˆT@Ȑî I¼7ùÕóàäß&Ñ<—M>¨êß’ÿþß={úùé›ßÿ§¾|qjÙ°9oÕŠíÚeV®É¦‡yžzyiÝ}ËdM>òò'ñ–'$ËùçGæ·á–œï¸N9°4éùsèçÅò­„æ·¡–.Êø(ˆ8†Z7m:Õð/x½ó"¿jÈåÕg÷ûPk¤ûëPÛWù”:6Ù„ŽÂ¿7¿Ån™yE}´xû×a©_~µ¢T5qVµž‘›_ÛæïÚ'^~lG&\ÿÏMïèØ<ïs íU!Ó¢¿ µûÉ¢)HFRè ZïñþroÜI:ú…ËI³:”ËÕšªë™¬Ûix+_³›õl6SÿÜkð»m}¼QÂ?¾3æ>(é~ñQz7ôÂKŽ9OË¿*ú¢S|]ã”ÑoœP)‡Ž¬¥Y¼ëâøôwï>þ]¿wòôøÍñ÷~ãä|½œ29ëü‚¸9¯Íb³uçû#Ï'¯ªªýìcÑÇzß»Ëñûø÷©ÖiVÒÊìì:­ñQÚÎÉK„ ï¿Öd—¤ßÌsežÏ>~ÍŸÐ;¹‘ÞñxÜÑHög™lóݬ! @퍚^eMÚàãqú†¢ƒ·é5á Ç=Ÿ“e›dÓ·`Hƒ~QÍrѺ�>=¸Ž‰Ëê*Í®%æ ŒHop°J#ÿìOéSš³Ï>~Æ?ûßg«Eù4—¹g$Oa`¹¯^=§tð­Sš]’›<ÞúÑñË/ž§³jºÎ}À“œ†ô¬¨›öM…yÿìã'¹ŒŸ ¦~ÓÌO×”“^¶åµ²Í‰ù[™æïü’trþâÝ_’®òjUæ} ÚòâÛYó$Ï—¯”•ëT¾M‰1Ó }o9<˜ñß5 •W4¿7Å”5ñ×+; ÔЇÀ©"åQ§÷?>ü%‡wï~ÿûœ»BÝ$„é ydbαÞÜÔS“6úiÊk¿›ý«¬ö»ïã3ú1¡ãŸn~a¶X^~¶;þt¼3ÞùzMú»Yæ¡.³:ýý/²_”~&?~ægÒï}ÿßàÏñŠ<ä­ï}üû7¤à¦Ój½ädçWÇÛ÷>ÝÛùôáÃíݏ¿§ßœœŽé[XÃË"¿’h³eË֝ô‹‚Bÿõn¸j<%%ÑæäQ⯭]JdP³1†Bm?î æcþ2k®—Sú¶­×ù¡@§O‰ŽôÙÖÇp)›G§Ÿy]•Õ”El¼ª«¶šVeú{¤Úðîݦ)?NÉßâ‹~|'ý$ýx|QU”Š¤,DV^·Å´ôߥž~š”T㏉t¿¨yrMÖö¹nhßÛùþaÚŒWXý >ù¸´vÑ>ÉIgä[Ù(m„È¿äΖÐÒÎò7ËS¼xA?Å\mâ®Çw ·[`3©f×ÌìóvŸ

After deleting the copied XML file, the website was back to normal, which means that the code I added to the default.aspx.cs file seems to work ok.

Could it be that there is something in the XML file that is causing this? Invalid GUID?


Jul 14, 2010 at 11:48 AM
Since I didn't get any further with my copy/paste from an existing XML to a new XML I created a new XML, like this: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <post> <author>CrashingDutchman</author> <title>Testing Manually inserted blog</title> <description>Testing manually entered description</description> <content>Testing manually entered content</content> <ispublished>True</ispublished> <iscommentsenabled>False</iscommentsenabled> <pubDate>2010-07-10 10:00:00</pubDate> <lastModified>2010-07-10 10:00:00</lastModified> <raters>0</raters> <rating>0</rating> <slug>Testing-Manually-inserted-blog</slug> <tags> <tag>Testing tag</tag> </tags> <comments /> <categories /> <notifications /> </post> I saved the file with this name: f7adfab5-228b-4488-8ac1-d7f5cd87e38.xml What I get is the garbage I posted in my previous post. I really hope someone can help!
Jul 15, 2010 at 12:09 PM

What version of BE are you using?  If it's a version prior to 1.6, you can try adding an Application_Error() handler into the Global.asax file (in the root folder).  In this post, I posted some code on April 23rd that has an Application_Error() handler you can use.  If you add that to your global.asax file, then you should hopefully get a real error message, rather than those garbage characters.

Also, for debugging purposes, I would make sure the custom errors tag in the web.config file is set to Off:

<customErrors mode="Off">

Jul 15, 2010 at 12:14 PM
[off topic]Why do I sometimes get the option to format text here (at top of editor), but most of time not. See my previous post that contained HTML, it is unreadable, but it wasn't when I posted. [/off topic] Thanks for answering again Ben, you are my only hope in solving this... I am using version 1.6. I will change the setting for customErrors and see what happens and report back.
Jul 15, 2010 at 12:19 PM

I've had the same problem a couple of times with the Discussions editor here -- where the WYSIWYG controls are missing.  Last time it happened to me ( 2 days ago ), I wrote CodePlex and they said they had done an update and tested their changes with every major browser.  I think it's some caching problem, because when I cleared all of browser's cache, the WYSIWYG toolbar came back.  CodePlex has a number of inconvenient issues like this.

If you're using BE 1.6, you might want to try the opposite -- that is, remove the Application_Error() handler from the global.asax file.  I've seen a couple of times where that code is for some reason producing an unhandled error that results in the garbage characters.  So you could try removing the Application_Error() handler and also setting the customErrors tag.

Jul 15, 2010 at 12:33 PM
Clearing cache didn't help... Maybe I should just use a different browser for Codeplex... Anyway, The line in web.config contained this text: <customErrors mode="RemoteOnly" defaultRedirect="~/error404.aspx"> I changed it to; <customErrors mode="Off"> After putting the XML file in the directory, I got a real error message (that I had seen earlier) and one of the lines it said that the GUID was not valid and it should containt 4 dashes. The GUID was online generated and looks like this: f7adfab5-228b-4488-8ac1-d7f5cd87e38 Not sure what is wrong with that... I now have commented out the Application_Error handler in the global.asax-file... Let's see what that does.
Jul 15, 2010 at 12:40 PM
Ok, it turns out that my GUID was not correct. It missed a character... It seems to be solved now... Will report back in a few days... Ben, thanks for your help so far. This was clearly my mistake, although I checked the GUID length a couple of times, this seems to have been the culprit.