<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ASP.Net</title>
	<atom:link href="http://www.aspnet-mvc-info.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.aspnet-mvc-info.com</link>
	<description>Developing web applications with Asp.Net</description>
	<lastBuildDate>Thu, 12 Apr 2012 08:54:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Developing Tridion 2011 .Net component templates</title>
		<link>http://www.aspnet-mvc-info.com/2012/04/developing-net-component-templates-for-tridion-2011/</link>
		<comments>http://www.aspnet-mvc-info.com/2012/04/developing-net-component-templates-for-tridion-2011/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 18:09:12 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Tridion 2011]]></category>
		<category><![CDATA[Tridion templating]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=366</guid>
		<description><![CDATA[Recently i had the opportunity to develop component templates for a Tridion 2011 implementation. In this article I want to share my thought on the new templating features, provide quick tips and wrap up with some templating limitations that should be addressed in future versions of Tridion. My previous Tridion component template development experience is [...]]]></description>
			<content:encoded><![CDATA[<p>Recently i had the opportunity to develop component templates for a Tridion 2011 implementation. In this article I want to share my thought on the new templating features, provide quick tips and wrap up with some templating limitations that should be addressed in future versions of Tridion.</p>
<p>My previous Tridion component template development experience is all based on VBscript and the templating features from Tridion 5.3. Since I have plenty experience with .Net development I was confident the switch to Tridion 2011 template development would be a smooth one. It's worth mentioning that I only developed component templates since the implementation used a dynamic publishing model (only component presentation xml is published to the database). The overall experience with the new templating features was very positive, the biggest improvements that I would like to point out:</p>
<ul>
<li>Better productivity because of the ability to work with Visual Studio, a professional IDE which offers syntax highlighting, code completion and other nifty tools that increase developer productivity.</li>
<li>Faster bug fixing because of remote debugging and the logging functionality offered by the Tridion libraries.</li>
</ul>
<p>The overall improvement of the template development experience has been quite substantial for me, being able to use a full fletched IDE and having decent debugging options makes a world of difference to me and my productivity as a developer.</p>
<h2>Tridion .Net templating quick tips</h2>
<p>When getting started with .Net template development there are some things you should look at, as they will have a positive effect on productivity and possibly save some frustration:</p>
<ul>
<li>If you have the possibility, install Visual Studio on the same machine as the Tridion Content Manager Server. This allows for easier remote debugging of you templates without the risk of network/domain component causing issues and leaving you unable to use remote debugging. If you are unable to get remote debugging working on the customer network and you cannot install Visual Studio on the Tridion Content Manager, consider setting up a separate development environment where you can, cause debugging will boost productivity greatly. There is documentation on how to get remote debugging working on <a href="http://sdllivecontent.sdl.com/LiveContent/">SDL live content</a>.</li>
<li>Download the <a href="http://www.sdltridionworld.com/community/2011_extensions/AssemblyUploader2.aspx">AssemblyUploader2</a> plugin for Visual Studio, this plugin allows for fast uploading of dll files into Tridion, having this plugin will save you a lot of manual and repetitive upload tasks.</li>
<li>Making the switch from VBscript to .Net I needed to get familiar with the new TOM.Net API. There are two things which make this process easier and faster. The most important thing to obtain the Tridion 2011 SP1 TOM.Net API documentation provided by Tridion. Use the Visual Studio object browser to quickly nagivate the Tridion libraries and see what functionality they expose.</li>
</ul>
<h2>Tridion .Net templating limitations</h2>
<p>As stated in the introduction, there are some limitations to the Tridion .Net template development which I encountered during the project.</p>
<ul>
<li>The most noticeable for me is the limited support for automated testing. Tridion classes used for templating are not testable making it harder to isolate code for testing. During training at Tridion the trainer did mention that Tridon will look at this for future versions.</li>
<li>A limitation worth mentioning is that all templating code has to be uploaded to Tridion in a single dll file, so all the code has to be maintained within one Visual Studio project. I found this out the hard way: Template execution failed when I referenced a second project which contained utility/support classes while both dll files where unloaded into Tridion correctly. This limitation can be frustrating when you want to reuse code from utility/support classes which reside within a different project. Fortunately there is a workaround for this limitation. Visual Studio offers the choice to add classes from a different project to the current project as a link. This way you can use the code from other projects within you templating project without duplicating the code.</li>
</ul>
<h2>Wrapping up</h2>
<p>Tridion still supports VBscript templates, the reason is simple: upgrading Tridion should not break any existing templates and implementations. Even though VBscript is not officially deprecated I strongly recommend making the switch to .Net development for your next template development project. The reason is simple, the switch has to be made sometime, better make it soon and start seeing the benefits of the new .Net template development features for yourself.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2012/04/developing-net-component-templates-for-tridion-2011/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Telligent Community 6.0 custom caching</title>
		<link>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-custom-caching/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-custom-caching/#comments</comments>
		<pubDate>Fri, 16 Sep 2011 22:15:43 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Telligent Community 6.0]]></category>
		<category><![CDATA[Velocity script]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=339</guid>
		<description><![CDATA[In this article I will be briefly describing a custom caching approach which I developed for custom Telligent Community 6.0 widgets. Understanding caching and anticipating issues with cache is important to keep the load time of widgets and pages in check. Widgets within Telligent are cached for five seconds out-of-the-box. This is a balance between [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I will be briefly describing a custom caching approach which I developed for custom Telligent Community 6.0 widgets. Understanding caching and anticipating issues with cache is important to keep the load time of widgets and pages in check.</p>
<p>Widgets within Telligent are cached for five seconds out-of-the-box. This is a balance between performance gains by not having to re-evaluate the widget code and preventing the content of the widget becoming stale. While the five second cache is fine for most widgets out there, there are some widgets which may require additional caching to reduce load. Examples are widgets that perform many expensive database queries or connect to external API’s.</p>
<p>To illustrate how many expensive database queries can cause high load times for widgets I will describe a widget a recently developed for a client. This custom widget provides an overview of the amount of content within the community to give the user an indication of how active the groups within the community are. The community has ten groups, with a total of fifty sub groups. These groups contain roughly five hundred threads and twenty-five hundred replies. Querying all this content causes high load on the database server and increases load time for the widget. We remedied this problem by enhancing the caching. While this is not the only possible form of improvement, this article will only discuss caching.</p>
<p>There are two approaches known to me to increase caching within Telligent. The first approach is changing the standard Telligent caching through the caching.config. For more information see the <a title="Telligent caching documentation" href="http://telligent.com/support/telligent_evolution_platform/community/w/community6/caching-configuration.aspx" target="_blank">documentation</a>. I would like to point out that changes to the standard Telligent caching effect everything that is put into the cache. If you require only a portion of the widgets to be cached for a longer period of time, changing the standard Telligent caching probably yields undesirable results in other parts of the community.</p>
<p>The second approach requires customization through an extension, but you can achieve a more fine grained control over caching than you can with changing the standard caching. If you want to cache a portion of the widgets for ten minutes, and leave the rest on the standard five second caching, this approach is the way to go. If this is your first time writing an extension for Telligent Community 6.0, <a title="Telligent Community 6.0 widget development" href="http://blog.building-blocks.com/2011/08/creating-an-iscriptedcontentfragmentextension-for-use-in-telligent-enterprise-3-0-widgets" target="_blank">this</a> article by Adam Seabridge is a good read. Basically what we want to do is write our own extension to handle caching for us and enable us to determine how long an object remains in the cache. The extension will look like this:</p>
<pre class="brush:csharp">using System;

using Telligent.Evolution.Extensibility.Caching.Version1;

namespace KvKVelocityScriptExtensions
{

    public class CachingVelocityScriptExtensions : Telligent.Evolution.Extensibility.UI.Version1.IScriptedContentFragmentExtension
    {

        public string Name
        {
            get { return "KvK Cache Extension Plugin"; }
        }

        public string ExtensionName
        {
            get { return "KvKCachingExtension"; }
        }

        public string Description
        {
            get { return "Caching Extension Class For Use In Custom Widgets"; }
        }

        public void Initialize()
        {
            //stuff here;
        }

        public object Extension
        {
            //pass back an instance of the TwitterService which exposes the methods
            get { return new CachingService(); }
        }
    }

    public class CachingService
    {
        #region GroupStatistics

        public const string KvKGroupListWidgetCacheKeyPrefix = "KVKGROUPLISTWIDGET{0}";

        public GroupStatistics GetGroupStatistics(int groupId)
        {
            string cacheKey = string.Format(KvKGroupListWidgetCacheKeyPrefix, groupId);
            GroupStatistics groupstatics = (GroupStatistics)CacheService.Get(cacheKey, CacheScope.All);

            if (groupstatics != null) {
                return groupstatics;
            }

            return null;
        }

        public void PutGroupStatistics(int groupId, int minutesToCache, int forumThreadCount, int forumThreadReplyCount, DateTime lastForumThreadReply)
        {
            string cacheKey = string.Format(KvKGroupListWidgetCacheKeyPrefix, groupId);
            GroupStatistics groupStatistics = new GroupStatistics
            {
                ForumThreadCount = forumThreadCount,
                ForumThreadReplyCount = forumThreadReplyCount,
                LastForumThreadReply = lastForumThreadReply
            };

            CacheService.Put(cacheKey, groupStatistics, CacheScope.All, null, TimeSpan.FromMinutes(minutesToCache));
        }

        #endregion
    }

    public class GroupStatistics
    {
        public int ForumThreadCount { get; set; }
        public int ForumThreadReplyCount { get; set; }
        public DateTime LastForumThreadReply { get; set; }
    }

}</pre>
<p>As the code above shows, we make a simple extension with some simple functions that interact with Telligent caching. As you cannot cast objects within Velocity script, the functions within your caching extension have to return concrete instances of objects, in this case an instance of the GroupStatistics class. You have to write a small amount of additional code when want to cache an additional type of object. Now that we got our simple extension added to Telligent Community 6.0 we can start using it from Velocity script like this:</p>
<pre class="brush:jfx">#foreach($group in $groups)
	#set($groupStatistics = $CachingExtension.GetGroupStatistics($group.Id))
	#if ($groupStatistics)
		## Use cached results.
	#else
		## Execute normal widget code.
		## Insert results into cache.
		$CachingExtension.PutGroupStatistics($group.Id, 15, $threadCount, $replyCount, $lastReactionDate)
	#end
#end</pre>
<p>While this solution takes some additional effort, it adds great value over the standard Telligent caching in that it gives developers to power to cache widgets individuality to their needs. While caching is not the answer to every performance issue, adding additional caching in the right places can reduce load on the servers and help keep page loads in check. If you have any questions feel free to leave a comment or contact me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-custom-caching/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Telligent Community 6.0 custom tagging solution</title>
		<link>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-diy-tagging-solution/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-diy-tagging-solution/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 20:26:44 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Telligent Community 6.0]]></category>
		<category><![CDATA[Tridion 5.3]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=331</guid>
		<description><![CDATA[In this article I will be briefly describing a custom component I developed for integrating two web platforms at a client, the website and their community (running Telligent Community 6.0) . The website uses a tagging system which matches news articles and seminars to content pages on the website. The website itself is developed in [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I will be briefly describing a custom component I developed for integrating two web platforms at a client, the website and their community (running Telligent Community 6.0) . The website uses a tagging system which matches news articles and seminars to content pages on the website. The website itself is developed in .Net web forms. The tagging is managed via the Tridion Content Management System (5.3). The tagging system will be expended in the near future by pulling content from the community and matching it to content pages on the website using the same tagging system.</p>
<p>The community is developed using Telligent Community 6.0, which gave me to opportunity to work with this new product. The Telligent platform has evolved greatly compared to its predecessor Community Server, especially when it comes to customization and integration. The easiest way to integrate Telligent Community 6.0 is through using the rest API, which is quite elaborate as the documentation will <a href="http://telligent.com/community/developers/w/developer6/endpoint-documentation.aspx">show</a>.</p>
<p>Unfortunately, while the Telligent API is pretty elaborate, there are no endpoints available to pulling content by their tags. Something I hope will be available in the future, since the data structure for storing tags within Telligent is pretty straightforward.</p>
<p>When developing the integration component we went for a simple integration with maximum performance. Since the website can communicate directly with the Telligent Community 6.0 database, we choose not a developed a web service, but integrate the code into the website directly. We used standard Linq2Sql with repository pattern to hold the objects, and developed some business logic to sort the results by relevancy. Nothing especially fancy from a technical perspective, but I always find it fun to integrate platforms.</p>
<p>Since I will be developing a full community in Telligent Community 6.0 at a later period, there may be more articles regarding Telligent custom widget development on the way.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/09/telligent-community-6-0-diy-tagging-solution/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Asp.Net MvC 3 from scratch: Models</title>
		<link>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-models/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-models/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 09:42:01 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Asp.Net MvC]]></category>
		<category><![CDATA[Book Reviews]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=299</guid>
		<description><![CDATA[This is the third article in the series where we create a book review application from scratch using Asp.Net MvC 3. In this article were going to start developing the data layer for our application. Since this goal is fairly large I will be chopping it up into three articles, this article will get our [...]]]></description>
			<content:encoded><![CDATA[<p>This is the third article in the series where we create a book review application from scratch using Asp.Net MvC 3. In this article were going to start developing the data layer for our application. Since this goal is fairly large I will be chopping it up into three articles, this article will get our data layer up and running. The upcoming two articles will cover unit-testing and proper integration with the rest of the application through dependency injection.</p>
<h2>The data layer</h2>
<p>The main concern of the data layer is to manage and persist the data of the application. We will build our data layer using the Entity Framework 4.0, a object relational mapper tool build by Microsoft. The newest version of the framework offers a lot of neat new features, the most prominent being the “code first approach”. This feature allows us build our data layer starting with hand coding the data classes (the models). The database will be generated later using the models as the blueprint. The benefits of this approach: the models are clean, not generated by any tool and not directly coupled to Entity Framework. To utilize this approach we have to install an extension for the Entity Framework called “EFCodeFirst”, which you can install through the NuGet Package manager.</p>
<h2>The basics</h2>
<p>Before we get started, the data layer can be created inside a separate project in our solution, this makes it easier to physically recognize the existence of a separated layer and it dividing the application into multiple projects helps with structuring as the application grows larger. All right then let’s get started with coding our models. I will start with coding the basic models we need at this point, the book and the review:</p>
<pre class="brush:csharp">public class Book
{
        public int Id {get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string ISBN { get; set; }
}

public class Review
{
        public int Id { get; set; }
        public Book Book { get; set; }
        public string Content { get; set; }
        public DateTime Created { get; set; }
}</pre>
<p>Now we that we got our basic models in place we have to make the Entity Framework aware of their existence. The code first way to do this is to define a context that derives from the DbContext. The models themselves live inside the context as DbSets:</p>
<pre class="brush:csharp">public class EntityContext : DbContext
{
        public DbSet&lt;Review&gt; Reviews { get; set; }
        public DbSet&lt;Book&gt; Books { get; set; }
}</pre>
<p>As mentioned before the database is generated using the model as the blueprint. Personally i like to start with standard set of dummy data every time i run my application. The database if recreated by the Entity Framework every time i run my application, then the dummy data is inserted. We have to code the dummy data so the example provided here is pretty basic:</p>
<pre class="brush:csharp">public class EntityBaseData : DropCreateDatabaseAlways&lt;EntityContext&gt;
{
        protected override void Seed(EntityContext context)
        {
            context.Books.Add(new Book{Author = "Oskar uit de Bos", ISBN = "1234567", Name = "Book1"});
        }
}</pre>
<p>Notice that our class inherits from a class class DropCreateDatabaseAlways, which tells the Entity Framework to drop and recreate a fresh database. Insert the class into the gloabal.asax like this:</p>
<pre class="brush:csharp">protected void Application_Start()
{
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            DbDatabase.SetInitializer(new EntityBaseData());
}</pre>
<p>Last step is setting up the connection to the database. By default the Entity Framework looks for a connection string with a name that matches our custom DbContext name, in our case EntityContext. Lets give the Entity Framework what it wants, add the following connection string to the web.config file:</p>
<pre class="brush:xml">&lt;connectionStrings&gt;
    &lt;add name="EntityContext"
         connectionString="data source=.\SQLEXPRESS;Database=BookReviews5;Integrated Security=SSPI;"
         providerName="System.Data.SqlClient" /&gt;
&lt;/connectionStrings&gt;</pre>
<h2>The next step</h2>
<p>While we got our basic setup covered there is little to no structure at this point, so let’s apply some structure. Most of you should be familiar with the concept of repositories, they encapsulate the mechanisms for storing, retrieving and querying data from the rest of the application. Repositories act as gateways and guardians for our data, preventing data access logic from being scattered all over our data layer. Now that we got some basic structure in place we got testability to think about. While there are many different approaches for testing a data layer, i will take a strict unit-testing approach, so not integration testing with the database.</p>
<p>The focus of the unit-testing lies with data access logic inside the repositories. To enable testing without the database we will abstract the link to the database (our custom DbContext) away from the repositories into a separate component. Let’s start with this separate component, since we will need it when we start working on our repositories.</p>
<p>I named this component EntityProvider, since its main function is to provide the application’s data (entities) to our repositories. The basic idea is that every version of the EntityProvider exposes data through several IDbSet interfaces. The first implementation, our main implementation, works with the actual database. The implementation looks like this:</p>
<pre class="brush:csharp">public interface IEntityProvider
{
        IDbSet&lt;Review&gt; Reviews { get; set; }
        IDbSet&lt;Book&gt; Books { get; set; }

        void PersistChanges();
}

public class SqlEntityProvider : IEntityProvider
{
        private readonly DbContext _context;

        public SqlEntityProvider()
        {
            _context = new EntityContext();
        }

        public IDbSet&lt;Review&gt; Reviews
        {
            get { return _context.Set&lt;Review&gt;(); }
            set { Reviews = value; }
        }

        public IDbSet&lt;Book&gt; Books
        {
            get { return _context.Set&lt;Book&gt;(); }
            set { Books = value; }
        }

        public void PersistChanges()
        {
            _context.SaveChanges();
        }
}</pre>
<p>Now on to the first repository. As mentioned before, repositories act as gateways and guardians for our data.  Since there is a basic set of functionality that every repository should have, i have created a simple interface. The first implementation, our book repository, will only implement basic functionality by the interface. Our first repository looks like this:</p>
<pre class="brush:csharp">public interface IRepository&lt;T&gt; where T : class
{
        IEnumerable&lt;T&gt; All();

        void Change(int id, T entity);
        void Add(T entity);
        void Remove(T entity);
}

public class BookRepository : IRepository&lt;Book&gt;
{
        private IEntityProvider Provider { get; set; }

        public BookRepository(IEntityProvider provider)
        {
            Provider = provider;
        }

        public IEnumerable&lt;Book&gt; All()
        {
            return Provider.Books.AsEnumerable();
        }

        public void Change(int id, Book entity)
        {
            Book item = Provider.Books.Where(e=&gt;e.Id == id).FirstOrDefault();
            item.Name = entity.Name;
            item.ISBN = entity.ISBN;
            item.Author = entity.Author;

            Provider.PersistChanges();
        }

        public void Add(Book entity)
        {
            Provider.Books.Add(entity);
            Provider.PersistChanges();
        }

        public void Remove(Book entity)
        {
            Provider.Books.Remove(entity);
            Provider.PersistChanges();
        }
}</pre>
<h2>Wrapping up</h2>
<p>We got a lot of work done, it's time to wrap up the first article on the models. We have created basic models and wired them up to the Entity Framework using the code first approach. For more in-depth information on the code first approach check out <a href="http://blogs.msdn.com/b/adonet/archive/2010/12/06/ef-feature-ctp5-released.aspx">this</a> resource.  We created our first testable repository which contains basic functionality. But how about some results for all our hard work? A possible quick test is adding the following code to the index action of the home controller.</p>
<pre class="brush:csharp">public ActionResult Index()
{
            SqlEntityProvider provider = new SqlEntityProvider();
            BookRepository repository = new BookRepository(provider);
            var result = repository.All();

            ViewBag.Message = result.FirstOrDefault().Author;

            return View();
}</pre>
<p>Note that is <strong>not</strong> the proper way of integrating the repositories with the controllers, this is simply for the quick and dirty results. The proper loosely coupled way to integrate these components is through dependency injection, will will be covered in a later article. I expect the next article to be up within a week or so, until then happy coding. Feel free to ask questions, feedback is much appreciated. Full source for all that we have done so far is available <a href="https://docs.google.com/leaf?id=0Bw5Ev4VzE00TZGUwM2E0ZmEtNmI4My00M2ZiLWFjYjAtYTRmZDhlZjliOTU0&amp;hl=en">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-models/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.Net MvC 3 from scratch: Routing</title>
		<link>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-routing/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-routing/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 18:56:55 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Asp.Net MvC]]></category>
		<category><![CDATA[Book Reviews]]></category>
		<category><![CDATA[Unit-testing]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=185</guid>
		<description><![CDATA[This is the second article in the series where we create a book review application from scratch using Asp.Net MvC 3. In the first article i did a general introduction and created the project. In this article we are going to discuss the importance of automated testing and were going to finally going to write some code [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second article in the series where we create a book review application from scratch using Asp.Net MvC 3. In the <a href="http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-introduction-2/">first article</a> i did a general introduction and created the project. In this article we are going to discuss the importance of automated testing and were going to finally going to write some code for testing our routes.</p>
<p>The routing mechanism is vital to the mapping of requests within our application. This makes subjecting routes to automated testing a valid investment of time. Automated testing of routes requires the help of a mocking framework, there a several frameworks available, i will be using MOQ for this article series.</p>
<p>We will be installing MOQ with help of the NuGet package manager. The easiest way to install third party libraries using NuGet is simply through the GUI. Click references insight the unit-test project and click "Add package reference". In the next screen select "All" under the "Online" section on the left, then enter your search in the upper right corner like shown in the screenshot below. MOQ is the fourth result in de search results, click it and then click install.</p>
<p><img class="aligncenter" title="NuGet package manager" src="http://www.aspnet-mvc-info.com/wp-content/uploads/2011/03/Package-manager.gif" alt="" width="600" height="400" /></p>
<p>This is just a simple example of the power of NuGet, installing complex libraries with dependencies is just as easy. You can use the same approach to update your third party libraries by selecting "All" under the "Updates" section on the left, so there is no more manual importing of any libraries anymore, hurray!</p>
<h2>Unit-testing</h2>
<p>We will be writing tests during the development of our application. Now that we got MOQ installed, lets talk about the importance of automated testing in the form of unit-testing. If you have limited or no experience with automated testing or unit-testing, it is recommended to read up on the subject, at least the basics before continuing. check out my <a href="http://www.aspnet-mvc-info.com/resources/">resource page</a> for recommended reading.</p>
<p>Before we get to why we should unit-test, lets set a definition for unit-testing. The clearest definition i have come across is one made by Roy Osherove: <em>A unit-test is a an automated piece of code that invokes the method or class being tested and then checks some assumptions about the logical behavior of that method or class. A unit-test is always always written using a unit-testing framework. It is fully automated, trustworthy, readable and maintainable</em>.</p>
<p>But why should we as developers be bothered with unit-testing the first place? Well basically because we should care about the quality of our the web applications we develop. Delivering quality can be a challenge with a constantly evolving application, unit-testing provides a means to enhance and maintain the quality of our web application. The three major advantages offered by unit-testing are:</p>
<ul>
<li><strong>Unit-testing allows for easy refactoring</strong>. Readily-available unit tests make it easy for the programmer to check whether a piece of code is still working properly after a change. If a change causes a fault, it can be quickly identified and fixed.</li>
<li><strong>Unit-testing makes for great technical documentation</strong>. Developers somehow need to convey the functionally offered by class or method to other developers. One of the possibilities is looking at the unit-tests to gain a basic understanding off a class or method.</li>
<li><strong>Unit-testing promotes good coding</strong>. An important aspect of good coding is loose coupling. Loose coupling is a prerequisite for testing code with dependencies because it enables the replacements of dependencies with test doubles (stubs, mocks). This is the only way to control how dependencies will behave when under test, which is vital for unit-testing.</li>
</ul>
<p>Having discussed the advantages of unit-testing, it’s only fair to point out that that unit-testing is not able to cover all the bases, unit-testing has it's limitations and you should not reply soulfully on one technique. The first limitation of unit-testing is that it does not cover integration between different parts of the system. The second limitation is that the test scenarios are created by the developer. Somehow end-users tend to be creative and use/abuse the application in ways that developers do not expect and therefore are not covered by unit-testing.</p>
<p>While unit-testing does not cover all the bases, it is very important for the overall quality of the application. Just do not soulfully on unit-testing, some form of integration testing and user testing are important to prepare an application for "the real world". Now let's do some unit-testing of our own.</p>
<h2>Routing</h2>
<p>As mentioned before, we will start with the automated testing of our routes! The routing mechanism is vital to the mapping of requests within our application. This makes subjecting routes to automated testing a valid investment of time.</p>
<p>The challenge with testing routes is that the routing mechanism expects an request from the user, in the form of an HttpContext instance. This is a dependency, which we are going to replace with a special test double called a mock using the MOQ framework. We configure the mock to behave the way we want, faking a request from the user and giving us control over the dependency behaves.</p>
<p>With the mock in place, we call the routing mechanism, passing in our mocked object. The routing mechanism then returns a the route data, which contains the information on how the routing mechanism will map the request. We can check the contents of the route data to see how the request would be mapped.  Now let's see the code:</p>
<pre class="brush:csharp">using System.Web;
using System.Web.Routing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace BookReviews.Web.Tests.Routes
{
    public static class RouteTestHelpers
    {
        public static Mock&lt;HttpContextBase&gt; BuildMockHttpContext(string url)
        {
            // Create a mock instance of the HttpContext class.
            var mockHttpContext = new Mock&lt;HttpContextBase&gt;();

            // Decorate our mock object with the desired behaviour.
            var mockRequest = new Mock&lt;HttpRequestBase&gt;();
            mockHttpContext.Setup(x =&gt; x.Request).Returns(mockRequest.Object);
            mockRequest.Setup(x =&gt; x.AppRelativeCurrentExecutionFilePath).Returns(url);

            var mockResponse = new Mock&lt;HttpResponseBase&gt;();
            mockHttpContext.Setup(x =&gt; x.Response).Returns(mockResponse.Object);
            mockResponse.Setup(x =&gt; x.ApplyAppPathModifier(It.IsAny&lt;string&gt;())).Returns&lt;string&gt;(x =&gt; x);

            return mockHttpContext;
        }

        public static RouteData GetRouteDataForMockedRequest(string url)
        {
            var routes = new RouteCollection();
            MvcApplication.RegisterRoutes(routes);

            // Create a mock instance of the HttpContext class with the desired behaviour.
            var mockHttpContext = BuildMockHttpContext(url);

            return routes.GetRouteData(mockHttpContext.Object);
        }
    }

    [TestClass]
    public class RouteTests
    {
        [TestMethod]
        public void TestReviewControllerIndexRoute()
        {
            RouteData routeData = RouteTestHelpers.GetRouteDataForMockedRequest("~/review/index");

            // Check if the route was mapped as expected.
            Assert.IsTrue(routeData != null &amp;&amp; routeData.Values["controller"].ToString() == "review");
            Assert.IsTrue(routeData != null &amp;&amp; routeData.Values["action"].ToString() == "index");
        }
    }
}</pre>
<p>The code should be pretty straightforward with the commenting provided and the explanation provided earlier. As you may have noticed pretty much all of the code is reusable, so adding tests for new routes takes very little effort. In the next article we will start coding a lot more with our model. So this is it for the second article! Feel free to ask questions, feedback is much appreciated. Get the full source code for our progress so far from <a href="https://docs.google.com/leaf?id=0Bw5Ev4VzE00TNWQzNmMzMmYtZjFjOC00MjI4LThiNzUtNTk1ZmNmNTRmMTQ1&amp;hl=en">here</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-routing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asp.Net MvC 3 from scratch: Introduction</title>
		<link>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-introduction/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-introduction/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 11:49:33 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Asp.Net MvC]]></category>
		<category><![CDATA[Book Reviews]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=172</guid>
		<description><![CDATA[Web development is best suited for those who like continuous learning, you have to with the constant changes in technologies and available frameworks. To get a grip on new technologies and frameworks i often find myself writing code simply to learn and experiment. Now i have decided to combine this experimenting with my blogging by [...]]]></description>
			<content:encoded><![CDATA[<p>Web development is best suited for those who like continuous learning, you have to with the constant changes in technologies and available frameworks. To get a grip on new technologies and frameworks i often find myself writing code simply to learn and experiment. Now i have decided to combine this experimenting with my blogging by developing  a series of articles based on developing a web application using the Asp.Net MvC 3.</p>
<h2>The Asp.Net MvC 3 framework</h2>
<p>I choose to develop my application with the Asp.Net MvC framework because it enables me to develop high quality web applications. The framework utilizes successful design patterns (Model View Controller) and is build using important object oriented principles and best-practices like separation of concerns, loose coupling and testability. While it may take some getting used to for those coming from Asp.Net Web Forms, the initial learning investment will prove worth while.</p>
<p>The Asp.Net MvC framework recently had it's third major release, while many new features have been added, there are two new features that got me really exited. First is the Razor view engine, which offers cleaner and “easy on the eyes” syntax for the views. Razor comes with full Intellisense support. The second feature is the NuGet package manager which enables developers to easily manage third party libraries and their dependencies from within Visual Studio. NuGet makes installing and updating off all third party libraries a breeze. We will be working with both these new features during this article series. After discussing the framework let's talk about the application we are going to build.</p>
<h2>The Application</h2>
<p>Before we begin, the concept behind the application is pretty straightforward. Community demo applications like <a href="http://nerddinner.codeplex.com/">Nerddinner</a> proved that a simple concept can be effective for those wanting to learn a framework. We are going to develop a community website centered on book reviews. We start simple with the core functionality:  write, tag and submit book reviews. As the series progresses functionality will be extended. We will start developing responses to book reviews with a badge/kudos system. We should also implement some membership mechanism like OpenID integration. But before we get carried away, lets actually start by creating the a new project!</p>
<h2>Project creation</h2>
<p><a href="http://www.aspnet-mvc-info.com/wp-content/uploads/2011/03/Overview.png"><img class="alignright" src="http://www.aspnet-mvc-info.com/wp-content/uploads/2011/03/Overview.png" alt="" width="232" height="297" /></a>Time to fire up Visual Studio and get coding! <em>Make sure you have installed Asp.Net MvC 3 otherwise it will not show up in the project templates when creating a new project.</em> In the project creation screen select the Asp.Net MvC 3 project template. Name the project BookReviews.Web, and the solution BookReviews. In the second screen of the project creation select the select the following settings:</p>
<ol>
<li><strong>Project template</strong>: Internet application</li>
<li><strong>View engine</strong>: Razor</li>
<li><strong>Create a unit-test project</strong>: Yes</li>
<li><strong>Test project Name</strong>: BookReviews.Web.Tests</li>
<li><strong>Unit-test framework</strong>: Visual Studio Unit Test</li>
</ol>
<h2>Wrapping up</h2>
<p>After creating the project your Solution Explorer should look like the screenshot on the right, containing the web project along with a unit-test project. The unit-test project offers the opportunity for automated testing. We will start with automated testing in the next article. We will be using automated testing for our routes, ensuring that requests made by users get mapped properly within our application. So this is it for the first article, the next article get will posted within a few days! Feel free to ask questions, feedback is much appreciated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/03/asp-net-mvc-3-from-scratch-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating bulk SQL data scripts</title>
		<link>http://www.aspnet-mvc-info.com/2011/03/generating-bulk-sql-data-scripts/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/03/generating-bulk-sql-data-scripts/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 15:30:57 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=49</guid>
		<description><![CDATA[Most web developers who develop Asp.Net web applications come across SQL Server. While developers may have less direct contact with databases than before due to ORM (object-relational mapping) tools, most of us still work with databases on a regular basis. Today was one of those days, I was faced with generating a couple of large SQL data export scripts.  These scripts have [...]]]></description>
			<content:encoded><![CDATA[<p>Most web developers who develop Asp.Net web applications come across SQL Server. While developers may have less direct contact with databases than before due to ORM (object-relational mapping) tools, most of us still work with databases on a regular basis. Today was one of those days, I was faced with generating a couple of large SQL data export scripts.  These scripts have to be executed by a service provider, and since I don't have access to their machines delivering scripts is the only simple way.</p>
<p>There are many tools for generating large SQL data export scripts, but not all are suited for managing large/bulk scripts. SQL data compare, a tool by Red Gate, generates scripts that are rather large, without an option to split the generated script. Since SQL data compare was my only tool for managing SQL data, I had to search for additional tooling, and i found the wonderful BCP utility.</p>
<p>It turns out the <a title="BCP utility" href="http://msdn.microsoft.com/en-us/library/aa174646(v=sql.80).aspx" target="_blank">BCP utility</a> is included in the SQL server install, and its specifically made for dealing with large bulk exports and imports. Its old school command-line, which might not make it the most user-friendly tool, but damn, is it fast. And it's available on every machine that has SQL server installed. The basic usage of the BCP utility is clearly explained in <a title="BCP basics" href="http://sqlfool.com/2008/12/bcp-basics/" target="_blank">this</a> article, it’s pretty straightforward and the tool is awesome so use it! That is all, happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/03/generating-bulk-sql-data-scripts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Web Forms vs MvC debate</title>
		<link>http://www.aspnet-mvc-info.com/2011/03/the-web-forms-vs-mvc-debate/</link>
		<comments>http://www.aspnet-mvc-info.com/2011/03/the-web-forms-vs-mvc-debate/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 08:12:10 +0000</pubDate>
		<dc:creator>Oskar</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Asp.Net MvC]]></category>
		<category><![CDATA[Asp.Net Webforms]]></category>

		<guid isPermaLink="false">http://www.aspnet-mvc-info.com/?p=42</guid>
		<description><![CDATA[Currently Microsoft ships two frameworks to develop web application with the .Net framework (Asp.Net Web Forms and Asp.Net MvC). Microsoft is developing and supporting both frameworks alongside each other, emphasizing that developers have to pick the right tool for the task at hand. Despite the position Microsoft takes on the subject, there has been debate [...]]]></description>
			<content:encoded><![CDATA[<p>Currently Microsoft ships two frameworks to develop web application with the .Net framework (Asp.Net Web Forms and Asp.Net MvC). Microsoft is developing and supporting both frameworks alongside each other, emphasizing that developers have to pick the right tool for the task at hand. Despite the position Microsoft takes on the subject, there has been debate within the .Net community as to which framework is the better framework for developing web applications. In this article I discuss my views on the subject, which I consider an important subject and thus a good starter posting for an Asp.Net blogger.</p>
<h2>Why use frameworks?</h2>
<p>Before we get into comparing the Web Forms framework to the MvC framework, I want to address the benefits of using application development frameworks in the first place. First and foremost a framework helps me be an efficient developer by taking care of the general overhead associated with developing web applications. This lets me focus on the client specific challenges. Secondly a framework can help me deliver high quality applications by supporting and encouraging the use of design patterns and best-practices.</p>
<p>At this point in time approximately 80% of all Asp.Net implementations use Web Forms. This is no surprise since Web Forms is been around considerably longer, and has been quite successful in the past. But the MvC framework seems to be on the rise and having worked with both frameworks, I can see why the MvC framework is gaining momentum. It does very well in a lot of the areas where the Web Forms framework has been having troubles.</p>
<h2>The Asp.Net Web Forms framework</h2>
<p>The Asp.Net Web Forms framework has been around for quite some time, but it’s still maintained and even extended by Microsoft, the last release being the .Net framework 4 release. Despite these efforts, as it stands now, using the Web Forms framework does not help me being an efficient developer. Although this might sound a bit harsh it should be said, the reason the Web Forms framework was created simply doesn’t serve the current needs of enterprise web applications developers.</p>
<p>The original reason for creating the Web Forms framework was to offer desktop developers a smooth transition to web development. This design goal brought forth technical difficulties because there are differences in state between the desktop and the web, which uses the inherently stateless HTTP protocol. To overcome these challenges Web Forms employs an event-driven postback/viewstate development model to hide developers from the stateless web. However, this development model is fragile and has been known to cause problems with scaling complexity.</p>
<p>Aside from the technical issues, the Web Forms framework suffers from a lack of control, mainly with the way it generates output. The Web Forms framework relies on controls to build applications. These controls generate output, giving the developer only very limited control over the output. This makes it more difficult to do front-end and client-side development. This also poses challenges when working with accessibility and html standards. While new options for control over the output were added with the .Net framework 4 release, it’s still limited.</p>
<p>The second point where the Web Forms framework is not successful is in help me deliver quality applications. In all honesty it has to be noted that being a good developer is still mostly the responsibility of the developer itself, and not just that of the framework. However a framework can inherently support best-practices and encourage developers to use best-practices. There is no such support when working with the Web Forms framework. Important best-practices like seperation of concerns, loose coupling and testability have to be implemented by the developers themselves. This shortcoming was remedied somewhat by the creation of the design pattern called MVP (Model View Presenter), but these efforts have nothing to do with the framework, and is not enforced by the framework in any way.</p>
<h2>The Asp.Net MvC framework</h2>
<p>The Asp.Net MvC framework was developed by Microsoft to be an alternative to Asp.Net Web Forms for building web applications. The framework utilizes the MVC (Model View Controller) design pattern, and is build using important object oriented principles and best-practices like separation of concerns, loose coupling and testability. I’m not going to explain these best-practices in this article, but there’s a wealth of documentation on what they are and how harness their power. The MvC framework also respects web standards, so there’s no bypass of the inherently stateless nature of the HTTP protocol.</p>
<p>The first point where the MvC framework is really successful l: helping me be an efficient developer. The reason the MvC framework succeeds where the Web Forms framework fails is by serving the current needs of enterprise web applications developers. It takes care of the common overhead like you would without compromising on flexibility. This is where it beats the Web Forms framework, the MvC framework gives developers total control over everything that is going on.</p>
<p>The second point where the MvC framework is successful l: helping me deliver quality applications. The framework inherently works with the MvC design pattern, giving separation of concerns out of the box. Separation of concerns makes it easier to manage complexity and make changes on certain isolated parts of the application. Loose coupling is incorporated into the MvC framework itself, enabling developers to swap even the core component of the frameworks with custom replacements to change the behavior of the framework without effecting other components. This makes amazing flexibility and makes working with the best-practice of loose coupling easy. Testability is also relatively easy with the MvC, this best-practice is emphasized by Microsoft since unit-testing is been getting a lot of attention lately.</p>
<h2>Wrapping up</h2>
<p>Responsibility for the overall quality of the application still lies with the developers. They have to use the best-practices and make sound decisions when developing, whatever framework they use. Working with the MvC won’t guarantee success, it just makes it easier to be successful. If you have had success with the Web Forms framework in the past or still, you can continue to do so. However I would advise that everyone doing Asp.Net development at least fiddle around with the MvC framework a little, it might just be the thing for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aspnet-mvc-info.com/2011/03/the-web-forms-vs-mvc-debate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

