.Net MVC Project with AutoFac, SQL and Redis Cache

Summary

In this blog post I’m going to demonstrate a simple .Net MVC project that uses MS SQL server to access data.  Then I’m going to show how to use Redis caching to cache your results to reduce the amount of traffic hitting your database.  Finally, I’m going to show how to use the AutoFac IOC container to tie it all together and how you can leverage inversion of control to to break dependencies and unit test your code.

AutoFac

The AutoFac IOC container can be added to any .Net project using the NuGet manager.  For this project I created an empty MVC project and added a class called AutofacBootstrapper to the App_Start directory.  The class contains one static method called Run() just to keep it simple.  This class contains the container builder setup that is described in the instructions for AutoFac Quick Start: Quick Start.

Next, I added .Net library projects to my solution for the following purposes:

BusinessLogic – This will contain the business classes that will be unit tested.  All other projects will be nothing more than wire-up logic.

DAC – Data-tier Application.

RedisCaching – Redis backed caching service.

StoreTests – Unit testing library

I’m going to intentionally keep this solution simple and not make an attempt to break dependencies between dlls.  If you want to break dependencies between modules or dlls, you should create another project to contain your interfaces.  For this blog post, I’m just going to use the IOC container to ensure that I don’t have any dependencies between objects so I can create unit tests.  I’m also going to make this simple by only providing one controller, one business logic method and one unit test.

Each .Net project will contain one or more objects and each object that will be referenced in the IOC container must use an interface.  So there will be the following interfaces:

IDatabaseContext – The Entity Framework database context object.

IRedisConnectionManager – The Redis connection manager provides a pooled connection to a redis server.  I’ll describe how to install Redis for windows so you can use this.

IRedisCache – This is the cache object that will allow the program to perform caching without getting into the ugly details of reading and writing to Redis.

ISalesProducts – This is the business class that will contain one method for our controller to call.

Redis Cache

In the sample solution there is a project called RedisCaching.  This contains two classes: RedisConnectionManager and RedisCache.  The connection manager object will need to be setup in the IOC container first.  That needs the Redis server IP address, which would normally be read from a config file.  In the sample code, I fed the IP address into the constructor at the IOC container registration stage.  The second part of the redis caching is the actual cache object.  This uses the connection manager object and is setup in the IOC container next, using the previously registered connection manager as a paramter like this:

builder.Register(c => new RedisConnectionManager("127.0.0.1"))
    .As<IRedisConnectionManager>()
    .PropertiesAutowired()
    .SingleInstance();

builder.Register(c => new RedisCache(c.Resolve<IRedisConnectionManager>()))
    .As<IRedisCache>()
    .PropertiesAutowired()
    .SingleInstance();

In order to use the cache, just wrap your query with syntax like this:

return _cache.Get("ProductList", 60, () =>
{
  return (from p in _db.Products select p.Name);
});

The code between the { and } represents the normal EF linq query.  This must be returned to the anonymous function call: ( ) =>

The cache key name in the example above is “ProductList” and it will stay in the cache for 60 minutes.  The _cache.Get() method will check the cache first, if the data is there, then it returns the data and moves on.  If the data is not in the cache, then it calls the inner function, causing the EF query to be executed.  The result of the query is then saved to the cache server and then the result is returned.  This guarantees that the next query in less than 60 minutes will be in the cache for direct retrieval.  If you dig into the Get() method code you’ll notice that there are multiple try/catch blocks that will error out if the Redis server is down.  For a situation where the server is down, the inner query will be executed and the result will be returned.  In a production situation your system would run a bit slower and you’ll notice your database is working harder, but the system keeps running.

A precompiled version of Redis for Windows can be downloaded from here: Service-Stack Redis.  Download the files into a directory on your computer (I used C:\redis) then you can open a command window and navigate into your directory and use the following command to setup a windows service:

redis-server –-service-install

Please notice that there are two “-” in front of the “service-install” instruction.  Once this is setup, then Redis will start every time you start your PC.

The Data-tier

The DAC project contains the POCOs, the fluent configurations and the context object.  There is one interface for the context object and that’s for AutoFac’s use:

builder.Register(c => new DatabaseContext("Server=SQL_INSTANCE_NAME;Initial Catalog=DemoData;Integrated Security=True"))
    .As<IDatabaseContext>()
    .PropertiesAutowired()
    .InstancePerLifetimeScope();

The context string should be read from the configuration file before being injected into the constructor shown above, but I’m going to keep this simple and leave out the configuration pieces.

Business Logic

The business logic library is just one project that contains all the complex classes and methods that will be called by the API.  In a large application you might have two or more business logic projects.  Typically though, you’ll divide your application into independent APIs that will each have their own business logic project as well as all the other wire-up projects shown in this example.  By dividing your application by function you’ll be able to scale your services according to which function uses the most resources.  In summary, you’ll put all the complicated code inside this project and your goal is to apply unit tests to cover all combination of features that this business logic project will contain.

This project will be wired up by AutoFac as well and it needs the caching and the data tier to be established first:

builder.Register(c => new SalesProducts(c.Resolve<IDatabaseContext>(), c.Resolve<IRedisCache>()))
    .As<ISalesProducts>()
    .PropertiesAutowired()
    .InstancePerLifetimeScope();

As you can see the database context and the redis caching is injected into the constructor of the SalesProjects class.  Typically, each class in your business logic project will be registered with AutoFac.  That ensures that you can treat each object independent of each other for unit testing purposes.

Unit Tests

There is one sample unit test that performs a test on the SalesProducts.Top10ProductNames() method.  This test only tests the instance where there are more than 10 products and the expected count is going to be 10.  For effective testing, you should test less than 10, zero, and exactly 10.  The database context is mocked using moq.  The Redis caching system is faked using the interfaces supplied by StackExchange.  I chose to setup a dictionary inside the fake object to simulate a cached data point.  There is no check for cache expire, this is only used to fake out the caching.  Technically, I could have mocked the caching and just made it return whatever went into it.  The fake cache can be effective in testing edit scenarios to ensure that the cache is cleared when someone adds, deletes or edits a value.  The business logic should handle cache clearing and a unit test should check for this case.

Other Tests

You can test to see if the real Redis cache is working by starting up SQL Server Management Studio and running the SQL Server Profiler.  Clear the profiler, start the MVC application.  You should see some activity:

Then stop the MVC program and start it again.  There should be no change to the profiler because the data is coming out of the cache.

One thing to note, you cannot use IQueryable as a return type for your query.  It must be a list because the data read from Redis is in JSON format and it’s de-serialized all at once.  You can de-searialize and serialize into a List() object.  I would recommend adding a logger to the cache object to catch errors like this (since there are try/catch blocks).

Another aspect of using an IOC container that you need to be conscious of is the scope.  This can come into play when you are deploying your application to a production environment.  Typically developers do not have the ability to easily test multi-user situations, so an object that has a scope that is too long can cause cross-over data.  If, for instance, you set your business logic to have a scope of SingleInstance() and then you required your list to be special to each user accessing your system, then you’ll end up with the data of the first person who accessed the API.  This can also happen if your API receives an ID to your data for each call.  If the object only reads the data when the API first starts up, then you’ll have a problem.  This sample is so simple that it only contains one segment of data (top 10 products).  It doesn’t matter who calls the API, they are all requesting the same data.

Other Considerations

This project is very minimalist, therefore, the solution does not cover a lot of real-world scenarios.

  • You should isolate your interfaces by creating a project just for all the interface classes.  This will break dependencies between modules or dlls in your system.
  • As I mentioned earlier, you will need to move all your configuration settings into the web.config file (or a corresponding config.json file).
  • You should think in terms of two or more instances of this API running at once (behind a load-balancer).  Will there be data contention?
  • Make sure you check for any memory leaks.  IOC containers can make your code logic less obvious.
  • Be careful of initialization code in an object that is started by an IOC container.  Your initialization might occur when you least expect it to.

Where to Get The Code

You can download the entire solution from my GitHub account by clicking here.  You’ll need to change the database instance in the code and you’ll need to setup a redis server in order to use the caching feature.  A sql server script is provided so you can create a blank test database for this project.

 

MVC – List of Check Boxes

Summary

In this post I’m going to show how to handle a list of check boxes in an MVC application.

The Interface

I’ve kept this example as simple as possible to point out the tricky spots when attempting to deal with check boxes.  For those of you who have worked with HTML and the POST form submit, you’ll know that check boxes are annoying.  The basic problem with a check box is that only the check boxes that are checked will appear in the list of submitted objects.  If you have thousands of check boxes on your screen, then that would be a more efficient method of submitting your data.  Leaving the server code to sort out what changed since the page was rendered.  However, if you have 100 or fewer check boxes, it makes more sense to just submit all the check boxes back with a flag to indicate if it was checked or not.

The following is a screenshot of the screen I’m going to use.  The check box list is dynamic and is determined by a data source.  In this example, the list of names on the screen will be populated manually (i.e. hard-coded).  In a real application you’ll need to determine what data will be used in your check list and query the data using an ORM or ADO, etc.

The Model

 Let’s start with the model.  First I created an object to represent one person record, or in this case, one check box of information:

public class PersonModel
{
    public string Name { get; set; }
    public bool Checked { get; set; }
}

This object is pretty easy to figure out.  There is a name that forms the title next to the check box.  Your data might consist of a first and last name, in which you can concatenate them using Razor on your view.  The checked boolean value is used to represent the fact that the check box is checked or not.

Then I created another object to represent the entire view consisting of a list of personnel, or a list of check boxes:

public class HomeViewModel
{
    public List<PersonModel> Persons { get; set; }
}

That concludes the model itself.

The Default Controller Method

The controller consists of two methods.  The first method sets up the data and sends it to the view:

public ActionResult Index()
{
    var myHomeViewModel = new HomeViewModel();

    myHomeViewModel.Persons = new List<PersonModel>();
    myHomeViewModel.Persons.Add(new PersonModel { Name = “Frank“, Checked = false });
    myHomeViewModel.Persons.Add(new PersonModel { Name = “Joe“, Checked = false });
    myHomeViewModel.Persons.Add(new PersonModel { Name = “Sue“, Checked = false });
    myHomeViewModel.Persons.Add(new PersonModel { Name = “Mike“, Checked = false });

    return View(myHomeViewModel);
}

This is all very basic stuff.  Just initialize a list of personnel (called myHomeViewModel) and populate it with 4 items.  Then make sure you pass the list to the view.

I’ll show how the submit controller works after I describe the view.


The View

In order to use your model data, you need to declare the model at the top of the view:

@model MVCMultiCheckBox.Models.HomeViewModel

Then the real work occurs inside the form tags:

@using (Html.BeginForm(“Submit“, “Home“))
{
    for (int i = 0; i < Model.Persons.Count; i++)
    {
        <div>
            @Html.CheckBoxFor(m => m.Persons[i].Checked, new { id = “cbPerson_” + i })
            @Html.DisplayFor(m => m.Persons[i].Name)
        </div><br />
        @Html.HiddenFor(m => m.Persons[i].Name);

    }
    <div><input type=”submitvalue=”Submitname=”Submitclass=”btn btn-default” /></div>
}

The controller’s name is “Home” and the controller post method will be named “Submit”.  Keep that in mind when you’re trying to figure out why your submit doesn’t do anything.  Next, is the for loop.  That will iterate through the list of check boxes defined in the model.  Inside the loop are three (3) very important items: The check box, the displayed name and a hidden field.  The check box and name are obvious, but the hidden field is used to make sure that something is submitted when the check box is not checked.  The name of the hidden field will be the same name as the check box.  If a check box is set, then it will be returned, if not, then the hidden field will be returned which will be set to false (all hidden fields have a value of false).  Run the program, right-click on the web page and view the source to see what is rendered to the browser.


The Http POST Controller

Finally, the post controller looks like this:

[HttpPost]
public ActionResult Submit(HomeViewModel result)
{
    return View(“Index“, result);
}


Which does nothing with the result set.  You’ll need to put a break-point on the “return view()” line and submit some data.  Then look at the values in side of “result”.  You should see your model updated with the correct true/false representing the check boxes that you checked on the interface.  Here’s the result variable in the watch window after checking joe and sue (with everything expanded):

The POST controller is where you’ll need to call a save method in your personnel business class and save the changed results back to the database.  If you’re attempting to reduce the amount of chatter to your database, you can setup a “PreviouslyChecked” flag for each record and then only save back records where the “Checked” is not equal to “PreviouslyChecked”.  Of course, there are many other possible ways to handle the updating of your database from the results returned from your view, but that is not for this blog post.

How to Get The Code

You can download the sample source from my GitHub account by clicking here.


 

Legacy Code Writers

Summary

The purpose of this blog post is to describe how legacy code gets perpetuated years beyond its useful life and how to put a stop to it.  I will also make my case for why this process needs to be stopped.  I will attempt to target this article to managers as well as the developers who are continuing the creation of legacy code.  I would like to make a disclaimer up front that my intent is not to insult anybody.  My intent is to educate people.  To get them out of their shell and think about newer technologies and why the new technologies were invented. 

My History

First, I’m going to give a bit of my own history as a developer so there is some context to this blog post.  

I have been a developer since 1977 or 78 (too long to remember the exact year I wrote my first basic program).  I learned Basic.  Line numbered Basic.  I join the Navy in 1982 and I was formally educated on how to repair minicomputers, specifically the UYK-20 and the SNAP-II.  In those days you troubleshoot down to the circuit level (and sometimes replace a chip).  While I was in the Navy, the Apple Macintosh was introduced and I bought one because it fit in the electronics storage cabinet in the transmitter room on the ship (which I had a key to).  I programmed with Microsoft Basic and I wanted to write a game or two.  My first game was a battleship game that had graphical capabilities (and use of the mouse, etc. etc.).  It didn’t take long before the line numbers became a serious problem and I finally gave in and decided to look at other languages.  I was very familiar with Basic syntax, so switching was like speaking a foreign language.  It was going to slow me down.

I stopped at the computer store (that really was “the day”), and I saw Mac Pascal in a box on the shelf and the back of the box had some sample code.  It looked similar to Basic and I bought it.  I got really good at Pascal.  Line numbers were a thing of the past.  In fact I used Pascal until I was almost out of college.  At that time the University of Michigan was teaching students to program using Pascal (specifically Borland Pascal).  Object oriented programming was just starting to enter the scene and several instructors actually taught OOP concepts such as encapsulation and polymorphism.  This was between 1988 and 1994.

The reason I used Pascal for so long was due to the fact that the Macintosh built-in functions used Pascal headers.  The reason I abandoned Pascal was due to the fact the the World Wide Web was invented around that time and everything unixish was in C.  I liked C and my first C programs were written in Borland C.  


Fast Forward…

OK, I’m now going to fast-forward to the late 90’s and early 2000’s when OOP programming really became main stream and frameworks, unit testing, etc. all became available.  When the web became something that businesses used there were only a hand-full of tools available.  There was C, html (with javascript), Java, PHP and Microsoft’s product called ASP (and a hand-full of oddballs that no longer exist).  If you wanted to develop a dynamic interactive website application, and you were running Microsoft Windows Server products, you had to perform the deed in ASP.  I avoided this path by using PHP on a Linux machine, but I got lucky.  I was in charge of the department and I made the final decision on what technology will be used and how the product would be developed.  Don’t get me wrong, there is a lot of ASP code that is in use and it is stable and operational.  Unfortunately, ASP is one of the most difficult legacy code to convert into something modern.

What’s my Beef with Legacy Programmers?

If your development knowledge ended with ASP and/or VB without learning and using a unit testing framework, the MVC framework (or equivalent), ORMs, Test Driven Development, SOLID principles, then you probably are oblivious to how much easier it is to program within a modern environment.  This situation happens because programmers focus on solving a problem with the tools they have in their tool box.  If a programer doesn’t spend the time to learn new tools, then they will always apply the same set of tools to the problem.  These are the programmers that I am calling Legacy Programmers. 

Legacy Programmers, who am I talking about?

First, let’s describe the difference between self-taught and college educated developers.  I get a lot of angry responses about developers who have a degree and can’t program.  There are a lot of them.  This does not mean that the degree is the problem and it also should not lead one to believe that a developer without a degree will be guaranteed to be better than a degree carrying developer.  Here’s a Vin diagram to demonstrate the pool of developers available:


The developers that we seek to create successful software is the intersection of the degree/non-degree programmers.  This diagram is not intended to indicate that there are more or less of either developer in the intersection called solid developers.  In my experience, there are more college degree carrying developers in this range due to the fact that most solid developers will be wise enough to realize that they need to get the piece of paper that states that they have a minimum level of competence.  It’s unfortunate that colleges are churning out so many really bad developers, but to not obtain the degree usually indicates that the individual is not motivated to expand their knowledge (there are exceptions).

OK, now for a better Vin diagram of the world of developers (non-unix developers):


In the world of Microsoft language developers there are primarily VB and C# developers.  Some of these developers only know VB (and VB Script) as indicated by the large blue area.  I believe these individuals outnumber the total C# programmers judging by the amount of legacy code I’ve encountered over the years, but I could be wrong on this assumption.  The number of C# programmers are in red and the number of individuals who know C# and not VB are small.  That’s due to the fact that C# programmers don’t typically come from an environment where C# is their first language.  In the VB circle, people who learned VB and not C# are normally self-taught (colleges don’t typically teach VB).  Most of the developers that know VB and C# come from the C# side and learn VB, or if they are like me, they were self-taught before they obtained a degree and ended up with knowledge of both languages.

The legacy programmers I’m talking about in this blog post fall into the blue area and do not know C#.


Where am I Going With This?

OK, let’s cut to the chase.  In my review of legacy code involving VB.Net and VB Script (AKA Classic ASP) I have discovered that developers who built the code do not understand OOP patterns, SOLID principles, Test Driven Development, MVC, etc.  Most of the code in the legacy category fit the type of code I used to write in the early 90’s before I discovered how to modularize software using OOP patterns.  I forced myself to learn the proper way to break a program into objects.  I forced myself to develop software using TDD methods.  I forced myself to learn MVC (and I regret not learning it when it first came out).  I did this because these techniques solved a lot of development issues.  These techniques help to contain bugs, enhance debugging capabilities, reduce transient errors and make it easier to enhance without breaking existing features (using unit tests to perform regression testing).  If you have no idea what I’m talking about, or maybe you’ve heard the term and you have never actually used these techniques in your daily programming tasks, you’re in trouble.  Your career is coming to an end unless you learn now.

Let’s talk about some of these techniques and why they are so important.  First, you need to understand Object Oriented Programming.  The basics of this pattern is that an object is built around the data that you are working on (I’m not talking about database data, I’m talking about a small atomic data item, like an address or personnel information or maybe a checking account).  The data is contained inside the object and then methods are built to act on this data.  The object itself knows all about the data that is acted on and external objects that use this object do not need to understand nuances of the data (like how to dispose of allocated resources or how to keep a list properly ordered).  This allows the developer that creates the object to hide details, debug the methods that act on the data and not have to worry about another object corrupting the data or not using it correctly.  It also makes the software modular.

On a grander scale is a framework called MVC (Model View Controller).  This is not the only framework available, but it is the most common web development framework in Microsoft Visual Studio.  What this framework does is give a clean separation between the C# (or VB) code and the web view code (which is typically written in HTML, JQuery and possibly Razor).  ASP mixes all the business logic in with the view code and there are no controllers.  In MVC, the controllers will wire-up the business logic with the view code.  Typically the controller will communicate with an AJAX call that gives the web-based interface a smooth look.  The primary reason for breaking code in this fashion is to be able to put the business logic in a test harness and wrap unit tests around each feature that your program performs.

Unit testing is very important.  It takes a lot of practice to perform Test Driven Development (TDD) and it’s easier to develop your code first and then create unit tests, until you learn the nuances of unit testing, object mocking and dependency injection.  Once you have learned about mocking and dependency injection, you’ll realize that it is more efficient to create the unit tests first, then write your code to pass the test.  After your code is complete, each feature should be matched up with a set of unit tests so that any future changes can be made with the confidence that you (or any other developer) will not break previously defined features.  Major refactoring can be done in code designed this way because any major change that breaks the code will show up in the failure of one or more unit tests.

ORMs (Object Relational Mapping) are becoming the technique to use for querying data from a database.  An ORM with LINQ is a cleaner way to access a database than ADO or a DataSet.  One aspect of an ORM that makes it powerful is the fact that a query written in LINQ can use the context sensitive editor functions of Visual Studio to avoid syntax errors.  The result set is contained in a object with properties that produces code that is easier to read.

APIs (Application Programming Interface) and SOA (Service Oriented Architecture) are the new techniques.  These are not just buzzwords that sound cool.  These were invented to solve an issue that legacy code has: You are stuck with the language you developed your entire application around.  By using Web APIs to separate your view with your business logic, you can reuse your business logic for multiple interfaces.  Like mobile applications, custom mini-applications, mash-ups with 3rd party software, etc.  The MVC framework is already setup to organize your software in this fashion.  To make the complete separation, you can create two MVC projects, one containing the view components and one containing the model and controller logic.  Then your HTML and JQuery code can access your controllers in the same way they would if they were in the same project (using Web API).  However, different developers can work on different parts of the project.  A company can assign developers to define and develop the APIs to provide specific data.  Then developers/graphic artists can develop the view logic independently.  Once the software is written, other views can be designed to connect to the APIs that have been developed, such as reports or mobile.  Other APIs can be designed using other languages including unix languages running on a unix (or Linux) machine.  Like Python or Ruby.  The view can still communicate to the API because the common language will be either JSON or XML.

Another aspect of legacy code that is making enhancements difficult is the use of tightly coupled code.  There is a principle called SOLID.  This is not the only principle around, but it is a very good one.  By learning and applying SOLID to any software development project, you can avoid the problems of tightly coupled code, procedures or methods that perform more than one task, untestable code, etc.

The last issue is the use of VB itself.  I have seen debates of VB vs. C#, and VB has all the features of C#, etc. etc.  Unfortunately, VB is not Microsoft’s flagship language, it’s C#.  This is made obvious by the fact that many of C# Visual Studio functions are finally going to come to the VB world in Visual Studio 2015.  The other issue with VB is that it is really a legacy language with baggage left over from the 1980’s.  VB was adapted to be object oriented not designed to be an object oriented language.  C# on the other hand is only an OOP language.  If you’re searching for code on the internet there is a lot more MVC and Web API code in C# than in VB.  This trend is going to continue and VB will become the “Fortran” of the developer world.  Don’t say I didn’t warn ya!


Conclusion

If you are developing software and are not familiar with the techniques I’ve described so far, you need to get educated fast.  I have kept up with the technology because I’m a full-blooded nerd and I love to solve development issues.  I evolved my knowledge because I was frustrated with producing code that contained a lot of bugs and was difficult to enhance later on.  I learned each of these techniques over time and have applied them with a lot of success.  If I learn a new technique and it doesn’t solve my issue, I will abandon it quickly.  However, I have had a lot of success with the techniques that I’ve described in this blog post.  You don’t need to take on all of these concepts at once, but start with C# and OOP.  Then work your way up to unit testing, TDD and then SOLID.

 

So You’re About to Graduate with a Degree in Computer Science…

Introduction

I’m going to relax and write a free-form blog post today about preparing for a career in the field of Computer Science. This post is directed at students that are getting close to graduation or are thinking ahead about how they are going to turn their expensive degree into a job that is both satisfying to work at and earn an excellent income.


How Prepared are Students Fresh out of College?

I’m afraid that this question is more complicated than it seems.  Technically the core Computer Science courses taught at major universities are more than adequate to get you started in the field of software development.  However, competition is tough, and you want to rise above the “average” student.  You also don’t want to spend a lot of time finding a job.  It’s better to be able to choose from a list of jobs.  Knowledge that is taught in the classroom is just the foundation that you need to build your career on.  You’ll need to learn some practical knowledge before you can really shine, and you’ll need to make sure you fully understand the principles that you learned in college.  What principles am I talking about?  Object oriented programming principles for one.  Database design principles, data structures, coding practices, etc.

What all this means is that you’ll have to do some studying outside the classroom.  You’ll also need to do a few example programs to gain a full understanding of the subjects you’ve been taught.


Does this Stuff get Easier when I get into the Working World?


As you get more practice at building software it definitely gets easier.  Some techniques are still hard, and the ever-changing technology world makes learning new things a constant task.  It also makes it an interesting and challenging career.  As a student, most people are just learning about the syntax of their first language.  Once you’ve written a few programs, the syntax will come automatically, like riding a bicycle.  At first, riding a bicycle is all about focusing on balancing.  After a while, you don’t think about balancing any more.  It’s automatic.  The same applies to programming.  Once you know the syntax, then the next challenge is learning how to apply algorithms to solving the total problem.  This is really just a challenge in breaking the problem down small enough to solve with an algorithm you have in your tool box.  Once you have that down, you just get so good at it that you can think up solutions to big problems in minutes.


Is there any Way to Prepare Myself Now?

Yes there is.  There are two primary directions in the software development field and you’ll need to choose one field or the other so you can focus your efforts.  One field is the .Net field with Microsoft products like Visual Studio, IIS, C#, Visual Basic, SQL Server, etc.  The other field is unix based systems with PHP, Ruby, Python, Apache, Oracle, MySQL, etc.  There are other fields as well, but I’d stick to one of the two main paths.  I have developed software from both fields at one time or another.  I rarely use my knowledge from both fields.  Normally a company will pour their resources into one or the other and it’s difficult to try and learn both at the same time.

Currently, I’m working for a company that uses Microsoft products and I’m working in the .Net field.  So I’m going to give some pointers on how you can prepare yourself to get a good job with some .Net knowledge coupled with your college degree.

As of this writing this is what you should learn outside of class:

1. MS SQL server
2. C#
3. An ORM using LINQ queries (Entity Framework is an easy ORM to learn)
4. MVC website programming

Start off slowly.  Ease into it.  If you try to bite off too much you’ll get frustrated and give up.  What you want to do is learn how to install some free software, experiment with it on a small scale and then think up a project that want to build using the techniques you learned.  This is important, and it’s can be listed on your resume as a hobby.  Hobbies that involve your career will impress a person looking at your resume.  It makes the statement that you are serious about your career and you are interested in the job that you are seeking.  


OK, I’m Sold, How do I get Started?

Start with MS SQL server express.  Type “download ms sql server express” into google and look for microsoft’s download center.  Download the software and install it on your PC.  As of this writing SQL Server Express 2012 is the current version available.  Avoid using any pre-release or Technology Preview versions.  These could have bugs and will only distract you from learning what you really should learn: How to create and access a database.

OK, now, let’s assume you installed SQL Server and you want to proceed.  Open the Server Manager Studio console and get familiar with how it works.  This is an interface into your database.  Right now you don’t have any databases created, so right-click on the “Databases” node and select “New Database”.  Give it a name (I’ll call mine “sampledata”) and create it.  Next, create a table inside the new database.  Open your database node (“sampledata”) by clicking on the “+” symbol next to it.  You’ll see what looks like a subdirectory named “Tables”.  Right click on that and select “New Table”.  Give it a name (I’ll call mine “students”).  You’ll be presented with a designer interface where you can create fields (called columns).  Name the first column “id”, then make it an “int”.  Name the second column “Name”, then make it a “char(50)”.  You should see something like this:

Now click on the save button and name the table “student”.  Close the current window.

Next, we’re going to put some data into that table that we created.  Open the subdirectory named “Tables” and right click on the node named “dbo.student”, select “Open Table”.  Now put some data into your table.  Here’s a sample of what I typed into my table:


What are you learning?  You’re beginning to learn the basic tasks of setting up a database.  Next, let’s do a simple select query.  Click on your table node and then click the “New Query” button. There is a little drop-down list in the tool bar that is above your “Object Explorer” window and it should say “sampledata” in it.  That is the current database that will be queried.  If this drop-down does not have your database selected, then just select your database.  Then your queries will be performed against tables in your database.  Now type this into the query window:

select * from student

Hit the F-5 key, or click on the “! Execute” button.  You should see this at the bottom of your query window:


Now you can experiment with your query to select all the students and order by “name”, select students with “id” less than 3, etc. etc.  Create a second table that is related to the first table you created.  Then fill it with data and learn how to join two tables together.  Do some research on inner join and outer join.  Practice your queries by adding more related tables and test joining them together.  You should fully understand what an outer join is and the difference between a left and right outer join.  You could spend a day learning this knowledge, but it will become the knowledge that sets you apart from a newly minted college student.


Is that all?

Nope.  That’s just the beginning.  Next, you should download Visual Studio for web development.  The free version.  Type “visual studio express” into google and find the Microsoft products screen.  Currently “Express 2013 for Web” is available as well as “Express 2013 for Windows”.  Download “Express 2013 for Web” and install this on your machine.  You’ll need an MSN account to download it, this is free.  It’s a bit time consuming, but I’m going to teach you how to connect to that database that you just installed and created.

Once you’ve installed Express, start it up and create a new MVC4 project.  You’ll need to look under the “Visual C#” section then under “Web” and select “Visual Studio 2012” and finally click on the “ASP.NET MVC4 Web Application” type.  Give it a name and click “OK”.  Next it will ask you what type of MVC application you want, choose an empty project with razor in the drop-down.

In your solution explorer (the panel in the top right corner of visual studio) right click on the “controllers” directory and “add”, then click on “controller”.  Leave the dropdown as an “Empty MVC Controller”  and name it “HomeController”.  Click the “Add” button.  You should see a window with a little bit of code an din the middle is a “return View();” line of code.  Right click on “View()” and select “Add View” then click the “Add” button.  This will create a matching view for this controller.  Now you’ll see a cshtml web page.  At this point, you have a working website and it will startup a virtual webserver and a webpage will appear withe word “Index” on it.  Yeah!

OK, seriously.  Let’s connect to a database and read something, then print it on the web page.  Right-click on the “Models” directory in your “Solution Explorer” window, then “add -> New Item”.  Click on the “Data” item and click “ADO.NET Entity Data Model”:


Just click the “Add” button and leave the default name “Model.edmx”.  Click “Next” to generate from a database.  Now you’re going to need a new connection.  This is the tricky part.  Click the “New Connection” button and select a “Microsoft SQL Server” datasource.  Click “Continue” and another window appears.  You should be able to select your server from the “Server Name” list.  It should match the name that appears in the SQL server connect to database window.  The server name is also shown in the top of your “Object Explorer” of the SQL Server Management Studio window.  You can correct the name by typing it into the “Server name” text/drop-down control.  If it is correct, then you can select the database (leave the “use windows authentication” radio button alone).  Select your database and click “OK”.  Then click the “Next” button.  Now you’ll see this window (assuming all went as planned):


Now drill down into the tables and check all the tables you wish to access from your program and click the “Finish” button.  

If your table does not contain a primary key, then you’ll have to do some research (because EF will not allow tables without primary keys).  This is easy to fix by going back to the SQL Server console, right-click on your table and select “modify”, then right click on the “id” field and make it “set primary key”.  If your data has unique values in that field, you can save your changes.  If that field contains data that is null or duplicated, you’ll need to fix the data first, then come back and add the primary key. Sounds frustrating?  You’re learning a very important lesson about database design.  Set the primary key first, then put data in the table.

If you need to update or add tables to your entity framework, you can double-click the edmx file in the solution explorer of visual studio and then right-click on the blank window and select “Update Model from Database”.  That will take you back to the window pictured above and you can check all tables that you want to add to the edmx file.  You should see a little graphical representation of your table in the context window.  Now make sure you click on the model1.edmx window to ensure that it is currently selected, then click on the save button.

Now you have knowledge of how to setup an Entity Framework context.

Next, let’s go back to the HomeController.cs file and add a using at the top.  I’m trying to minimize the amount of code here, so I’m going to cheat and access the database directly from the controller.  Normally you’ll create classes in your Model directory and they will access your data and return it to your controller.  

Type this after your last using statement:

using TestMVC4Application.Models;

Now type this inside your controller (assuming you added a table named student to your context):

public ActionResult Index()
{
    using (var db = new sampledataEntities())
    {
        var studentNames = (from s in db.students select s.Name).ToList();

        return View();
    }

}

The “sampledataEntities()” name came from the context.  If you double-click on your edmx file and click on the background window, you’ll see the properties in the lower right that will tell you your “Entity Container Name”.  That is the context name.  Very important knowledge.

In the code above, I opened a context and called it “db”.  Entity framework renamed the table with an “s” on the end.  It creates a class with the table name and it creates a list with the same name and an “s” on the end.  Lesson to take from this is to always name your SQL Server tables in singular form (like “student” or “teacher, not “students” or “teachers”).  That will save you some headaches later when attempting to find the right names in your LINQ code.

Now your program will run, but nothing new will happen.  You’ll still get a webpage with “Index” printed on it.  However, you can now put a break-point on the “return View()” line of code and run your program.  There is a gray bar on the left side of the window.  Click on that bar at the line of code you wish to break on and it will turn the line red.


Now run your program.  When it stops at the red line, you can hover your mouse cursor over the studentNames variable and see that it has items in it.  Now add a line to put your studentNames into the viewbag variable:

public ActionResult Index()
{
    using (var db = new sampledataEntities())
    {
        var studentNames = (from in db.students select s.Name).ToList();

        ViewBag.studentNames = studentNames;

        return View();
    }

}

The ViweBag object is part of razor and it allows you to transfer data to the view.  Now double-click on your view called “Index.cshtml” (it’s located in the Views folder in the Solution Explorer.

Add a line to your view:

@{
    ViewBag.Title = “Index“;
}

<h2>Index</h2>

@ViewBag.studentNames[0]


This will print the first student name (it’s at index zero of an array of students).  Run your program and see for yourself.

If you got this far, then you have just learned a little MVC programming.  You learned a little C# programming.  You learned how to setup and use an ORM called Entity Framework.  You learned a little bit of Razor.  You also learned how to connect to a database server and read data into your application.

Now it’s time to run with it.  Find a web application that you want to build.  Something that is not too big, but big enough to be a challenge.  Design and build your database, test your queries using the SQL Server Management Studio console.  Add tables to your edmx context in your C# application.  Try out your queries in LINQ inside your controller.  Add controllers and views.  Tweak the HTML inside the view to display your data in a more attractive format.   If you can’t figure out how to do something, Google it.  There are a lot of Entity Framework LINQ sites that show how to do queries.  There’s a lot of examples of MVC programming and Razor.

You need a project that will hold your interest for a while.  Once you’ve built something that performs a real task, you’ll have a working knowledge of these technologies.  These are valuable tools that you should put on your resume.  Make sure your confident with these technologies and go nail down that job you really wanted.



 

API Controllers

Introduction

For those who follow my blog, you’ll remember that I have been working on a project using the Visual Studio MVC 4 framework.  I spent a considerable amount of time researching how the pieces of this framework fits together and I’ve discovered some nuances.  Many of these tricks I learned after starting the real project and attempt to get some real (as in, not research) work done.  So this post will cover the API Controller.


Getting Started

To begin this test example, we’ll need a new MVC 4 empty project.  You can refer to my previous post on how to create this.  Once you have an empty project, create an empty MVC controller in the “Controllers” directory (right-click on the “Controllers” directory and select “Add -> Controller”, then name it “HomeController” (make sure it’s an empty MVC controller type).  Then right-click on the View() method and “add view”.  Just leave it named “Index”.

OK, now we’re going to delete everything in the Index.cshtml file and make it look like this (you can just paste this into it):

<!doctype html>
<html>
  <head>
    <title></title>
    <script src=”~/scripts/jquery-2.0.3.js“></script>
    <script src=”~/scripts/homescript.js“></script>
  </head>
  <body>
      <div>
        <input type=”submitvalue=”Test 1id=”TestController1“/><br/>
        <input type=”submitvalue=”Test 2id=”TestController2“/><br/>
        <input type=”submitvalue=”Test 3id=”TestController3“/><br/>
        <input type=”submitvalue=”Test 4id=”TestController4“/><br/>
      </div>
  </body>
</html>



Now you’ll need a javascript file and you’ll need JQuery.  Download the JQuery JS file from JQuery.com.  I’m using version 2 for this demo, I’m pretty sure you can use either version.  We’re only going to use it for the AJAX capabilities.  Create a “scripts” directory and copy the JQuery.js file into that directory and also create an empty js file called “homescript.js” in the “scripts” directory:


Now, our JS file will start with this code:

$(document).ready(function() {

$(“#TestController1“).click(function() {

});

$(“#TestController2“).click(function() {

});

$(“#TestController3“).click(function() {

});

$(“#TestController4“).click(function() {

});

});

Next, we’ll need to add an API Controller, then we can get started.  Right-click on the “Controllers” directory and select “Add -> Controller”, then select an empty API Controller type.  Name it “DemoController”.  I’ll be adding two classes that I’ll just use as containers of information to pass back and forth using JSON.  Your API controller should look like this (I left out the usings for clarity):

namespace MvcApiControllerBlogSample.Controllers
{
    public class PersonnelType
    {
        public string First;
        public string Last;
    }

    public class TestType
    {
        public int Number;
    }

    public class DemoController : ApiController
    {

    }

}

Now it’s time to get down to business.  My first test will be very simple and should work out of the box.  First, I’m going to add some code to the homescript.js file (inside the first click function:

$(“#TestController1“).click(function() {
    $.ajax({
        type: “GET“,
        url: “api/Demo?account=TEST“,
        success: function() {

        },
        error: function(error) {
            alert(error.responseText);
        }
    });

});

Next, I’ll add a small method in the API Controller code:

public class DemoController : ApiController
{
    [HttpGet]
    public void PostOne(string account)
    {
        string result = account;
    }
}

Put a breakpoint on the line in your controller where the string “result” is assigned “account”.  Then run the application and click the first button.  You should see your program run to the breakpoint.  Now examine the text inside “account”.  It should be “TEST”.

When referring to a controller, you use the first part of the controller name (i.e. this one is called “DemoController”, but we call it “Demo” in the URL string above).  You also need to use “api” in the path name.  If you open the WebApiConfig.cs file, you’ll see a route that specifies this route:

api/{controller}/{id}

Notice the first part of the path is “api” with no braces around it.  That specifies that the first part of the path must start the word “api”.  The second parameter is the controller name, and the third parameter is an id (used by a post operation), which could also be setup as a URL parameter like I did in the above example (for post operations, a get operation always uses the URL convention like that listed above).

So now we constructed a simple “get” operation involving a parameter.  You can add more parameters just like you would add to a URL anchor link (separating with and symbols).  

Now let’s try our hand at a POST operation.  Add this code to your second controller in the homescript.js file:

$(“#TestController2“).click(function() {
    var temp = { First: ‘Joe‘, Last: ‘Smith‘ };

    $.ajax({
type: “POST“,
  url: “api/Demo/SavePersonnel/test“,
  contentType: “application/json“,
  data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
            alert(error.responseText);
}
    });
});

And in the API controller:

public class DemoController : ApiController
{
    [HttpGet]
    public void PostOne(string account)
    {
        string result = account;
    }

    [HttpPost]
    [ActionName(“SavePersonnel“)]
    public HttpResponseMessage ThisMethodNameDoesntMatter(string id, PersonnelType record)
    {
        return Request.CreateResponse(HttpStatusCode.OK, record);
    }

}

The first thing you might notice is the “ActionName” attribute added to the “ThisMethodNameDoesntMatter” method.  This will be used to specify that this post action will be executed by the ajax call in the javascript when specifically cited (see the “SavePersonnel” inside the “URL” specification in the javascript above).  If you execute this code as it is, it will fail.  That’s because we need to add a route to the WebApiConfig.cs file, which should now look like this:

namespace MvcApiControllerBlogSample
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: “DefaultApi“,
                routeTemplate: “api/{controller}/{id}“,
                defaults: new { id = RouteParameter.Optional }
            );

            // Controllers with Actions
            // To handle routes like `/api/VTRouting/route`
            config.Routes.MapHttpRoute(
                name: “ControllerAndAction“,
                routeTemplate: “api/{controller}/{action}/{id}
            );
        }
    }

}

Now you can run this application and click on the second button.  If you put a breakpoint inside the “ThisMethodNameDoesntMatter” method, you’ll see that the program stops at that point and the record will contain the first and last name hard-coded in the javascript.  For a real-world application, you can feed your text fields into these javascript variables before calling the ajax command.  You’ll also notice that the id has been filled in with “test”.  This is an optional configuration.  You do not have to setup your controller to accept an id or any url parameters when a post is issued.  I’ll show you that next.

On to the third example.  Let’s add code to the javascript file for “TestController3”:

$(“#TestController3“).click(function() {
    var temp = { Number: ‘5‘ };

    $.ajax({
type: “POST“,
url: “api/Demo/SaveTestType/Ignore“,
contentType: “application/json“,
data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
           alert(error.responseText);
}
    });
});

And for the controller add this method after the last one:

[HttpPost]
[ActionName(“SaveTestType“)]
public HttpResponseMessage doesntmatter(TestType testrec)
{
    return Request.CreateResponse(HttpStatusCode.OK, testrec);

}

Now run this program with a breakpoint inside the “doesntmatter” method and you’ll see that “testrec” will contain the number “5”.  Also, you’ll notice that there is no id passed, but you’ll still need to specify an id (I called it “Ignore”) in the javascript.  This is to ensure a proper pattern match with the routing that has been defined in the WebApiConfig.cs file.  One last example, to demonstrate that you can have two controller methods with the same parameters but called from different ajax calls.  Create this code for your “TestController4” javascript:

$(“#TestController4“).click(function() {
    var temp = { Number: ‘9‘ };

    $.ajax({
type: “POST“,
url: “api/Demo/SaveTestType2/Ignore“,
contentType: “application/json”,
data: JSON.stringify(temp),
success: function() {

},
error: function(error) {
           alert(error.responseText);
}
    });
});

And finally for the controller:

[HttpPost]
[ActionName(“SaveTestType2“)]
public HttpResponseMessage doesntmatter2(TestType testrec)
{
    return Request.CreateResponse(HttpStatusCode.OK, testrec);

}

Now, if you put a breakpoint inside each C# controller method, you can click on each button (Test 1 through Test 4) and see your program stop at the correct controller.  You can also see that the “doesntmatter2” method contains a “9” instead of a “5”.  So we know that the correct parameter is being passed.

One other thing to notice (if you haven’t noticed already), is that the method names in the controller don’t mean anything.  You can give them descriptive names for your own identifying purposes.  The name in the “ActionName” attribute is what controls which method is called from the post.  Without this attribute, you will need to create post methods with different parameters so the controller knows which one to match.  Also, I’m betting it’s possible to manipulate the routing to set up a pattern where you don’t need the “Ignore” parameter in your ajax call.  I have yet to dig deeper into the routes.  When I get that nailed down, I’ll do another blog post and report what I’ve discovered.  There are also other types of controllers, like a DELETE and a PUT controller, which I did not include in this blog post.

Summary

The four sample API controllers that I have presented are a test project that I set up to reverse engineer what I needed in order to make my application run.  Sometimes you have to create a small test with just the bare essentials to see how things interact with each other.  Otherwise, you can waste a lot of time trying to get something simple to work because it is buried in a lot of other program clutter (which could be conflicting with your code).  Now that I’ve figured out the very basics, I’ll keep this little program handy for further testing.  I hope this helps you get rolling without going through all the pain I did when I attempted to make this work.









 

MVC 4 API controllers

If you’ve read my previous posts you’ll know that I’m in the research phase of deciding which framework to use with my company’s new project.  At this point I’m leaning toward MVC 4 with a few add ons: AngularJS, Bootstrap, Less, EF-6 and some others.  MVC is starting to grow on me and I wanted to show how to pass data back and forth between jquery (using AJAX) and an API controller (just to get warmed up).

Let’s Get Started
 
To get this started I created a blank MVC 4 application and a controller called “HomeController.cs” in the “Controllers” directory.  Once this file was created, I opened the file and it already contained this code (automagically):


I apologize for using images for the code in this post, I’ll include a link to the whole project at the end so you can download the source code.  Or you can just follow along with my descriptions and create this project on your own (giving you the chance to learn the tricks as you do it).

If you right click on the “View” method, you’ll see an option called “Add View…”.  Select that and a new dialog box will appear to create a view.  Leave the view name “Index” and just click the “Add” button.  A new cshtml file will be created in the “Views” directory.  This is where you’ll put some html code for the startup page.  Before modifying that file, let’s create a script directory and a javascript file.

Right-click on the project and click “Add -> Add New Folder”.  Name the folder “scripts”.  Then right-click on the scripts folder and select “Add -> New Item”.  Then navigate to create a js file:


You can name the file anything you like.  I named mine “javastuff.js”.

Next, you’ll need JQuery.  I would recommend going to the JQuery website and downloading the latest version available.  The reason I like to do it this way is because it only needs one file.  If you use the NuGet facility, you’ll probably get a bunch of stuff you don’t need.  

Go to “jquery.com” and click on the download button.  I chose version 2.0.3 for this example.  Once you have downloaded the js file that is needed for jquery, drag it into the scripts folder.

Now it’s time to include the javascript into the html index.cshtml file created earlier.  First double-click on the index.cshtml file to edit the contents.  Then drag each js file into the code just above the <h2> tags.  Like this:


Of course, you can also hand type the script tags in if you like.  Make sure the jquery reference is on top.  You should be able to run your application and it will do pretty much nothing at this time (except print the text “Index” at the top of the browser).

All right, back to the C# stuff.  Create another controller in the “Controllers” directory, but this time make sure it is an empty API Controller (Right-click on the “Controllers” directory and select “Add -> Controller…”).  Name it “PersonnelController”:


One more file to create.  Right-click on the “Models” directory and create a C# file.  Name it “PersonnelModel.cs”.  Your models should contain the code that queries your database, but I’m going to skip using a database in this sample to keep it as simple as possible.  What I’m going to do is create a class that will represent one database record.  Then I’ll use lists of this class to represent data queried from the database.  The “PersonnelModel.cs” file should look like this:


Now we can use a list of this class inside of the api controller file (open your “PersonnelController.cs” file and enter this code):


I had to add a using statement to bring in the model for this example.  This “Get()” API controller will communicate with the JQuery that we are about to create.  Edit the “javastuff.js” file and make an ajax call like this:


Now you can put a breakpoint on the line where the variable temp is assigned to data.  When you run your application you’ll break at that point and you can see that data contains a list of records that match what was added to result in the C# controller above:



Here’s the source code for the entire project:
MVC Blog Post Controller Demo Project (Zip File)

In my next post I’m going to show how to add AngularJS to the project and connect a grid control to the API Controller and automatically display rows of data in the index.cshtml file.

 

MVC 4, Django Research

In earlier posts I’ve talked about the necessity of research.  I always keep my eyes open for new technology.  At DealerOn we are about to embark on a new and major project (of which I can’t give details at this time).  All I can say is that it will be a complete ground-up design.  At this point all possibilities are open.  We have kicked around a bunch of ideas on how to design this new web application.  Django with Python is still being considered and I have done some preliminary analysis of Visual Stuido’s Python/django implementation.  My first assessment of this implementation is that was should go all in or don’t attempt it.  In other words: Stick to Python’s native OS (Linux) so we are relatively assured that we can build this web application without running into technical problems part way through the project. 

The other environment I was researching is MVC4.  Specifically the Web API with AngularJS.  I found a CRUD sample application that has AngularJS with Web API and it works rather well.  My only real turn-off was the sheer number of source files it took to make that beast run.  Here’s a link to the code: CRUD grid using AngularJS, web api, Entty Framework and Bootstrap.  One other appealing aspect of this project is that it uses EF and bootstrap (bootstrap provides responsive design for portable devices). 

In addition to downloading samples from the web, I have purchased two books to read and gain further insight to these two frameworks (django and MVC).  The first book is for django:

I only thumbed through this book so far, but I own a lot of Apress books and they’re generally good for information. 

For MVC, I purchased this book:

 
 
I started reading this book yesterday and I have to say that I like this book a lot.  If you have never done MVC programming before, buy this book.  It starts with an empty project and has a chapter on one concept at a time.  The first concept it covers is the controller.  The first test programming is nothing more than a controller source file that returns a string.  The chapter describes the default controller names (“HomeController”), the default controller directory and how to use controller methods.  This is all taught without regard to views or models (covered in successive chapters each).  The appeal of this method of learning is that you can lean one concept before moving on to the next.  I have looked at a lot of examples and reverse engineered some of this stuff from the examples (like the Web API interface, I learned by reverse-engineering a working example).  My knowledge is much more solid when I can focus on one piece at a time.
 
So now you’re probably thinking “Frank, you’ve never done an MVC project before?”  Nope.  The reality of software development is that you only get to use a new technology when you create a new application or rewrite an existing application from the ground up.  After that, you’re stuck for a long time with the technology you have chosen.  So choose wisely. 
 
I typically try to choose a technology that has been around for a while, that way all the quirks have been discovered by other developers and the answers are posted on forums like Stack Overflow (Stack Overflow, in case you don’t already know, is the holy grail of answers for programming problems).  I also strive to choose something that is close to bleeding edge so I know that it won’t be obsolete before I deploy the first application (i.e. I could just create this new app as a standard ASP code-behind application and be done with it.  But that’s really no fun and I hate code-behind pages).  Currently, frameworks are all the rage and there’s a reason for it: Separation of concerns.  It is easier to maintain an application if each file or module is concerned about one aspect of your application.  Concerns are like database access, URL routing, Business logic, views, etc.  By dividing these tasks into different files or modules, the developer can focus on one aspect at a time and not mix it all together in one source file (remember ASP?  Yuck).
 
When I first looked at a demo of the MVC setup, I was a horrified by the fact that there are three primary directories to contain all the major code files for the web application (The Model, View and Controller directories).  In a real-world application, I can visualize these folders growing to thousands of files each.  However, I have another plan for our application.  I plan to leave the model directory empty and wire the controllers directly to the business objects, which will be contained in a separate project or projects.  All the database Entity Framework stuff will also be in a separate project.  This will give a clean break between the web side of things and the business code for unit testing purposes (and the ability to use the business code for other applications, if necessary). 
 
Django
 
I spent some time looking at django and Python for Visual Studio.  If you’d like to experiment with this setup, go here: Python tools for Visual Studio.  There are a few tricks to overcome to get django to work properly, but they’re contained in the samples.  One turn-off is the amount of stuff needed to be installed and configured before it will work at all.  However, I’m willing to overlook a difficult configuration if it is only used to get the project started and running.  The appeal of the demo project that I looked at was the minimal number of files that were necessary to make it work.  Django was designed to just get things rolling and it certainly does that (once the initial configuration and setup hurdles are crossed).
 
My purpose in testing the Visual Studio version was my hope that it would work as a project within a solution.  In other words, I was hoping to create my business logic in another project (i.e. assembly) and just reference it in my Python code.  This doesn’t seem to work with the 32-bit version of Python.  The 64-bit version of Iron Python doesn’t seem to work with django (or perhaps I haven’t stumbled on the proper way to install django yet, since Iron Python doesn’t use pip for installations). 
 
Another avenue I explored was to connect to SQL Server from Python.  There are database connectors for SQL Server and there are a lot of people having issues with it.  The whole SQL Server part has it’s own drivers and requires other software to be installed and configured.  I have a lot more research to do on this subject.
 
The django avenue will create other issues with our environment if we decide to go that route and there is no ability to import and use objects from C# projects.  One issue will be the ORM that we use.  It will have to be an ORM that is native to django.  We would also need to verify how compliant any SQL Server driver is, so we know up front if we are digging a big hole for ourselves.  We are not in a position to convert our database from SQL Server into any other technology at this time.  Our database is currently tied to other applications and it contains a lot of stored procedures.
 
Conclusion
 
At this point you’re probably thinking that I’m biased to using MVC because most of my recent development work has been in C# and SQL Server.  However, I have switched technologies in the past.  I have built large web applications using PHP and Oracle all on top of the Linux OS.  So I’m not tied to Microsoft.  I have also ported a PHP/Oracle system to C#/SQL Server, so I know how to switch between two different technologies.  My gut feeling at this point is that I need more knowledge of both MVC and django to make a more informed decision on which way to go.  This decision will probably be sooner than later, since I really want to get the show on the road and this project has been on the back burner for too long already.