European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 3 Hosting :: Handling errors in ASP.NET MVC 3

clock July 25, 2011 08:15 by author Scott

With the arrival of ASP.NET MVC 3, it is very easy for us to handle errors in ASP.NET MVC.

The HandleErrorAttribute in ASP.NET MVC lets us specify how to handle an exception that is thrown by an action method. By default, when an action method with the HandleErrorAttribute throws an exception, MVC displays the Error view that is located in the ~/Views/Shared folder.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)


{


    filters.Add(new HandleErrorAttribute());

}


This filter automatically applies to any action method in any controller so that you don’t have to apply HandleErrorAttribute action level or controller level.

If user makes a request for web.config file (http://yourDomain.com/web.config), and we know that MVC restricts this request and throws an exception that is uncatchable by HandleErrorAttribute because HandleErrorAttribute just handles errors that are thrown by action methods. So for above case, traditional asp.net error window will be displayed.

Here is a diagram that show how HandleErrorAttribute works?



So how to handle errors that are not thrown by any action method means that errors those are unhandled or uncaught able by HandleErrorAttribute.

It’s simple, just create a new file ‘Error.aspx’ in the root of the project and update web.config file with this code snippet:

<customErrors mode="On" redirectMode="ResponseRewrite"


              defaultRedirect="Error.aspx" />

Now, whenever an error thrown by any action method, HandleErrorAttribute are asked to handle it and ~/Views/Shared/Error.aspx view will be displayed. In contrast, when an unhandled error will occur that is not thrown by any action method, this Error.aspx file will be displayed to end user.

If you want to know what unhandled error was and you want to be informed through email, it is simple, just do it:

// for Sending Error in Email


protected void Page_Load(object sender, EventArgs e)


{


   string subject = "An unhandled Error Message";


   string body = HttpContext.Current.Server


                     .GetLastError().ToString();


    subject.SendErrorMessage(body);


}


public static void SendErrorLive(this string subject,


string body)


{


    WebMail.From = “[email protected]”;


    WebMail.Password = “password”;


    WebMail.SmtpPort = 25;


    WebMail.SmtpServer = “smtp.live.com”;


    WebMail.UserName = “[email protected]”;


    WebMail.EnableSsl = true;


    WebMail.SmtpUseDefaultCredentials = false;


    WebMail.Send(“[email protected]”, subject, body);


}

Oh no, this technique is for Error.aspx but what for ~/Views/Shared/Error.cshtml?

By default, asp.net mvc passes HandleErrorInfo type to the Error.cshtml view. This type let us directly get error info as shown here:

@Model.Exception.Message

Or directly send email within the view:

@{Model.Exception.GetType().ToString()


.SendErrorMessage(Model.Exception.ToString());}

Now following errors are under your control:

1. Errors that are thrown by action methods [~/Views/Shared/Error.cshtml]
2. Any other kind of errors [Error.aspx]



European ASP.NET MVC 3 Hosting :: ASP.NET MVC3 Tools Update – Scaffolding with the Repository Pattern

clock July 8, 2011 08:28 by author Scott

In this post I’m going to show you how to use MvcScaffolding to add a new controller template to enable scaffolding with data access code that uses the Repository Pattern.

One of the new features is built in tooling support for scaffolding. The “Add Controller” Dialog box has been revamped to include a few new options.

As you can see there are much more options as compared to before. The scaffolding options are as follows:

- Template: Allow you to specificy what kind of controller you want to generate. Out of the box you get an empty controller (Just a class with no actions), Controller with actions and views using the Entity Framework code first, and controller with empty read/write actions.

- Model: This is the object that will be used for scaffolding strongly typed views, CRUD actions and data access.

- DataContext: By default this is an EF Code First class that inherits from DbContext. You can either select an existing context or have the scaffolding tools create a new one for you.

- Views: Select between ASPX and Razor. This is pretty much the same as the “Add New View” dialog box.

- Advanced Options include layout/master page settings and View script settings. Again, stuff that is also in the “Add New View” Dialog.



Scaffolding using the “Controller with read/write actions and views, using Entity Framework” is especially cool because it generates a controller, all associated views AND data access code for you. That’s right, all you need to do is create an model class and the scaffolder does the rest. How’s that for a productivity boost?


To test this I created a simple Product class which is defined as the following:

public class Product{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}


Then I added a new controller with the following options:



The new tooling support created a new controller, all associated views and the data access code. That’s really cool, but let’s take a look at the controller code.

private ProductContext db = new ProductContext();
 //
// GET: /Product/
 public ViewResult Index()
{
return View(db.Products.ToList());
}


By default the scaffolding tools use the ProductContext object directly in the Controller. Many people don’t like this coupling (myself included) and prefer to use
the Repository Pattern. This allows us to abstract away our data access code behind a repository, making it easier to work with and later modify, if need be.

Well the good news is that the add controller dialog is extensible. You can add your own controller templates to enable data access using any technology mechanism you want.

I’m going to show you a way to get a repository option for EntityFramework to show up with very little work. All you need to do is install the MvcScaffolding NuGet Package.

Open the Package Manager Console and enter “Install-Package MvcScaffolding”:



Now right click on the controllers folder and select “Add”->”Controller”. We’re going to re-scaffold out our ProductController, associated views and data access code (WARNING: This will overwrite any changes you have made so be careful.)

Now take a look at the templates section and you should see new templates:



The last option let’s you scaffold out the entire thing and use repositories for data access. Go ahead and click “Add”. Check the checkboxes to allow the scaffolder to override existing items.

We can verify this by looking at our ProductController and we should see the following:

private readonly IProductRepository productRepository;

// If you are using Dependency Injection, you can delete the following constructor
public ProductController() : this(new ProductRepository()) { }
 public ProductController(IProductRepository productRepository) {
this.productRepository = productRepository;
}

//
// GET: /Product/
 public ViewResult Index(){
return View(productRepository.All);
}

Now the controller uses a repository instead of hard coding in the data access code. The repository itself uses EF Code First to do all the data access.



European ASP.NET MVC Hosting :: ASP.NET MVC Routing Tutorial

clock July 7, 2011 07:23 by author Scott

In this tutorial, you are introduced to an important feature of every ASP.NET MVC application called ASP.NET Routing. The ASP.NET Routing module is responsible for mapping incoming browser requests to particular MVC controller actions. By the end of this tutorial, you will understand how the standard route table maps requests to controller actions.

Using the Default Route Table

When you create a new ASP.NET MVC application, the application is already configured to use ASP.NET Routing. ASP.NET Routing is setup in two places.

First, ASP.NET Routing is enabled in your application's Web configuration file (Web.config file). There are four sections in the configuration file that are relevant to routing: the system.web.httpModules section, the system.web.httpHandlers section, the system.webserver.modules section, and the system.webserver.handlers section. Be careful not to delete these sections because without these sections routing will no longer work.

Second, and more importantly, a route table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event.

The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.

Listing 1 - Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

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

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.

Imagine that you enter the following URL into your web browser's address bar:

/Home/Index/3

The Default route maps this URL to the following parameters:

controller = Home

action = Index

id = 3

When you request the URL /Home/Index/3, the following code is executed:

HomeController.Index(3)

The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Home. If you don't supply an action, the action parameter defaults to the value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.

Let's look at a few examples of how the Default route maps URLs to controller actions. Imagine that you enter the following URL into your browser address bar:

/Home

Because of the Default route parameter defaults, entering this URL will cause the Index() method of the HomeController class in Listing 2 to be called.

Listing 2 - HomeController.cs

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(string id)
        {
            return View();
        }
    }
}

In Listing 2, the HomeController class includes a method named Index() that accepts a single parameter named Id. The URL /Home causes the Index() method to be called with an empty string as the value of the Id parameter.

Because of the way that the MVC framework invokes controller actions, the URL /Home also matches the Index() method of the HomeController class in Listing 3.

Listing 3 - HomeController.cs (Index action with no parameter)

using System.Web.Mvc;


namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

The Index() method in Listing 3 does not accept any parameters. The URL /Home will cause this Index() method to be called. The URL /Home/Index/3 also invokes this method (the Id is ignored).

The URL /Home also matches the Index() method of the HomeController class in Listing 4.

Listing 4 - HomeController.cs (Index action with nullable parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            return View();
        }
    }
}

In Listing 4, the Index() method has one Integer parameter. Because the parameter is a nullable parameter (can have the value Null), the Index() can be called without raising an error.

Finally, invoking the Index() method in Listing 5 with the URL /Home causes an exception since the Id parameter is not a nullable parameter. If you attempt to invoke the Index() method then you get the error displayed in Figure 1.

Listing 5 - HomeController.cs (Index action with Id parameter)

using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int id)
        {
            return View();
        }
    }
}



The URL /Home/Index/3, on the other hand, works just fine with the Index controller action in Listing 5. The request /Home/Index/3 causes the Index() method to be called with an Id parameter that has the value 3.

Summary

The goal of this tutorial was to provide you with a brief introduction to ASP.NET Routing. We examined the default route table that you get with a new ASP.NET MVC application. You learned how the default route maps URLs to controller actions. Hope the tutorial can help and give benefit for all of you.



European ASP.NET MVC 3 Hosting :: Remote Validation in ASP.NET MVC 3 RC1

clock June 22, 2011 06:35 by author Scott

Remote validation has finally landed in RC1 of ASP.NET MVC 3.  It’s a weird area as more often than not people tend to over complicate something that is really pretty simple.  Thankfully the MVC implementation is fairly straightforward by simply providing wiring allowing the jQuery Validation plugin to work it's magic.  Basically there is a new Remote attribute that can be used like so.

public class Credentials
{   
    [Remote("Username", "Validation")]
    public string Username { get; set; }    

    public string Password { get; set; }
}

As you can see we have attributed the Username field with a Remote attribute.  The 2 parameters tell us what Action and Controller we should call to perform the validation.  This does make me feel slightly uneasy as it kind of feels like you are coupling the controller to the model which doesn't sit right by me.  currently sitting on the fence I'll see how it works in real life.  Anyway I implemented it like so,

public class ValidationController : Controller
{    public ActionResult Username(string UserName)
    {
        return Json(Repository.UserExists(Username), JsonRequestBehavior.AllowGet);
    }
}

And thats you - provided you have the necessary client side libraries included of course (jQuery, jQuery Validate etc). and have Client Side Validation turned on (now by default in MVC3).


Configuration

The Remote attribute offers a few nice little configuration options to make things easier.  The typical ones are there such as ErrorMessage, ErrorResource etc. but there are a few specific ones as well.

Fields

There may be a case where ding the name and the value of a single form field isn’t enough to perform validation.  Perhaps validation is affected by some other field/value in the form.  The Remote attribute accepts a comma separated list of other fields that need to be sent up with the request using the Fields parameter

This basic example will send up the value of the EmailService input field along with the value of Username.  Clean and simple.

[Remote("Username", "Validation", Fields = "EmailService")]

HttpMethod

HttpMethod simply allows us to change how the ajax request is sent e.g. via POST or GET or anything else that makes sense.  So to send a remote request via POST

[Remote("Username", "Validation", HttpMethod = "POST")]

A Minor Difference

You might notice if you read the release notes for RC1 that my implementation of the controller is slightly different.  The reason being that the example in the release notes is broken :-).  The example looks like this

public class UsersController {
    public bool UserNameAvailable(string username) {
        return !MyRepository.UserNameExists(username);
    }
}

However the Validate plugin expects a JSON response which is fine on the surface but returning a boolean response to the client side results in a response body of False (notice the captial F) which in turn causes a parse error when the plugin performs JSON.parse.  My suggested solution is actually more inline with how most people would typically write an Ajax capable controller action anyway (though I am not happy with the JsonRequestBehaviour usage) but there are other ways but they aren’t pretty….

public class ValidationController : Controller
{       
    public string Username(string username)
    {
        return (!Repository.UserExists(Username)).ToString().ToLower();
    }
}

See?  Ugly and plain WRONG (but it will work).

Nice to see this feature finally landing as it can be useful in certain situations.



European ASP.NET MVC 3 Hosting :: Error 0x80070643 When Install ASP.NET MVC 3, How to Fix It?

clock June 9, 2011 05:00 by author Scott

Have you ever get this error message when you installed your ASP.NET MVC 3?



This is the steps that I took to fix it:

1. Remove the trailing backslash from the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0\Path

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\4.0.30319.0\Path

2. Uninstalled the old version of "Microsoft ASP.NET Web Pages".

3. Add the trailing backslash back to those keys.

4. Install MVC 3.



Good luck!!



European ASP.NET MVC 3 Hosting :: Get Selected Row from ASP.NET MVC 3 WebGrid

clock June 2, 2011 06:00 by author Scott

Every website has to display data and every website has a Grid control. In ASP.NET MVC 3 there’s the WebGrid, which is part of the Microsoft Web Helpers library. This can be downloaded through NuGet (formerly NuPack). NuGet is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. One piece of functionality that is critical is reacting when the user selects an item in the WebGrid. This article will focus on finding out which row was selected, but also how to find out more about the data that is selected.

Before moving on, you need to download ASP.NET MVC 3.
Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. To focus on the answer, I’ve got a simple model as seen below.



Using the WebGrid, it’s easy to display this data to the user.



The first column is the key to making this work. @item.GetSelectLink outputs a HTML anchor tag with the row selected. This is passed as a
QueryString, and the name of the QueryString is set by the selectionFieldName property set on the grid.



To find out what row is selected is just as easy. The WebGrid has a property called
SelectedRow. This sets a reference to a GridViewRow object that represents the selected row in the control. When you combine this with the HasSelection property, you can get the selected row like this.



I’ve created a partial view called _Person.cshtml. The file begins with an underscore (_) because I don’t want this file called directly from the web. The second parameter is the data being passed into the partial view. The data in this instance is the selected row.



Very easy, right??



European ASP.NET MVC 3 Hosting :: Scaffolding with the Repository Pattern in ASP.NET MVC 3

clock May 27, 2011 07:17 by author Scott

In this post I’m going to show you how to use MvcScaffolding to add a new controller template to enable scaffolding with data access code that uses the Repository Pattern.

One of the new features is built in tooling support for scaffolding. The “Add Controller” Dialog box has been revamped to include a few new options.



As you can see there are much more options as compared to before. The scaffolding options are as follows:

- Template: Allow you to specificy what kind of controller you want to generate. Out of the box you get an empty controller (Just a class with no actions), Controller with actions and views using the Entity Framework code first, and controller with empty read/write actions.
- Model: This is the object that will be used for scaffolding strongly typed views, CRUD actions and data access.
- DataContext: By default this is an EF Code First class that inherits from DbContext. You can either select an existing context or have the scaffolding tools create a new one for you.
- Views: Select between ASPX and Razor. This is pretty much the same as the “Add New View” dialog box.

Advanced Options include layout/master page settings and View script settings. Again, stuff that is also in the “Add New View” Dialog.



Scaffolding using the “Controller with read/write actions and views, using Entity Framework” is especially cool because it generates a controller, all associated views AND data access code for you. That’s right, all you need to do is create an model class and the scaffolder does the rest. How’s that for a productivity boost?


To test this I created a simple Product class which is defined as the following:

public class Product{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}

Then I added a new controller with the following options:



The new tooling support created a new controller, all associated views and the data access code. That’s really cool, but let’s take a look at the controller code.

private ProductContext db = new ProductContext();
 //
// GET: /Product/
 public ViewResult Index()
{
return View(db.Products.ToList());
}


By default the scaffolding tools use the ProductContext object directly in the Controller. Many people don’t like this coupling (myself included) and prefer to use
the Repository Pattern. This allows us to abstract away our data access code behind a repository, making it easier to work with and later modify, if need be.

Well the good news is that the add controller dialog is extensible. You can add your own controller templates to enable data access using any technology mechanism you want.

I’m going to show you a way to get a repository option for EntityFramework to show up with very little work. All you need to do is install the MvcScaffolding NuGet Package.

Open the Package Manager Console and enter “Install-Package MvcScaffolding”:



Now right click on the controllers folder and select “Add”->”Controller”. We’re going to re-scaffold out our ProductController, associated views and data access code (WARNING: This will overwrite any changes you have made so be careful.)

Now take a look at the templates section and you should see new templates:



The last option let’s you scaffold out the entire thing and use repositories for data access. Go ahead and click “Add”. Check the checkboxes to allow the scaffolder to override existing items.

We can verify this by looking at our ProductController and we should see the following:

private readonly IProductRepository productRepository;

// If you are using Dependency Injection, you can delete the following constructor
public ProductController() : this(new ProductRepository()) { }
 public ProductController(IProductRepository productRepository) {
this.productRepository = productRepository;
}

//
// GET: /Product/
 public ViewResult Index(){
return View(productRepository.All);
}

Now the controller uses a repository instead of hard coding in the data access code. The repository itself uses EF Code First to do all the data access.



HostForLife.eu Proudly Launches Premier European SQL 2008 R2 Hosting

clock May 24, 2011 06:27 by author Scott

HostForLIFE.eu was established to cater to an under served market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu – a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. We proudly announces the availability of the SQL 2008 R2 hosting in our entire servers environment. HostForlife customers have a choice between SQL Server 2008 and SQL 2008 R2 when creating a database from inside the HostForLife hosting control panel.

SQL Server 2008 R2 delivers several breakthrough capabilities that will enable your organization to scale database operations with confidence, improve IT and developer efficiency, and enable highly scalable and well managed Business Intelligence on a self-service basis for your users. For more information on SQL Server 2008 R2, visit the Microsoft website, http://www.microsoft.com/sqlserver/en/us/default.aspx.

Some of the capabilities that customers and partners will benefit from include:

1. PowerPivot: a managed self-service analysis solution that empowers end users to access, analyze and share data across the enterprise in an IT managed environment using Excel 2010 and SharePoint Sever 2010.
2. Master Data Services: helps IT organizations centrally manage critical data assets companywide and across diverse systems, and enables more people to securely manage master data directly, and ensure the integrity of information over time.
3. Application and Multi-server Management: helps organizations proactively manage database environments efficiently at scale through centralized visibility into resource utilization and streamlined consolidation and upgrade initiatives across the application lifecycle.
4. Report Builder 3.0: report authoring component with support for geospatial visualization. This new release provides capabilities to further increase end user productivity with enhanced wizards, more powerful visualizations, and intuitive authoring.
5. StreamInsight: a low latency complex event processing platform to help IT monitor, analyze and act on the data in motion to make more informed business decisions in near real-time.

For more information about this new product, please visit our site http://hostforlife.eu/SQL-2008-R2-European-Hosting.aspx.

About HostForLife

As a leading small to mid-sized business web hosting provider, we strive to offer the most technologically advanced hosting solutions available to our customers across the world. Security, reliability, and performance are at the core of our hosting operations to ensure each site and/or application hosted on our servers is highly secured and performs at optimum level. Unlike other web hosting companies, we do not overload our servers.



European ASP.NET MVC 3 Hosting :: Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package

clock May 19, 2011 08:24 by author Scott

Hello, today we will give brief explanation about how to Scaffold your ASP.NET MVC 3 project with the MvcScaffolding package. Before we move on, I have good information for all of you. We have supported the latest ASP.NET MVC 3. We are the one of the most providers that support ASP.NET MVC 3 in Europe. To preview this new product, please visit http://hostforlife.eu/ASPNET-MVC-3-European-Hosting.aspx. If you have further question about our new product, please contact us at here.

Back to this tutorial, let’s start it:

1. Install ASP.NET MVC 3, which includes the excellent NuGet Package Manager.
2. Create or open an ASP.NET MVC 3 web application. I’m calling mine ‘SoccerSite’.
3. Install the MvcScaffolding package. You can install it using the NuGet Package Manager Console, so it only takes a few seconds and you don’t have to download anything using your browser.  To do so,

- Open the Package Manager Console window using Visual Studio’s View->Other Windows->Package Manager Console menu item.
- Enter the following:

Install-Package MvcScaffolding



- That’s it! Note: be sure you installed MvcScaffolding, not MvcScaffold. We’ll retire the old MvcScaffold package shortly.

In case you’re wondering, EFCodeFirst is the new super-elegant version of Entity Framework that persists plain .NET objects to a relational database without any configuration fuss, T4Scaffolding is the core scaffolding infrastructure (locates types in your project, finds scaffolders in other packages, renders templates, etc), and MvcScaffolding is a set of ASP.NET MVC-specific templates (for controllers and views) that bolts onto the T4Scaffolding core.

Scaffolding a CRUD interface

Let’s create a model for a soccer team. Add the following class to your Models folder, then compile your solution (Ctrl-Shift-B):

namespace
SoccerSite.Models
{
    public class Team
    {
        public int TeamId { get; set; }
        [Required] public string Name { get; set; }
        public string City { get; set; }
        public DateTime Founded { get; set; }
    }
}

Next, we can create a complete Create-Read-Update-Delete (CRUD) UI for this model by issuing a single scaffolding command into the Package Manager Console:

Scaffold Controller Team

Note: You can use the TAB key to autocomplete many things in the Package Manager Console. In this case, you can autocomplete the words “Scaffold” and “Controller”, since the scaffolding package knows about them. It doesn’t know about “Team”, though – we may add completion on model type names in a future version.



As you can see, it’s gone ahead and created a controller, a database context (a tiny bit of Entity Framework code that represents a data store), and views for all the CRUD actions. You can run it right now (Shift-F5), and as long as you have SQL Server Express running on your machine, EFCodeFirst will automatically connect to it, create your database schema, and you’ve got a basic working application without writing a single line of procedural code.

Note that since the model was called “Team”, the controller is called “TeamController”, so to reach it you need to point your browser to
http://…/team:



The database is initially empty.



Creating an item. Validation rules are applied automatically. Note that since “Founded” is a DateTime it can’t be null and hence is required. Change it to DateTime? (i.e., with the question mark to make it nullable) if you want it to be optional.



Listing Items



Deleting an item

But what if I don’t have SQL Express installed?

If you don’t have SQL Express installed and running, you may have got the following error when your code tried to read or write some data:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Blah blah blah…

No problem! You can quickly switch to use the new SQL Server Compact – a lightweight, in-process database – without having to download or install anything manually. Simply add SQL Server Compact to your project by issuing the following command in the Package Manager Console:

Install-Package EFCodeFirst.SqlServerCompact

Ta da – no more external database required. Run your project again (Shift-F5) and this time it will create and connect to a file-based database (a .sdf file will appear in your ~/App_Data folder). The EFCodeFirst.SqlServerCompact package adds a file to your project called AppStart_SQLCEEntityFramework.cs, which configures the runtime to use SQL CE.


Of course you probably still want the proper version of SQL Server when you eventually deploy your application for public use, but for small applications or for learning, SQL CE is really handy.

Scaffolding a repository

If you check out the code right now, you’ll see that TeamController reads and writes the data in SoccerSiteContext directly. That’s fine in many simple scenarios, but if you want to decouple your controller logic from persistence logic a little (e.g., so that you can write clean unit tests for the controller), you may prefer to reach your data through an interface.

No problem! Let’s regenerate the controller with the –Repository flag:

Scaffold Controller Team –Repository –Force

Notice that we also need to say –Force, otherwise the scaffolder won’t overwrite the files you already have in your project. Now the scaffolder will produce an additional class, TeamRepository, and the following interface which TeamRepository implements:

    public interface ITeamRepository
    {
        void Add(Team post);
        void Delete(int id);
        IEnumerable<Team> GetAllTeams();
        Team GetById(int id);
        void Save();
    }

TeamController will now only read and write data using ITeamRepository. If you’re new to ASP.NET MVC it may not be obvious why this is desirable, but if you start trying to write unit tests or switch data access technologies, you’ll find this interface-based data access method to be much cleaner and more flexible.

There’s so much more

It’s not just about CRUD! You can use scaffolding to create any type of project item if you write a template for it. This blog post has covered only the absolute beginning of what you can do, so over the coming days I’ll write blog posts to cover:

- Scaffolding specific individual items (e.g., views, repositories, etc) rather than whole controllers and related files
- Getting additional scaffolder packages and controlling which ones are used by default. For example, there’s currently a proof-of-concept LINQ to SQL scaffolding package that you can install and set to act as the default type of repository/data context.
- Customising the T4 templates that the scaffolders use to generate code
- Creating entirely new custom scaffolders for new types of things (e.g., unit test fixtures)



European ASP.NET MVC 3 Hosting :: Working with ServiceLocator in ASP.NET MVC 3.0

clock May 4, 2011 06:44 by author Scott

What is Common Service Locator?Today we have many Inversion of Control/Dependency Injection Containers like NInject,StructureMap,Unity,.. etc in the .NET world.Most of these vary quite widely in terms of configuration and initialization/registration of the instances.But they provide more or less similar interface while resolving the dependencies and returning object instances.Common Service Locator framework extracts these commonalities out and provides an abstraction on top of these IoC/DI containers.This is now part of the Enterprise Library 5.0 and used in the Enterprise Library code to create/retrieve objects.Common Service Locator provides an interface IServiceLocator.



It is quite evident from the method signatures that these are only related to retrieval of right object instances with proper resolution of the dependencies based upon different parameters.

Another important class related to the Common Service Locator is the ActivationException which needs to be thrown whenever there is exception in instantiating the objects /resolving the dependencies.

We were planning to use StructureMap as the DI Container and a StructureMap Adapter for Service Locator was available in Codeplex but that seemed far from complete.

So we went ahead to write few lines of code and develop a service locator which will use StructureMap as the DI container as shown below:



This class accepts an instance of the StructureMap.Container in the constructor and uses it to resolve dependencies and instantiate objects.In the implementation of the IServiceLocator methods we have to just map them suitably to StructureMap.Container.GetAllInstances and StructureMap.Container.GetInstance methods (and their overloads).The code which depends on IServiceLocator will perform exception handling based on ActivationException class whereas StructureMap raises StructureMap.StructureMapException in most of the cases.So we need to catch StructureMapException in this class and throw a ActivationException.The complete code is given below:



So we have our Service Locator class ready.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in