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 :: 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.



European ASP.NET MVC 3 Hosting :: Working with ASP.Net MVC 3 Razor View Engine and Syntax Highlighting

clock May 3, 2011 09:19 by author Scott

Today, we found a good answer on syntax highlighting for Razor. In the Visual Studio Gallery located at http://visualstudiogallery.msdn.microsoft.com/en-us/8dc77b9c-7c83-4392-9c46-fd15f3927a2e, a new Visual Studio extension has been recently added for a “Razor Syntax Highlighter”.

To leverage this new extension, we had to remove the editor mapping for .cshtml files in the Visual Studio Text Editor/File Extensions window and install the highlighter extension. As you see in the figure below, it worked great. This new extension uses the Razor Parser libraries to appropriately highlight the Razor code.



Unfortunately, this feature is offered as a Visual Studio Extension and hence is only available for paid-for Visual Studio 2010 editions.

Looking at the Razor Syntax, one can summarize it as a means to short-hand the <%= %> used in ASPX pages to designate code sections. For Razor, only a simple @ sign is used in-place of that bulky aforementioned code markup . Additionally, the Razor parser introduces helpful intelligence that makes the syntax even more user-friendly. For instance the following is a code block you would see in an ASPX page:

<%=if(true){%>
       <input value=”istrue”/>
<%}%>  

The corresponding Razor block for this snippet would be:


@if(true){
       <input value=”istrue”/>
}

The Razor syntax has simply “inferred” that the code will have a closing curly bracket without us having to apply any special markup tags to it. This further reduces the markup needed to accomplish the same task.

An important difference between Razor and ASPX View Engines is the absence of master pages for the earlier. Razor simply provides a _ViewStart.cshtml to bootstrap our application layout.

@{
    Layout = “~/Views/Shared/_Layout.cshtml”;
}

Latest Razor Beta does however support Partial rendering (RenderPartial) to explicitly render a Partial View as well as calling @RenderBody() which loads the actual view content to be served.

Now,
HostForLife.eu has supported ASP.NET MVC 3 hosting. For more information about this new product, please visit here.



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