ASP.net MVC Archives - Page 3 of 5 - Digital Tool Factory blog ASP.net MVC Archives - Page 3 of 5 - Digital Tool Factory blog

The Digital Tool Factory Blog

How to fix Visual Studio slowness problems by deleting ExpansionsXML.xml

The Problem

'Program Guy 1' photo (c) 2009, Briles Takes Pictures - license: http://creativecommons.org/licenses/by/2.0/I’ve had Visual Studio 2010 installed from the first day it was released, and lately it has gotten significantly slower.   That’s not surprising with an increased number of add-ons and extensions.  However, closing the program recently started taking an increasingly long period of time.  It recently reached OVER EIGHT MINUTES so I opted to do some googling.

The Cause

I started by installing PerfMon, and PerfMonWatson, which while telling me the computer was slow, did nothing to tell me of the nature of the problem.  Then I installed Process Monitor by the Sys Intenals division of Microsoft and watched what happened when I opened adn closed the Visual Studio 2010.

The result?  When you open or close Visual Studio 2010 a terrifying number of things happen, but in my case an xml,

C:Users[UserName]AppDataLocalMicrosoftVisualStudio10.01033ExpansionsXML.xml

was being accessed, read and closed several thousand times.  Apparently Visual Studio will do that when the file gets corrupted.

The Solution

Just delete the .xml file and everything should run normally.  Visual Studio 2010 regenerated the file, and it was about one fifth the size it was before.  Everything is working slightly faster in general, and it now closes at a normal speed.


22
Jun 12


Written By Steve French

 

How to fix “The system cannot find the path specified” error in asp.net mvc 4

The Problem:

So, you’re coding away, and you run your asp.net mvc 4 site and you get the following error: The system cannot find the path specified

The Cause:

Most likely you have not already specified the database in the web.config, it’s a simple fix.

The Solution:

Just add this code into the web.config

<add name=”BlogProphetsiteContext” connectionString=”Server=.SQLEXPRESS;Database=BlogProphetsite;Trusted_Connection=true;MultipleActiveResultSets=true” providerName=”System.Data.SqlClient” />

and all will be good. For some reason it does not automatically generate one for you.


08
Jun 12


Written By Steve French

 

How to fix problems running Windows Azure web applications locally

The Problem:

You have an asp.net mvc 3 web project, and you are running it as part of a windows azure web application.   In my case it worked initially, but after I installed some Visual Studio plugins, run Windows Update, and installed a new router, it mysteriously stopped working.  A few of the error messages had me thinking it was caused by Sql Server, but I was mistaken.

The Cause:

This stumped me for several hours, but after much trial and error I discovered that the problem was with port mapping.

In the output window, I had the following messages:

Windows Azure Tools: Warning: Remapping public port 80 to 87 to avoid conflict during emulation.
Windows Azure Tools: Warning: Remapping public port 3389 to 3390 to avoid conflict during emulation.
Windows Azure Tools: Warning: Remapping private port 80 to 89 in role ‘MyCoolSite’ to avoid conflict during emulation.
Windows Azure Tools: Warning: Remapping private port 3389 to 3390 in role ‘MyCoolSite’ to avoid conflict during emulation.

I had enabled a homegroup somewhere along the way, which changed my network location, which somehow made changes in the firewall.

The Solution

This was more blind luck, but I got a windows firewall popup that asked me if I wanted to allow the Visual Studio Process to use lo these many ports.

So, in sum, check to make sure all of your ports are open.


15
May 12


Written By Steve French

 

How to programatically set the sql server database used by entity framework

The Problem:

'Entity Framework' photo (c) 2009, SondreB - license: http://creativecommons.org/licenses/by/2.0/For one reason or another you need to set the database used by entity framework programatically.  The more common way of doing such a thing is to set the database in your web.config class, but for whatever reason you need to set it in actual C# code.

The Cause:

There is no cause really, it is merely the way that entity framework and sql server work together.

The Solution:

The answer lies in setting the constructor properly.

Example Code Using Entity Framework and Data Context

using System.Data.Entity;

namespace MyDBServerExperiments.Models
{
public class DTFContext : DbContext
{
public DTFContext() : base(“Data Source=MyDBServer.DBServer.com;Initial Catalog=MyEntityFrameworkDB;Persist Security Info=True;user id=MyUsername; Password=MyPassword;”) { }

public DbSet<User> Users { get; set; }
public DbSet<BusinessObjects> BusinessObjects { get; set; }
public DbSet<Property> Properties { get; set; }

}

}

The above would be your data context file that uses the DBContext file  in your models folder, just fyi (that is the common place for Entity Framework models in the standard  Visual Studio 2010 web solution structure).

Note, everything happens in the constructor.  This give you many interesting opportunities to programatically swap out Sql Server database names and users, compared to the web.config option, which tends to be far more static.  It allows far more extensive use of business objects and


24
Apr 12


Written By Steve French

 

How to use UI Hints and Display Templates in ASP.net MVC 3

'wtf - code quality measurement' photo (c) 2008, smitty42 - license: http://creativecommons.org/licenses/by-nd/2.0/Surprisingly there is very little information about UI Hints and Display templates for ASP.net MVC 3, so I thought I would share what I have learned.

What are Display Templates?

Display Templates are lovely features of ASP.net MVC 3 that allow you to have a common formatting for certain properties of your objects.  For example, take the belowp roperty (which should be located in your models folder)

[DataType(DataType.ImageUrl)]
[UIHint(“ImageUrl”)]
[Display(Name = “Photo”)]
public string Photo { get; set; }

Everything looks like a standard property, UIHint property.  It would correspond to the Display Template (which is below, it would be name “ImageUrl.cshtml” and would be located in your Views/Shared/DisplayTemplates folder)

@model string
<img style=”display: block;” src=”@Model” alt=”” align=”right” />

What does the UI Hint do?

The UI Hint tells ASP.net MVC 3 to always display the Photo property using the formatting in the ImageUrl.cshtml file.  That way everything is nice, clean and using much less code.

How do you call UI Hints and Display Templates?

Just use the Html.DisplayFor command, for example the Display template below would look like this in Visual Studio 2010

@Html.DisplayFor(xx => xx.Photo)

and would render as

<img style=”display: block;” src=”/img/Photos/Photo123.png” alt=”” align=”right” />

in the browser, allowing you to keep formatting and style consistent across your entire site with very little effort.

 


10
Apr 12


Written By Steve French

 

How to fix the Initialization method TestInitialize threw exception problem in In Visual Studio 2010 Unit Testing

The Problem

You are making an ASP.net MVC 3 web application, and being a good person, you are unit testing as much as possible.  You have properly separated your database from your business objects and every other good practice.  However, when you unit test your controllers, you throw in a fake DBContext (I am assuming you are using the Entity Framework and Moq) and all of a sudden, you get the following error

<b>Failed 1 tests.</b>
Initialization method [YourTestClass].TestInitialize threw exception. System.ArgumentNullException: System.ArgumentNullException: Value cannot be null.
Parameter name: source.

Which certainly makes for one of the least helpful error messages of all time.

The Cause

The problem seems to be lazy loading and the DBSet Feature of Entity Framework.  For example the below passage in your source code below will throw the error

public virtual DbSet<Setting> Settings { get; set; }
public virtual DbSet<AccountSource> AccountSources { get; set; }

This bit of code will not thow the error

public DbSet<Setting> Settings { get; set; }
public DbSet<AccountSource> AccountSources { get; set; }

The problem seems to be entirely in the initialization method.

The Solution

Rather irritating isn’t it?  Especially since Lazy Loading is the design pattern to use, and works great in every other case.  However, if you just delete the “virtual” keyword everything works as intended.

 


03
Apr 12


Written By Steve French

 

How to fix problems with asp.net mvc 3 and jQuery UI AutoComplete

The Problem:

You’re tooling along, using the jQuery library to write some great search feature, and you write some great Linq to Sql code.  Being an awesome coder your use the extension method syntax.  Your action result (in the appropriate controller) looks like this

public ActionResult QuickSearch(string term)
{
var lst = context.Contacts.Select(xx => new {FullName= xx.FirstName +” ” + xx.LastName }).Where(xx => xx.label.ToUpper().Contains(term.ToUpper())).ToList();
return Json(lst,JsonRequestBehavior.AllowGet);
}

And for no good reason, you get no results when you try to search for a contact.  All you get is a blank drop down.  Why has jQuery UI failed you?  Why must javascript code always be so finicky?

The Cause:

For good reason Jquery UI Autocomplete uses JSon for remote data.  It looks for a predefined format, and it wants that name to be called “label”.  It is case sensitive.

The Solution:

Just change your ActionResult to look like this

public ActionResult QuickSearch(string term)
{
var lst = context.Contacts.Select(xx => new {label= xx.FirstName +” ” + xx.LastName }).Where(xx => xx.label.ToUpper().Contains(term.ToUpper())).ToList();
return Json(lst,JsonRequestBehavior.AllowGet);
}

and you will be golden.  Please note I changed FullName to label.  Jquery UI Autocomplete is a very nice and useful tool, but it demands to work on it’s own terms.  Beyond that I have never had a problem with this wonderful bit of ajax goodness.


29
Mar 12


Written By Steve French

 

How to fix the Entity Framework Code First problem – Model compatibility cannot be checked because the database does not contain model metadata problem

The Problem

So, you are tooling around in asp.net mvc 3 Entity Framework Code First, and you make a change to your underlying model.  you then get the following error when Entity Framework tries to recreate the database in Sql Server or Sql Server Express

Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.

The Cause

You still have some lock on the database in some way, perhaps you still have the database open in Visual Studio (it is very easy to do this in Visual Studio 2010) or perhaps you have it open in a Sql Server Management Studio window.  Perhaps Windows just doesn’t like you.  In any case, it’s that database is open, and Entity Framework Code First will not drop the database if anyone is still using it.

The Solution

You have to release all locks and holds on the database before Entity Framework Code First will drop the database.  To do that, open up Sql Server Management Studio and paste in the following code

USE [master]
GO

/****** Object: Database [MyDBname] Script Date: 02/24/2012 13:54:40 ******/
ALTER DATABASE [MyDBname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE [MyDBname] SET SINGLE_USER WITH NO_WAIT
DROP DATABASE [MyDBname]
GO

That will isolate your database (please note that “MyDBName” is where you should put your database name) and allow Entity Framework CodeFirst to drop and recreate the database and implement your changes.  Doing this WILL drop the database, so be careful.


06
Mar 12


Written By Steve French

 

ASP.Net MVC 3 In Review – One Year Later

'F'kin Computers.' photo (c) 2011, Cameron - license: http://creativecommons.org/licenses/by-sa/2.0/It’s been a little over a year since I’ve devoted myself to Asp.net MVC 3 and on the whole I’m quite impressed.  Microsoft seems to have picked a definite direction for the web (the Microsoft Web Platform Installer makes a nice guide for it), and I like it.  Here is my broad review, please bear in mind I’ve been doing asp.net webforms for about ten years.

The Pros of ASP.Net MVC 3

  1. The Razor View Engine – Brevity is wonderful
  2. The integration with Sql Server and Entity Framework CodeFirst
  3.  The full integration with JQuery
  4. The bare metal approach to html, it is much easier to find bugs in the code when there is less code.
  5. The full integration with Visual Studio 2010 – it is nice to have the platform and the IDE work fully together
  6. NuGet!  The single best way to install add-ons.
  7. The ease of testing your code via the test capabilities of Visual Studio

 

The Cons of ASP.Net MVC 3

  1. It is a pain to test actual data.  With the advent of code-first one would think that you could simply have a test database, but there is no way.  One has to use db fakes, which makes your entire testing a bit less useful.
  2. Coded User Interface Tests are not baked into the system in any way, and for no particular reason one cannot have CUITS in the same solution as the most popular ASP.net  MVC 3 scaffolding packages.

On the whole, I am a huge fan – for more information about it, check out the wonderful work that Shawn Wildermuth and Scott Hanselman have been doing.


14
Feb 12


Written By Steve French

 

How to fix more problems with ASP.net MVC 3 RouteValues

The Problem

You want to create urls that look something like http://SomeSite.com/Categories/Industrial/Fasteners/3.8-MM-Titanium-Wrench-Bolts/ so your site can rank extra high when people search for those profitable 3.8 MM Titanium Wrench Bolts. And in natural, RESTful fashion, your site and database is structured so that the Wrench Bolts are in a subcategory of Fasteners, which are part of the Industrial Category

The Cause:

None really, I’m just listing how one does this sort of thing.

The Solution

Firstly you have to define your route in your global.asax file, in the Register Routes section

routes.MapRoute(
“ItemInd”, // Route name
“Categories/{CategoryName}/{SubCategoryName}/{id}”, // URL with parameters
new { controller = “Product”, action = “Details”, CategoryName = “”, SubCategoryName = “”, id = “” } // Parameter defaults
);

a
Then you have to set your Route Values
Here is an ActionLink helper –

@Html.ActionLink(p.Name, “Details”, new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name })

And if you want to use the URL.Action helper, here is what that would look like.

<a href=”@Url.Action(“Details”, “Product”, new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name })”>Some Text</a>

as you might suspect, the new { controller = “Product”, action = “Details”, CategoryName = p.SubCategory.Category.Name, SubCategoryName = p.SubCategory.Name, id = p.Name } maps exactly to the corresponding parts in the global.asax file.

This wasn’t really a how to fix problem, but really more about using asp.net mvc 3 RouteValues.  I’ve found a lack of documentation on how to make relatively complicated urls, so I thought this would be a start!


14
Feb 12


Written By Steve French

 




Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.