Archive for the ‘Programming’ Category

May 11th, 2009

Creating Your First MVC ViewEngine

A question that I have been hearing a lot lately is:

How do I change the view location in MVC?

But what they really mean to say is:

How do I create a new ViewEngine that uses the view locations of my choosing?

It is actually very simple to do, and once you see it, I think you will agree with my assessment.  The first thing we are going to do to create our custom ViewEngine, is define the paths that we want to use for our master pages, view pages, and shared pages.  I have taken the liberty to define the following paths, you can customize them however you wish:

  • Master Pages:
    ~/Templates
    it use to be ~/Views/Shared or the controllers view
  • View Pages:
    ~/Views
  • Shared Pages:
    ~/Common
    it use to be ~/Views/Shared

The next thing we need to do is create a new class for our ViewEngine, for this example we are going to call it SimpleViewEngine.

public class SimpleViewEngine : VirtualPathProviderViewEngine
{
}

As you might have noticed from above our SimpleViewEngine inherits from VirtualPathProviderViewEngine, this is the root ViewEngine that uses the VirtualPathProvider (VPP). The VPP provides a way for web applications to read files off the file system in their local web application, so it is perfect for what we are doing. If you don’t want a file system based ViewEngine, and maybe want a ViewEngine based from the database, you can use the IViewEngine interface to create your own custom ViewEngine that fits your needs. (MVC is very flexible, by design)

The next thing we need to do is code our paths in to our SimpleViewEngine. We will do this in the constructor, so that they only have to be initialized once for the entire life span of our SimpleViewEngine.

public SimpleViewEngine ()
{
	/* {0} = view name or master page name
	 * {1} = controller name
	 */

	// create our master page location
	MasterLocationFormats = new[] {
		"~/Templates/{0}.master"
	};

	// create our views and common shared locations
	ViewLocationFormats = new[] {
		"~/Views/{1}/{0}.aspx",
		"~/Common/{0}.aspx",
	};

	// create our partial views and common shared locations
	PartialViewLocationFormats = new[] {
		"~/Views/{1}/{0}.ascx",
		"~/Common/{0}.ascx"
	};
}

As you can see the format is pretty straight forward. We create a string[] array with the paths of where our master pages, views, and common views are located. The only thing that we need to do is set place holders in our path so the the VirtualPathProviderViewEngine can replace the master name, view name, and controller name to construct our appropriate path.

  • {0}: is the view name or master page name.
  • {1}: is the controller name.

After we have done the hard part, which honestly wasn’t that hard, of creating the constructor with the paths, we just need to return the view objects from the constructed partial paths. Since we are using the standard ASP.NET Web Form (ASPX/ASCX) rendering engine. We are able to leverage the work already done by the MVC team and just return a new instance of the WebFormView object.

protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
	return new WebFormView(partialPath, null);
}

protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
	return new WebFormView(viewPath, masterPath);
}

Nothing really earth shattering here, just simply filling out the constructor with the proper parameters from our method, and then returning the newly created view. If you wanted to create a view based out of the database, or off your own syntax (meaning not ASP.NET syntax) then you would have to create your own view based off of the IView interface. But for this example we are only concerned with changing where our views are located.

There is one more thing that we need to do, and that is register our new SimpleViewEngine for use in the framework. The registration of view engines is done in the Global.asax, similar to the same way we register new routes.

public static void RegisterViewEngines(ViewEngineCollection viewEngines)
{
	viewEngines.Clear();
	viewEngines.Add(new SimpleViewEngine());
}

public static void RegisterRoutes(RouteCollection routes) { ... }

protected void Application_Start()
{
	RegisterRoutes(RouteTable.Routes);
	RegisterViewEngines(ViewEngines.Engines);
}

So we are now done. You have created a new view engines, defined your own routes, and registered this view engine with the MVC framework. Some other types of paths you may want to consider trying for your applications, using a custom ViewEngine, are special folders for your mobile or Facebook versions of your website.

  • Mobile: ~/Views/{1}/Mobile/{0}.aspx
  • Facebook: ~/Views/{1}/Facebook/{0}.aspx

I told you it was simple and straight forward, and I hope you agree that the MVC team has done an awesome job at providing a very flexible framework for us to tweak and customize it so it fits our applications.

Tags: , ,

Posted in ASP.NET, C#, How To | kick it on DotNetKicks.com | Bookmark | View blog reactions | 10 Comments »

April 18th, 2009

Code Camp 2009.1 - Gooey GUI… Programming in Visual Studio

Here is my presentation from Code Camp 2009.1:

You can download the software seen in this presentation at:

And Sara Ford’s best selling book on the subject, appropriately called Microsoft Visual Studio Tips.

sara-ford-visual-studio-tips

And because she is such an awesome person all the royalties from the book are going to a scholarship fund to help pay for the the costs of sending Hurricane Katrina survivors to college. So if you are interested go pick up a copy.

Top 3 of my favorite tips from Sara Ford:

  1. Did you know… You can create toolbar buttons to quickly toggle your favorite VS Settings? – #372
  2. Did you know… how not to accidentally copy a blank line? - #050
  3. Did you know… How to optimize Visual Studio for multi-monitors? - #381

Tags: , , ,

Posted in Personal, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

April 16th, 2009

Recession Proof Your Programming Skills

In this economy you have to do everything to keep your skills fresh and current so that employers find you a desirable hire.  I really though the tips provided in 8 Ways to Recession-Proof Your Programming Career where spot on when this article came out last year.  And now that the TechRepublic has released 10 kills developers will need in the next 5 years.  I have decided to give you some of my favorite Wrox books that align very well to this TechRepublic article.

Learn C#

Learn ASP.NET

Learn ASP.NET MVC

Final Cover Photo

didn’t think I would leave my book out, did you? ;)

Learn Java

Learn PHP

Learn RIA & Web 2.0

I beleive all these books are a nessisty in helping you improve your career.  You don’t have to understand or know all of this technology, but you should at least have one of these books on your shelf.

Tags: ,

Posted in ASP.NET, C#, JavaScript, News, Personal, Programming, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

April 13th, 2009

I see at least 4 things wrong with this code

I saw this code over on Ayende’s website. I see at least 4 things wrong with this code, which was found here.

public object DeepCopy (object value)
{
    try {
        return value;
    } catch (Exception ex) {
        throw ex;
    }
}

See if you can find them all.

Tags:

Posted in C#, News, Personal, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

March 31st, 2009

What are your Visual Studio tips?

As I announced yesterday I will be speaking at the Philly Code Camp 2009.1 on Visual Studio 2008 for beginners.  As part of this presentation I want to be able to provide the 10 most valuable tips for beginners using Visual Studio.

I did a quick search of the internet last night, on this subject, and everything seemed to point to Sara Ford as the defacto standard on Visual Studio tips.  She even has a best selling book on the subject, appropriately called Microsoft Visual Studio Tips.

sara-ford-visual-studio-tips

And because she is such an awesome person all the royalties from the book are going to a scholarship fund to help pay for the the costs of sending Hurricane Katrina survivors to college. So if you are interested go pick up a copy.

The problem is that she has 251 tips in the book, and 382 tips on her website and I need to widdle this down to the top 10.

Here are my top 3, so far:

  1. Did you know… You can create toolbar buttons to quickly toggle your favorite VS Settings? – #372
  2. Did you know… how not to accidentally copy a blank line? - #050
  3. Did you know… How to optimize Visual Studio for multi-monitors? - #381

What are yours? If you have a favorite please include it in the comments below with a link (if possible).

Tags: , , ,

Posted in Personal, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 18th, 2009

ASP.NET MVC 1.0 Released

Final Cover PhotoIt was just announced at MIX09 that ASP.NET MVC 1.0 has been released for general use and is out of the Release Candidate phase.  There has been no word on the changes form RC 2 to this release version.  But I will keep this post updated as I learn more.  Also as of writing this the download hasn’t been posted to CodePlex either, but I am sure that it will be posted pretty soon.

I am assured by Wrox that the cover of the book will be updated to look like what is on the right of your screen.  So it should be any day now, so go pre-order a copy today by clicking on the cover image to your right and it will take you to the Amazon page where you can place your pre-order.  That way as soon as the book ships you will have a copy waiting on your front porch.

Update: It is available from Microsoft Download.  Probably on CodePlex by the end of the day.  Here is the final description of the download for your reading pleasure.

ASP.NET MVC 1.0 provides a new Model-View-Controller (MVC) framework on top of the existing ASP.NET 3.5 runtime. This means that developers can take advantage of the MVC design patterns to create their Web Applications which includes the ability to achieve and maintain a clear separation of concerns (the UI or view from the business and application logic and backend data), as well as facilitate test driven development (TDD). The ASP.NET MVC framework defines a specific pattern to the Web Application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can take advantage of the specific Visual Studio 2008 MVC templates within this release to create their Web applications, which includes the ability to select a specific Unit Test structure to accompany their Web Application development.

The MVC framework is fully extensible at all points, allowing developers to create sophisticated structures that meet their needs, including for example Dependency Injection (DI) techniques, new view rendering engines or specialized controllers.

As the ASP.NET MVC framework is built on ASP.NET 3.5, developers can take advantage of many existing ASP.NET 3.5 features, such as localization, authorization, Profile etc.

Update: Phil Haack just posted his MVC 1.0 Release Anouncement.

Tags:

Posted in ASP.NET, News | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

March 18th, 2009

The State of ALT.NET

Over the past 6 months I have been trying to really quantify what it means to be using ALT.NET practices. And I can honestly say that I still honestly don’t know what it means to be an ALT.NETer. But I have come to a number of conclusions about the state of the ALT.NET community, that I wanted to share.

(1) The ALT.NET Community is fractured among itself.

There are too many different ways of out there of what it means to be a true ALT.NETer. There is the Test Driven Design crowd, there is the Domain Driven Design crowd, and to many other Driven Design paradigms to mention right now. Each advocate will stand up and say that their way is the only way to develop a true ALT.NET application, and all other ways are an abomination to software development.

From this point forward…

We need to understand that it doesn’t matter what paradigm you choose to follow or even if it has a name, just that you choose a way to design your application before you start coding. And as long as the way you choose to code is robust, easy to maintain, and easy for another developer to pick up where you left off — you are doing it right.

(2) Take the religious zealotry out of ALT.NET

This sort of goes back to #1, but I feel that it needs to be called out directly. There are too many people out there preaching about how their brand of ALT.NET is the only path to salvation from the drudgery of everyday .NET programming. I have heard from a number of people that you don’t have a true ALT.NET application unless you are using an IoC library, nHibernate, and separate your domain model in to a separate project library away from your data access layer. These types of strict requirements and zealotry for one type of component set the bar way to high for any average developer to say they are following the ALT.NET principals.

From this point forward…

It is an acceptable practice to use what ever makes the most sense for your project and your team. For example if you need IoC container and it makes your life easier as a developer to build the framework of your application you should use it, on the flip side if your application is pretty static and there is no need to have these swappable containers you should feel free to not use IoC containers until your application requirements dictate they are needed.

(3) Craftsmanship with out Engineering is no way to program software.

There seems to be a very strong focus on craftsmanship over standard engineering processes in the ALT.NET community. It seems like each week there is a new hot craftsmanship feature from some other language that is trying to be replicated in .NET. Lately it has been the focus of fluent API’s and the duck typing features that dynamic languages like Ruby have built in to their frameworks. This constant change and focus on new hot must have craftsmanship features really detracts from good solid software engineering principals that should be the focus of the ALT.NET education process.

K. Scott Allen had a really good analogy of this focus on craftsmanship over solid engineering of your code. He called it the Aluminum Wiring in side your software. In his article he talked about how the shortage of copper in the US during the 60’s and 70’s caused home construction to use Aluminum wiring over Copper wiring in houses, and how the use of Aluminum caused oxidization, corrosion, and overheating of the houses electrical system. He then went on to ask if all these new craftsmanship features are going to cause the same problems in software development and he specifically called out:

  • Mock objects
  • Fluent APIs
  • Declarative programming

I believe K. Scott is not to far from the truth, because we are sacrificing good engineering practices for what really amounts to programmer candy, just like the US construction industry sacrificed good engineering materials to save a few dollars.  It didn’t pay off for the home owners in the long run, and I surmise that this focus on craftsmanship will not pay off for the software in the long run either.

From this point forward…

We need to focus on good software engineering over the latest fad in software programming.  Currently the latest fad is making C# work like Ruby.  But it is just that a fad, that will quickly fade away when something new comes along.  It is basically the programmers equivalent of the rise and fall of Paris Hilton in the media.  Ruby is a nice language and has its niche purposes on the web, however there is a reason why Ruby doesn’t run mission critical applications (ex. financial systems) like C#, C++, or Java does, it simply doesn’t scale all that well.  Only time will tell if it will be around for the long haul or fade way in to the abyss of languages that grace this earth for only a short time.  But either way we shouldn’t be making business critical changes to the way we engineer software applications based on the craftsmanship of the newest language to hit the streets.

Conclusion

My conclusion is a short one on the state of ALT.NET. From everything I have learned over the past 6 months and the immersion in the tools that have come from the ALT.NET community, I have really come to one conclusion that seems to sum them all up.

ALT.NET started with some really down to earth goals of educating .NET developers about alternatives to developing software, by taking principals from other languages and frameworks and integrating them in to the .NET developers thought process. However this simple mission statement has seemed to have morphed into zealotry for design practices and certain tools and an obsession to always change the .NET framework to work more like the latest fad instead of forging out the best practices from other languages and frameworks. The state of ALT.NET is that it is broken, because it seems to be governed by a disorganized committee of bloggers with their own agendas. ALT.NET needs a hero, and that hero just needs to set down some commandments that all other ALT.NET conversations are governed by. See Update Below This is the only way the ALT.NET movement is going to survive the test of time.

This isn’t going to be an easy task, but I am willing to work with anybody who wants to form a working group to explorer the creation of these ALT.NET Commandments. If you are interested please click the Contact link above and maybe we can get something moving to help ALT.NET survive the test of time.

Update: Lee Drumond pointed out something that I didn’t consider about what I said above, and it probably should be rephrased so it is not taken the wrong way.  I had said:

ALT.NET needs a hero, and that hero just needs to set down some commandments that all other ALT.NET conversations are governed by… I am willing to work with anybody who wants to form a working group to explore the creation of these ALT.NET Commandments.

This should have actually went something like this…  ALT.NET needs a commitee thats sole focus is on advancing the principals of ALT.NET forward and breaking down the bariers in corporations through education.  Once corporations see the benifits of ALT.NET, developers will be finacially modivated to learn the ALT.NET ways, to keep and advance their own careers.  If the movement is not organized, it is nothing more than a social group that may gain a couple followers here and there, and really piss off others, just like any social group would.

By the way nothing I have said here is anything new to the ALT.NET community, it has all been said and repeated many times over in different ways and different formats.  Unfortunately it is usually met with the same reactions, as Jeremy has commented below, and very little retrospective seems to be happening.  Everything just moves forward as the status quo, as if there is nothing wrong with the fact that the same concerns are voiced over and over again.

Tags: ,

Posted in Programming, Rant | kick it on DotNetKicks.com | Bookmark | View blog reactions | 26 Comments »

March 3rd, 2009

ASP.NET MVC 1.0 Release Candidate 2

Final Cover PhotoPhil Haack has announced the availability of ASP.NET MVC 1.0 Release Candidate 2.

You can download the new version from Microsoft. Source code and samples are also available on the ASP.NET CodePlex workspace.

Overall, this new version doesn’t have many changes in the area of development and tooling, but there has been improvement for deploying ASP.NET MVC applications.  The setup process now requires .NET 3.5 SP1 to be installed, where in the past it was optional because the additional assemblies where included with the install.

Don’t worry though /bin deployment is still supported, they are not taking a runtime dependency on SP1 other than our existing dependency on System.Web.Routing.dll and System.Web.Abstractions.dll. Thus you can still bin deploy your application to a hosting provider who has .NET 3.5 installed without SP1 by following these instructions.

They are also adding an option to the installer that enables installing on a server that does not have Visual Studio at all on the machine, which is useful for production servers and hosting providers.  To do a server install you just need to run the following command to install MVC on your server.

msiexec /i AspNetMvc-setup.msi /q /l*v .\mvc.log MVC_SERVER_INSTALL="YES"

Also because of the latest breaking changes from Beta to RC 1 & 2, we are taking the time between now and the final release of the MVC Framework to work on the book and make sure all the loose ends are tied up.

I also got noticed today that our final cover design is done.  So we are in the final stretch of this book.  The cover hasn’t been uploaded to Amazon yet, but if you are interested in pre-ordering a copy just click on the cover image to your right and it will take you to the Amazon page where you can place your order.

Tags: , ,

Posted in ASP.NET, News, Personal, Portfolio, Review, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | 2 Comments »

February 17th, 2009

TF30042: The database is full. Contact your Team Foundation Server administrator.

Today I received the following error while trying to check in some code after a marathon night of coding:

TF30042: The database is full. Contact your Team Foundation Server administrator.

I got one of those “oh crap” sinking feelings, that some how my TFS server had decided to just die.  After doing a little research on this error, which there is very little (read close to none) information about on the internet.  So I gave up searching and decided to do a little trial and error adhock testing, and I found out that this error has nothing to do with the database but everything to do with the size of the database’s log file.  I came up with the following solution, that you will want to run in Microsoft SQL Server Management Studio:

WARNING!!! My TFS server is in a non-production environment and I am basically the only one who uses it.  Make sure to check with your network administrator and make a back up before you run the following code.

USE [master]

ALTER DATABASE [ReportServer] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [ReportServerTempDB] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsWorkItemTracking] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsIntegration] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsVersionControl] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsWorkItemTrackingAttachments] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsActivityLogging] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TfsBuild] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [STS_Config_TFS] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [STS_Content_TFS] SET RECOVERY SIMPLE WITH NO_WAIT
ALTER DATABASE [TFSWarehouse] SET RECOVERY SIMPLE WITH NO_WAIT

ALTER DATABASE [ReportServer] SET RECOVERY SIMPLE
ALTER DATABASE [ReportServerTempDB] SET RECOVERY SIMPLE
ALTER DATABASE [TfsWorkItemTracking] SET RECOVERY SIMPLE
ALTER DATABASE [TfsIntegration] SET RECOVERY SIMPLE
ALTER DATABASE [TfsVersionControl] SET RECOVERY SIMPLE
ALTER DATABASE [TfsWorkItemTrackingAttachments] SET RECOVERY SIMPLE
ALTER DATABASE [TfsActivityLogging] SET RECOVERY SIMPLE
ALTER DATABASE [TfsBuild] SET RECOVERY SIMPLE
ALTER DATABASE [STS_Config_TFS] SET RECOVERY SIMPLE
ALTER DATABASE [STS_Content_TFS] SET RECOVERY SIMPLE
ALTER DATABASE [TFSWarehouse] SET RECOVERY SIMPLE 

DBCC SHRINKDATABASE(N'ReportServer')
DBCC SHRINKDATABASE(N'ReportServerTempDB')
DBCC SHRINKDATABASE(N'TfsWorkItemTracking')
DBCC SHRINKDATABASE(N'TfsIntegration')
DBCC SHRINKDATABASE(N'TfsVersionControl')
DBCC SHRINKDATABASE(N'TfsWorkItemTrackingAttachments')
DBCC SHRINKDATABASE(N'TfsActivityLogging')
DBCC SHRINKDATABASE(N'TfsBuild')
DBCC SHRINKDATABASE(N'STS_Config_TFS')
DBCC SHRINKDATABASE(N'STS_Content_TFS')
DBCC SHRINKDATABASE(N'TFSWarehouse')

The above code will actually put all the TFS databases in Simple Recovery mode, which basically means no log file, and then shrinks all the log files that were previously in use. After you run this script in Microsoft SQL Server Management Studio you should not get this error message anymore, when you try to check in your files.

Tags: , ,

Posted in How To, SQL | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

February 3rd, 2009

A potentially dangerous Request.Form value was detected in ASP.NET MVC

If you are getting something like the following error message in ASP.NET MVC:

A potentially dangerous Request.Form value was detected from the client (Description=”<p>some HTML text</p>”)

This is because of something called Request Validation, that is a feature put in place to protect your application cross site scripting attacks, as described in a White Paper on ASP.NET:

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

You need to add the following to your action method:

[ValidateInput(false)]
public ActionResult MyAction (int id, string content) {
    // ...
}

This is a new feature that was added to ASP.NET MVC RC1 and it will turn off request validation for this action and this action only. However you need to take special precautions to double check your content for script tags, which may indicate a cross site scripting attack. And if you find one make sure to do a simple replace that will render it harmless, such as:

content = content.Replace("<script", "[script").Replace("</script>","[/script]");

The above is not the most bullet proof code, but if you are using the ValidateInputAttribute on your action make sure to do a quick search on XSS or Cross Site Scripting and become familiar with the basics of this kind of attack.

Tags: ,

Posted in ASP.NET | kick it on DotNetKicks.com | Bookmark | View blog reactions | 9 Comments »