latest posts

Apr 28, 2013

After wrapping up Phase One of my migration from WordPress to MVC4, I began diving into the admin side of the migration trying to replicate a lot of ease of use WordPress offered while adding my own touches. To begin I started with the Add/Edit Post form.

Sure enough immediately following adding the route, the form posted back properly and I was back at work on adding additional functionality to the backend. Hopefully that helps someone else out as I only found one unanswered StackOverflow post on this issue.
I should also note, a handy feature when utilizing Output Caching as discussed in a previous post is to programmatically reset the cache.

Apr 21, 2013

Search Functionality

A few common approaches to adding search functionality to a Web Application:

Web App Search Approaches

Pull down all of the data and then search on it using a for loop or LINQ - An approach I loathe because to me this is a waste of resources, especially if the content base you're pulling from is of a considerable amount. Just ask yourself, if you were at a library and you knew the topic you were looking for, would you pull out all of the books in the entire library and then filter down or simply find the topic's section and get the handful of books?

Implement a Stored Procedure with a query argument and return the results - An approach I have used over the years, it is easy to implement and for me it leaves the querying where it should be - in the database.

Creating a Search Class with a dynamic interface and customizable properties to search and a Stored Procedure backend like in Approach 2 - An approach I will be going down at a later date for site wide search of a very large/complex WebForms app.

For the scope of this project I am going with Option #2 since the scope of the content I am searching for only spans the Posts objects. At a later date in Phase 2 I will probably expand this to fit Option #3. However since I will want to be able to search on various objects and return them all in a meaningful way, fast and efficiently.
So let's dive into Option #2. Because the usage of virtually the same block of SQL is being utilized in many Stored Procedures at this point, I created a SQL View:
[sql]
CREATE VIEW dbo.ActivePosts
AS
SELECT
dbo.Posts.ID,
dbo.Posts.Created,
dbo.Posts.Title,
dbo.Posts.Body,
dbo.Users.Username,
dbo.Posts.URLSafename,
dbo.getTagsByPostFUNC(dbo.Posts.ID) AS 'TagList',
dbo.getSafeTagsByPostFUNC(dbo.Posts.ID) AS 'SafeTagList',
(SELECT COUNT(*) FROM dbo.PostComments WHERE dbo.PostComments.PostID = dbo.Posts.ID AND dbo.PostComments.Active = 1) AS 'NumComments'
FROM dbo.Posts
INNER JOIN dbo.Users ON
dbo.Users.ID = dbo.Posts.PostedByUserID
WHERE dbo.Posts.Active = 1
[/sql]
And then create a new Stored Procedures with the ability to search content and reference the new SQL View:
[sql]
CREATE PROCEDURE [dbo].[getSearchPostListingSP]
(@searchQueryString VARCHAR(MAX))
AS
SELECT
dbo.ActivePosts.*
FROM dbo.ActivePosts
WHERE
(dbo.ActivePosts.Title LIKE '%' + @searchQueryString + '%' OR
dbo.ActivePosts.Body LIKE '%' + @searchQueryString + '%')
ORDER BY dbo.ActivePosts.Created DESC
[/sql]
You may be asking why not simply add the ActivePosts SQL View to your Entity Model and do something like this in your C# code:

That's perfectly valid and I am not against doing it that, but I feel like code like that should be done at the Database level, thus the Stored Procedure. Granted Stored Procedures do add a level of maintenance over doing it via code. For one, anytime you update/add/remove columns you have to update the Complex Typein your Entity Model inside of Visual Studio and then update your C# code that makes reference to that Stored Procedure.
For me it is worth it, but to each their own. I have not made performance comparisons on this particular scenario, however last summer I did do some aggregate performance comparisons between LINQ, PLINQ and Stored Procedures in my in C#">LINQ vs PLINQ vs Stored Procedure Row Count Performance in C#. You can't do a 1 to 1 comparison between varchar column searching and aggregate function performance, but my point, or better put, my lesson I want to convey is to definitely keep an open mind and explore all possible routes. You never want to find yourself in a situation of stagnation in your software development career simply doing something because you know it works. Things change almost daily it seems - near impossible as a polyglot programmer to keep up with every change, but when a new project comes around at work do your homework even if it means sacrificing your nights and weekends. The benefits will become apparent instantly and for me the most rewarding aspect - knowing when you laid down that first character in your code you did so with the knowledge of what you were doing was the best you could provide to your employer and/or clients.
Back to implementing the Search functionality, I added the following function to my PostFactory class:

When all was done:
[caption id="attachment_2078" align="aligncenter" width="252"]in MVC App" width="252" height="171" class="size-full wp-image-2078" /> Search box in MVC App[/caption]
Now you might be asking, what if there are no results?
Your get an empty view:
[caption id="attachment_2079" align="aligncenter" width="300"] Empty Result - Wrong way to handle it[/caption]
This leads me to my next topic:

Custom Error Pages

We have all been on sites where we go some place we either don't have access to, doesn't exist anymore or we misspelled. WordPress had a fairly good handler for this scenario:
[caption id="attachment_2081" align="aligncenter" width="300"] WordPress Content not found Handler[/caption]
As seen above when no results are found, we want to let the user know, but also create a generic handler for other error events.
To get started let's add a Route to the Global.asax.cs:

Now you maybe asking why isn't the actual error going to be passed into the Controller to be displayed?
For me I personally feel a generic error message to the end user while logging/reporting the errors to administrators and maintainers of a site is the best approach. In addition, a generic message protects you somewhat from exposing sensitive information to a potential hacker such as "No users match the query" or worse off database connection information.
That being said I added a wrapper in my BaseController:

This wrapper will down the road record the error to the database and then email users with alerts turned on. Since I haven't started on the "admin" section I am leaving it as is for the time being. The reason for the argument being there currently is that so when that does happen all of my existing front end code is already good to go as far as logging.
Now that I've got my base function implemented, let's revisit the Search function mentioned earlier:

Optimization

You might be wondering why I left optimization for last? I feel as though premature optimization leads to not only a longer debugging period when nailing down initial functionality, but also if you do things right as you go on your optimizations are really just tweaking. I've done both approaches in my career and definitely have had more success with doing it last. If you've had the opposite experience please comment below, I would very much like to hear your story.
So where do I want to begin?

YSlow and MVC Bundling

For me it makes sense to do the more trivial checks that provide the most bang for the buck. A key tool to assist in this manner is YSlow. I personally use the Firefox Add-on version available here.
As with any optimization, you need to do a baseline check to give yourself a basis from which to improve. In this case I am going from a fully featured PHP based CMS, WordPress to a custom MVC4 Web App so I was very intrigued by the initial results below.
[caption id="attachment_2088" align="aligncenter" width="300"] WordPress YSlow Ratings[/caption]
[caption id="attachment_2089" align="aligncenter" width="300"] Custom MVC 4 App YSlow Ratings[/caption]
Only scoring 1 point less than the battle tested WordPress version with no optimizations I feel is pretty neat.
Let's now look into what YSlow marked the MVC 4 App down on.
In the first line item, it found that the site is using 13 JavaScript files and 8 CSS files. One of the neat MVC features is the idea of bundling multiple CSS and JavaScript files into one. This not only cuts down on the number of HTTP Requests, but also speeds up the initial page load where most of your content is subsequently cached on future page requests.
If you recall going back to an earlier post our _Layout.cshtml we included quite a few CSS and JavaScript files:

Now after re-running the YSlow test:
[caption id="attachment_2092" align="aligncenter" width="300"]in the MVC App" width="300" height="190" class="size-medium wp-image-2092" /> YSlow Ratings after Bundling of JavaScript Files in the MVC App[/caption]
Much improved, now we're rated better than WordPress itself. Now onto the bundling of the CSS styles.
Add the following below the previously added ScriptBundles in your BundleConfig class:

One thing that I should note is if your Bundling isn't working check your Routes. Because of my Routes, after deployment (and making sure the is set to false), I was getting 404 errors on my JavaScript and CSS Bundles.
My solution was to use the IgnoreRoutes method in my Global.asax.cs file:

MVC Caching

Now that we've reduced the amount of data being pushed out to the client and optimized the number of http requests, lets switch gears to reducing the load on the server and enhance the performance of your site.
Without diving into all of the intricacies of caching, I am going to turn on server side caching, specifically Output Caching. At a later date I will dive into other approaches of caching including the new HTML5 client side caching that I recently dove into.
That being said, turning on Output Caching in your MVC application is really easy, simply put the OutputCache Attribute above your ActionResults like so:

In this example, the ActionResult will be cached for one hour (3600 seconds = 1 hour) and by setting the VaryByParam to * that means each combination of arguments passed into the function is cached versus caching one argument combination and displaying the one result. I've seen developers simply turn on caching and not thinking about dynamic content - suffice it to say, think about what could be cached and what can't. Common items that don't change often like your header or sidebar can be cached without much thought, but think about User/Role specific content and how bad it would be for a "Guest" user to see content as a Admin because an Admin had accessed the page within the cache time before a Guest user had.

Conclusion

In this post I went through the last big three items left in my migration from WordPress to MVC: Search Handling, Custom Error Pages and Caching. That being said I have a few "polish" items to accomplish before switching over the site to all of the new code, namely additional testing and adding a basic admin section. After those items I will consider Phase 1 completed and go back to my Windows Phone projects.
Stay tuned for Post 9 tomorrow night with the polish items.

Apr 20, 2013

Can't believe it's been a week to the day when I began this project, but I am glad at the amount of progress I have made on the project thus far. Tonight I will dive into adding a WCF Service to act as a layer in between the logic and data layer done in previous posts Part 1, Part 2, Part 3, Part 4, Part 5 and Part 6) and add adding RSS support to the site.

Integrating a WCF Service

First off, for those that aren't familiar, WCF (Windows Communication Foundation) is an extremely powerful Web Service Technology created by Microsoft. I first dove into WCF April 2010 when diving into Windows Phone development as there was no support for the "classic" ASMX Web Services. Since then I have used WCF Services as the layer for all ASP.NET WebForms, ASP.NET MVC, Native Mobile Apps and other WCF Services at work since. I should note, WCF to WCF communication is done at the binary level, meaning it doesn't send XML between the services, something I found extremely enlightening that Microsoft implemented.
At it's most basic level a WCF Service is comprised of two components, the Service Interface Definition file and the actual implementation.
In the case of the migration, I created my Interfaceas follows:

The one thing to note, IsOneWay a top of the AddComment function indicates, the client doesn't expect a return value. As noted in last night's post, the end user is not going to want to wait for all the emails to be sent, they simply want their comment to be posted and the Comment Listing refreshed with their comment. By setting the IsOneWay to true, you ensure the client's experience is fast no matter the server side work being done.
And the actual implementation:

One thing you might be asking, isn't this a security risk? If you're not, you should. Think about it, anyone who has access to your WCF Service could add comments and pull down your data at will. In its current state, this isn't a huge deal since it is only returning data and the AddComment Operation Contract requires a prior approved comment to post, but what about when the administrator functionality is implemented? You definitely don't want to expose your contracts to the outside world with only the parameters needed.
So what can you do?

Keep your WCF Service not exposed to the internet - this is problematic in today's world where a mobile presence is almost a necessity. Granted if one were to only create a MVC 4 Mobile Web Application you could keep it behind a firewall. My thought process currently is design and do it right the first time and don't corner yourself into a position where you have to go back and do additional work.

Add username, password or some token to the each Operation Contract and then verify the user - this approach works and I've done it that way for public WCF Services. The problem becomes more of a lot of extra work on both the client and server side. Client Side you can create a base class with the token, username/password and simply pass it into each contract and then server side do a similar implementation

Implement a message level or Forms Membership - This approach requires the most upfront work, but reaps the most benefits as it keeps your Operation Contracts clean and offers an easy path to update at a later date.

Going forward I will be implementing the 3rd option and of course I will document the process. Hopefully this help get developers thinking about security and better approaches to problems.
Moving onto the second half of the post, creating an RSS Feed.

Creating an RSS Feed

After getting my class in my WCF Service, I created a new Stored Procedure in preparation:
[sql]
CREATE PROCEDURE dbo.getRSSFeedListSP
AS
SELECT
TOP 25
dbo.Posts.Created,
dbo.Posts.Title,
LEFT(CAST(dbo.Posts.Body AS VARCHAR(MAX)), 200) + '...' AS 'Summary',
dbo.Posts.URLSafename
FROM dbo.Posts
INNER JOIN dbo.Users ON
dbo.Users.ID = dbo.Posts.PostedByUserID
WHERE dbo.Posts.Active = 1
ORDER BY dbo.Posts.Created DESC
[/sql]
Basically this will return the most recent 25 posts and up to the first 200 characters of the post.
Afterwards I created a class to translate the Entity Framework Complex Type:

Now I am going to leave it up to you which path to implement. At this point you've got all backend work done to return the data you need to write your XML file for RSS.
There are many approaches to how you want to go about to proceeding, and it really depends on how you want to serve your RSS Feed. Do you want it to regenerate on the fly for each request? Or do you want to write an XML file only when a new Post is published and simply serve the static XML file? From what my research gave me, there are multiple ways to do each of those. For me I am in favor of doing the work once and writing it out to a file rather than doing all of that work on each request. The later seems like a waste of server resources.
Generate Once

One being using the Typed DataSet approach I used in Part 1 - requires very little work and if you're like me, you like a strongly typed approach.

Another option is to use the SyndicationFeed built in class to create your RSS Feed's XML - an approach I hadn't researched prior to for generating one

Using the lower level XmlWriter functionality in .Net to build your RSS Feed's XML - I strongly urge you to not do this with the 2 approaches above being strongly typed. Unstrongly Typed code leads to spaghetti and a debugging disaster when something goes wrong.

Generate On-Thee-Fly

Use the previously completed WCF OperationContract to simply return the data and then use something like MVC Contrib to return a XmlResultin your MVC Controller.

Set your MVC View to return XML and simply iterate through all of the Post Items

Those are just some ways to accomplish the goal of creating a RSS Feed for your MVC site. Which is right? I think it is up to you to find what works best for you. That being said, I am going to walk through how to do the first 2 Generate Once Options.
For both approaches I am going to use IIS's UrlRewrite functionality to route http://www.jarredcapellman.com/feed/ to http://www.jarredcapellman.com/rss.xml.
For those interested, all it took was the following block in my web.configin the System.WebService section:
[xml]
<rewrite>
<rules>
<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
<match url="^feed$" />
<conditions>
<add input="{
&nbsp&nbsp REQUEST_FILENAME}
" matchType="IsFile" negate="true" />
<add input="{
&nbsp&nbsp REQUEST_FILENAME}
" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="rss.xml" />
</rule>
</rules>
</rewrite>
[/xml]
To learn more about URL Rewrite go the official site here.

Option 1 - XSD Approach

Utilizing a similar approach to how I got started, utilizing the XSD tool in Part 1, I generated a typed dataset based on the format of an RSS XML file:
[xml]
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Jarred Capellman</title>
<link>http://www.jarredcapellman.com</link>
<description>Putting 1s and 0s to work since 1995</description>
<language>en-us</language>
<item>
<title>Version 2.0 Up!</title>
<link>http://www.jarredcapellman.com/2002/05/04/version-2-0-is-up/</link>
<description>Yeah in all its glory too, it's far from complete, the forum will be up tonight most likely...</description>
<pubDate>5/4/2012 12:00:00 AM</pubDate>
</item>
</channel>
</rss>
[/xml]
[caption id="attachment_2056" align="aligncenter" width="300"]for RSS" width="300" height="151" class="size-medium wp-image-2056" /> Generated Typed Data Set for RSS[/caption]
Then in my HomeController, I wrote a function to handle writing the XML to be called when a new Post is entered into the system:

Pretty intuitive code with one exception - I could not find a way to add the version property to the rss element, thus having to use the GetXml() method and then do a more elaborate solution instead of simply calling dt.WriteXml(HttpContext.Server.MapPath("~/rss.xml")).
Overall though I find this approach to be very acceptable, but not perfect.

Option 2 - Syndication Approach

Not 100% satisfied with the XSD Approach mentioned above I dove into the SyndicationFeed class.
Be sure to include using System.ServiceModel.Syndication; at the top of your MVC Controller.
I created the same function as above, but this time utilizing the SyndicationFeedclass that is built into .NET:

On first glance you might notice very similar code between the two approaches, with one major exception - there's no hacks to make it work as intended.
Between the two I am going to go live with the later approach, not having to worry about the String.Replace ever failing and not having any "magic" strings is worth it. But I will leave the decision to you as to which to implement or maybe another approach I didn't mention - please comment if you have another approach. I am always open to using "better" or alternate approaches.
Now that the WCF Service is fully integrated and RSS Feeds have been added, as far as the end user view there are but a few features remaining: Caching, Searching Content, Error Pages.
Stay tuned for Part 8 tomorrow.

Apr 18, 2013

Nearing the end of my initial migration now in Part 6, I dove into Comment Listing, Adding New Comments and then emailing users a new comment was entered. (Other Posts: Part 1, Part 2, Part 3, Part 4 and Part 5).
In Part 5, I imported the Comments, but wasn't doing anything but showing the Comment Count in the Post Title. In this post I will begin with what I did to display the comments.
First off I added a new column to my PostComments to handle those Comments that were not approved or are pending approval (thinking about spam bots in particular). After adding that new column, I created a Stored Procedure to return the Comments for a given Post, some (maybe most) might find creating a Stored Procedure to simply return one Table is unnecessary, but I find it helps keep my C# much cleaner by adding that layer between my SQL Database and my C# code.
[sql]
CREATE PROCEDURE [dbo].[getPostCommentsSP]
(@PostID INT)
AS
SELECT
dbo.PostComments.Modified,
dbo.PostComments.Body,
dbo.PostComments.Name
FROM dbo.PostComments
WHERE dbo.PostComments.PostID = @PostID AND
dbo.PostComments.IsApproved = 1 AND
dbo.PostComments.Active = 1
[/sql]
I proceeded to add a new function in my PostFactory to return the converted List collection:

Since the main listings do not display the Comments, just the count, it was necessary to have a unique ActionResult.
That being said, I did reuse my PartialView I created the other night, only adding to it:

Because the Comments are otherwise null I can reuse the PartialView.
After adding in all of the CSS Styles:
[caption id="attachment_2039" align="aligncenter" width="300"]in MVC4 Site" width="300" height="165" class="size-medium wp-image-2039" /> Comments Listing in MVC4 Site[/caption]
Next on the list of things I wanted to accomplish is adding a form below the Comments Listing.
Adding a pretty basic form for web developers is pretty trivial, however here is the code I am using:

A feature of WordPress I realized I enjoyed was the fact it emailed me when a new comment was entered in the system. So I figured I would add the same functionality to my MVC app. One thing I should note, this is far from ideal code. Think of a larger site, with hundreds or thousands of comments from users. The user would have to wait until all of the emails were sent and then return the user to the post they added their comment to. A better approach would be to offload this potentially long running task to a Windows Service - a feature I will be adding shortly.

So what is next? Implementing the WCF Service previously mentioned and the Windows Service mentioned above. This will allow me to easily create Windows Phone 8, Windows 8 Store apps or heck even a command line version if there was demand. More to come...

Apr 17, 2013

Continuing onto Part 5 of my migration from WordPress to MVC 4, I dove into Content, Comments and Routing tonight. (Other Posts: Part 1, Part 2, Part 3 and Part 4).
First thing I did tonight was add a new route to handle pages in the same way WordPress does (YYYY/MM/DD/) for several reasons, though my primary reason is to retain all of the links from the existing WordPress site - something I'd highly suggest you consider doing as well.
As noted the other night, your MVC Routing is contained in your Global.asax.cs file. Below is the route I added to accept the same format as WordPress:

Be sure to put it before the Default Route otherwise the route above will not work.
After I got the Route setup, I went back into my _Layout.cshtml and updated the header links to pull from a SQL Table and then return the results to the layout:

Further down the road I plan to add a UI interface to adjust the menu items, thus the need to make it programmatic from the start.
Next on the list was actually importing the content from the export functionality in WordPress. Thankfully the structure is similar to the actual posts so it only took the following code to get them all imported:

After getting the Comments Count displayed I wanted to do some refactoring on the code up to now. Now that I've got a pretty good understanding of MVC architecture I started to create Base objects. The commonly pulled in data for instance (Tag Cloud, Menu Items, Archive List etc.) I now have in a BaseModel and pulled in a BaseController. After which all Controllers inherit. I cut down on a good chunk of code and feel pretty confident as time goes on I will be able to expand upon this baseline architecture very easily.
[caption id="attachment_2032" align="aligncenter" width="300"]as of Part 5" width="300" height="115" class="size-medium wp-image-2032" /> Migration Project as of Part 5[/caption]
So what is on the plate next? Getting the Comments displayed, the ability to post new comments and in the back end email people upon a new comment being entered for a particular post.

Apr 15, 2013

Continuing onto Day 4 of my Migration to MVC 4 (Part 1, Part 2 and Part 3) contrary to what I suggested I would focus on last night, I dove into getting all of the MVC Routing in place so the site could start functioning like my existing WordPress site does.
Having only been really doing MVC for a month in half in between MonoDroid, MonoTouch and Windows Phone I hadn't had time to really dive into Routing, which I had been excited about implementing in a future project. One of the first hurdles I ran into was leaving the default routing in place. Frustratingly this caused all of my new routes to not be processed correctly, keep that in mind when you first dive into MVC.
For those also early on in their MVC Path, your routing is defined in the Global.asax.cs file.
Your default route is defined in the RegisterRoutes function:

I took it one step further by forcing the year parameter to be a number. To make use of the this route, just make sure your controller, Home has an ActionResult called Posts with both a year and month parameters like so:

So now that the routing is working like I wanted tomorrow night is a focus on getting the content pages imported, routed and displayed properly.
Being the planner I am, I figured I would map out the next few evenings:

Apr 14, 2013

Continuing my series on Migrating from WordPress to MVC4 (Part 1 and Part 2). Today I worked on getting the right hand side bar and importing Tags from the export mentioned in Part 1.
Where did I begin?
Based on the original import I made last Friday night, I created a Stored Procedure to create the right hand side "Archives List", for those curious here is the SQL:
[sql]
SELECT
DATEPART(YEAR, dbo.Posts.Created) AS 'PostYear',
DATENAME(MONTH, dbo.Posts.Created) AS 'PostMonth',
(SELECT COUNT(*) FROM dbo.Posts postsCount WHERE DATENAME(MONTH, postsCount.Created) = DATENAME(MONTH, dbo.Posts.Created) AND
DATEPART(YEAR, postsCount.Created) = DATEPART(YEAR, dbo.Posts.Created) AND postsCount.Active = 1) AS 'NumPosts'
FROM dbo.Posts
WHERE dbo.Posts.Active = 1
GROUP BY DATENAME(MONTH, dbo.Posts.Created), DATEPART(YEAR, dbo.Posts.Created)
ORDER BY DATEPART(YEAR, dbo.Posts.Created) DESC, DATENAME(MONTH, dbo.Posts.Created)
[/sql]
And then in the UI:

After all is said and done (also included are the SQL stored Links):
[caption id="attachment_2004" align="aligncenter" width="100"] Archived List and Links List[/caption]
At this point I needed to do a re-import of the data as I had only imported the Posts. In addition I added support to import the Categoriesfor Posts while I was at it.
If you're referencing the code in this series I added the following block immediately after the Post row is added. This block parses and imports the Tags and Categories:

Now that the Tags and Categories are imported into the SQL Server, I wanted to recreate the Tag Cloud feature that WordPress offers and Telerik offers in their ASP.NET WebForms Suite. At a base level all a Tag Cloud really does is based on the highest count of items, create a larger link of the Tag and get decreasingly smaller as the occurrences decrease.
So for those only here to check out how I accomplished it, let's dive in.
First I created a Stored Procedure to get the Top 50 used Tags:
[sql]
SELECT
TOP 50 (SELECT COUNT(*) FROM dbo.Posts2Tags WHERE dbo.Posts2Tags.TagID = dbo.Tags.ID) AS 'NumTags',
dbo.Tags.Description
FROM dbo.Tags
WHERE dbo.Tags.Active = 1
ORDER BY (SELECT COUNT(*) FROM dbo.Posts2Tags WHERE dbo.Posts2Tags.TagID = dbo.Tags.ID) DESC, dbo.Tags.Description ASC
[/sql]
And then in my Controller in the MVC 4 App:

After implementing the SQL, CSS and HTML I got it working just as I wanted:
[caption id="attachment_2008" align="aligncenter" width="116"] bbxp TagCloud[/caption]
Next up on the list is to import the comments, display them and create a comments form.

Apr 13, 2013

Continuing from last night's post, Part 1 of Migrating WordPress to MVC4 I spent some time today working on the visual display of the migrated posts. Like most programmers using WordPress, I utilize the excellent Syntax Highlighter JavaScript/CSS library for all of my code blocks. The caveat with this, those tags now exist all throughout my posts going back a year or more at this point. Luckily, my Regular Expression skills have gone up considerably with projects like my Windows Phone 8 app, jcCMAP that utilizes XPath and Regular Expressions extensively.
So where do you begin?
Like many migrations you have a choice, do you migrate the data as is into the new structure or do you manipulate, like in this case with the tags, the actual tags into something that is preprocessed?
Being a firm believer in storing data in as bare of a form as possible and then in my business and presentation layers worrying about the UI, I am choosing to leave the tags as they exist. Luckily, the tags follow a very easy to parse syntax with brackets and the name of the language.
First steps from last night were to do some refactorization of the Data Layer and split it into a true 3 tier architecture.
I first created a PostFactoryclass to interface with the EntityFramework in my Windows Class Library:

This block grabs all of the posts for a given date range from the getPostListingSP Stored Procedure and then using LINQ does a translation to a Postobject that resides in my PCL library. The Postobject exists in the Portable Class Library (PCL) to be utilized by the MVC4 app and the eventual Windows Phone 8 app. Planning ahead and doing things right from the get go will save you time - don't rush your initial architecture, you'll pay for it later.
Next I create my Post Object that encapsulates the properties I want exposed to the clients (MVC4 App and Windows Phone). Some might find it silly to not simply reuse the EntityFramework Complex Type object that the stored procedure mentioned above returns. I find that approach to be a lack of separation of concerns and crossing tiers between the data and UI layers. For a simple site I might overlook it, but for 99% of the things I do, I always have an object that acts as a middle man between the data and UI layers.
Now onto the code:

Pretty stock code, the only "interesting" code is the regular expression to grab all of the SyntaxHighlighter. For those doing Regular Expressions, I find it incredibly useful to use a tool like Regex Hero to build your Regular Expressions since you can test input on the fly without having to constantly rebuild your code and test.
Next on the "to code" list was the SyntaxTag object.

Again, a pretty basic class. Based on the full tag, it provides a clean interface to the Postclass (or others down the road) without mucking up other areas of code. One thing I did do that many might find strange is to use an enumeration to eliminate false positives. I am a huge fan of strongly typed code (thus why I shy away from languages that aren't) so it made perfect sense to again utilize this approach. As I utilize new tags for whatever reason, the logic is contained only here so I won't be hunting around for where to update it. Another less "clean" approach would be to put these in the web.config or in your SQL Database. Though I find both of those more performance intensive and not necessary in this case.
Now that the business and data layers are good to go for the time being, let's go back to our MVC4 App.
Inside my controller the code is pretty simple still for my Index:

At the moment I don't have my WCF Service written yet so for the time being I am simply referencing the Windows Class Library mentioned above, thus why I am referencing the PostFactoryclass directly in the Controller.
Then in my View:

The @(new MvcHtmlString(@Model.Body)) line is very important otherwise your HTML Tags will not be parsed as you would expect.
When all is said and done I went from this last night:
[caption id="attachment_1982" align="aligncenter" width="300"] End Result of an Initial Conversion[/caption]
To this tonight:
[caption id="attachment_1992" align="aligncenter" width="300"] After applying regular expressions to the Post Content[/caption]
Next up is creating the WordPress Sidebar History and extending functionality of the "engine" to support single Post Views.

Apr 12, 2013

In working on a new MVC4 app in my free time I had renamed the original assembly early on in development, did a clean solution, yet kept getting:

Multiple types were found that match the controller named XYZ. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request.

Turns out, since the project name changed, doing a clean solution had zero effect. So the quick and easy solution: go to your bin folder and delete the original dll.

Mar 06, 2013

Diving into MVC 4 this week and going through the default Kendo UI MVC 4 project type in Visual Studio 2012 I noticed quite a few assemblies I knew I wouldn't need for my current project, namely the DotNetOpenAuth assemblies.
I removed the 6 DotNetOpenAuth.* assemblies:
[caption id="attachment_1890" align="aligncenter" width="304"] MVC 4 Assemblies[/caption]
In addition you'll need to remove the Microsoft.Web.WebPages.OAuth reference as well.
To my surprise, upon building and debugging the new project I received the following exception:
[caption id="attachment_1891" align="aligncenter" width="550"] MVC 4 Exception - DotNetOpenAuth Not Found[/caption]
I double checked my packages.config and web.config config files for any reference, to no avail. As a last resort I deleted my bin and obj folders, rebuilt the solution and sure enough it started without any issues.
Hopefully that helps someone out.