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 4 Hosting - Amsterdam :: Securely Verify and Validate Image Uploads in ASP.NET and ASP.NET MVC

clock September 17, 2013 10:01 by author Ronny

One of the more interesting things had to do as part of building XAPFest was handle bulk image uploads for screenshots for applications and user / app icons. Most of the challenges here are UI-centric ones (which resolved using jQuery File-Upload) but the one security challenge that remains outstanding is ensuring that the content uploaded to your servers is safe for your users to consume.

Fortunately this problem isn't too hard to solve and doesn't require much code in C#.

Flawed Approaches to Verifying Image Uploads

Here's what usually see when developers try to allow only web-friendly image uploads:

  1. File extension validation (i.e. only allow images with .png, .jp[e]g, and .gif to be uploaded) and
  2. MIME type validation.


So what's wrong with these techniques? The issue is that both the file extension and MIME type can be spoofed, so there's no guarantee that a determined hacker might not take a js. file, slap an extra .png extension somewhere in the mix and spoof the MIME type.

Stronger Approach to Verifying Image Uploads: GDI+ Format Checking

Every file format has to follow a particular codec / byte order convention in order to be read and executed by software. This is as true for proprietary formats like .pptx as it is for .png and .gif.

You can use these codecs to your advantage and quickly tell if a file is really what it says it is - you quickly check the contents of the file against the supported formats codecs to see if the content fits into any of those specifications.

Luckily GDI+ (System.Drawing.Imaging), the graphics engine which powers Windows, has some super-simple functions we can use to perform this validation. Here's a bit of source you can use to validate a file against PNG, JPEG, and GIF formats:

using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
namespace XAPFest.Providers.Security
{
    ///
    /// Utility class used to validate the contents of uploaded files  
    ///
    public static class FileUploadValidator  
    {    
     public static bool FileIsWebFriendlyImage(Stream stream)   
     {
            try
            {
                //Read an image from the stream...
                var i = Image.FromStream(stream);
                 //Move the pointer back to the beginning of the stream
                stream.Seek(0, SeekOrigin.Begin);
                 if (ImageFormat.Jpeg.Equals(i.RawFormat))
                    return true;
                return ImageFormat.Png.Equals(i.RawFormat)|| ImageFormat.Gif.Equals(i.RawFormat);
            }
            catch
            {
                return false;
            }
        }
     }
}

All this code does is read the Stream object returned for each posted file into an Image object, and then verifies that the Image supports one of three supported codecs. This source code has not been tested by security experts, so use it at your own risk. If you have any questions about how this code works or want to learn more, please drop me a line in the comments below or on Twitter.

How Do Make Sure Files Are below [X] Filesize

Since had this source code lying around anyway, We thought we would share it: 

Super-simple, like we said, but it gets the job done. Express the maximum allowable size as a long and compare it against the length of the stream

public static bool FileIsWebFriendlyImage(Stream stream, long size)
        {
            return stream.Length <= size && FileIsWebFriendlyImage(stream);
        }
    }
The other important catch to note here is that move the Stream's pointer back to the front of the stream, so it can be read again by the caller which passed the reference to this function.



European ASP.NET MVC 4 Hosting - Amsterdam :: Asynchronous Controllers in ASP.NET MVC 4

clock September 6, 2013 12:01 by author Scott

One of the most important features of ASP.NET MVC 4 is the introduction of the new ASP.NET Web API, which simplifies REST programming with a strongly typed HTTP object model. In addition, ASP.NET MVC 4 takes advantage of the new asynchronous programming model introduced with .NET Framework 4.5 to allow developers to write asynchronous action methods. It is important to understand the advantages and disadvantages of the new asynchronous methods to use them whenever they will provide a benefit.

(ASP.NET MVC 4 also includes many enhancements focused on mobile development, such as jQuery Mobile support and selecting views based on which mobile browser makes requests. If you work with previous ASP.NET MVC versions and you target multiple mobile devices, the new display modes are worth moving to ASP.NET MVC 4. In addition, the bundling and minification framework makes it simpler to reduce HTTP requests for each page without having to use third-party tools.)

Asynchronous controllers ASP.NET MVC 4

Asynchronous execution is the future of Windows development : it has been largely demonstrated during the //Build conference two weeks ago.

In previous versions of ASP.NET MVC it was possible to create asynchronous controllers by inheriting the AsyncController class and using some conventions :

- MyActionAsync : method that returns void and launches an asynchronous process
- MyActionCompleted : method that returns an ActionResult (the result of the MVC action “MyAction”, in this case)

To allow the MVC engine to manage asynchronous operations and pass the result to the view engine, developers had to use the propery AsyncManager of the AsyncController. The “completed” method parameters was passed by the MVC engine through this object.

For example, the controller that is defined bellow allows to get a Json-serialized list of movies – asynchronously – from an OData service :

public class MoviesController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    } 

    public void GetJsonMoviesAsync(int? page)
    {
        const int pageSize = 20;
        int skip = pageSize * ((page ?? 1) - 1);
        string url = string.Format("http://odata.netflix.com/[…]&$skip={0}&$top={1}",
            skip, pageSize); 

        //the asynchronous operation is declared
        AsyncManager.OutstandingOperations.Increment(); 

        var webClient = new WebClient();
        webClient.DownloadStringCompleted += OnWebClientDownloadStringCompleted;
        webClient.DownloadStringAsync(new Uri(url));//the asynchronous process is launched
    } 

    private void OnWebClientDownloadStringCompleted(object sender,
        DownloadStringCompletedEventArgs e)
    {
        //the asynchronous process ends
        //"movies" result is added to the parameters of the AsyncManager
        //NB : it's the name of the parameter that is take by the
        //GetJsonMoviesCompleted method
        List<Movie> movies = null;
        if (AsyncManager.Parameters.ContainsKey("movies"))
        {
            movies = (List<Movie>)AsyncManager.Parameters["movies"];
            movies.Clear();
        }
        else
        {
            movies = new List<Movie>();
            AsyncManager.Parameters["movies"] = movies;
        } 

        movies.AddRange(Movie.FromXml(e.Result)); 

        //the ends of the asynchronous operation (launches the call of "Action"Completed)
        AsyncManager.OutstandingOperations.Decrement();
    } 

    public ActionResult GetJsonMoviesCompleted(List<Movie> movies)
    {
        //on retourne le résultat Json
        return Json(movies, JsonRequestBehavior.AllowGet);
    }
}

It’s not really complicated to create an asynchronous controller but ASP.NET MVC 4 and C# 5 with the new async and await keywords will make it easier !

public class MoviesController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    } 

    public async Task<ActionResult> GetJsonMovies(int? page)
    {
        const int pageSize = 20;
        int skip = pageSize * ((page ?? 1) - 1);
        string.Format("http://odata.netflix.com/[…]&$skip={0}&$top={1}",
                    skip, pageSize); 

        var webClient = new WebClient();
        string xmlResult = await webClient.DownloadStringTaskAsync(url);
        return Json(Movie.FromXml(xmlResult), JsonRequestBehavior.AllowGet);
    }
}

As you can see in the previous code snippet, in ASP.NET MVC 4 you always should inherits from AsyncController but there is no more naming conventions, no more Async/Completed methods, no more AsyncManager and the action returns a Task instead of an ActionResult !

 



Press Release :: European HostForLIFE.eu Proudly Launches ASP.NET MVC 5 Hosting

clock August 28, 2013 11:05 by author Ronny

European Windows and ASP.NET hosting specialist, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the Microsoft ASP.NET Model View Controller (MVC) technology. The MVC web application framework facilitates the development of dynamic, data-driven websites.

The latest update to Microsoft’s popular MVC (Model-View-Controller) technology,  ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

HostForLIFE.eu is Microsoft’s number one Recommended Windows and ASP.NET Spotlight Hosting Partner in Europe for its support of Microsoft technologies that include WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5, and Visual Studio Lightswitch.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression.

In addition to shared web hosting, shared cloud hosting, and cloud server hosting, HostForLIFE.eu offers reseller hosting packages and specialized hosting for Microsoft SharePoint 2010 and 2013. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

For more information about this new product, please visit http://www.HostForLIFE.eu

About HostForLIFE.eu:

HostForLIFE.eu is Microsoft No #1 Recommended Windows and ASP.NET Hosting in European Continent. HostForLIFE.eu service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and many top European countries.

HostForLIFE.eu number one goal is constant uptime. HostForLIFE.eu data center uses cutting edge technology, processes, and equipment. HostForLIFE.eu has one of the best up time reputations in the industry.

HostForLIFE.eu second goal is providing excellent customer service. HostForLIFE.eu technical management structure is headed by professionals who have been in the industry since it's inception. HostForLIFE.eu has customers from around the globe, spread across every continent. HostForLIFE.eu serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET MVC 4 Hosting - Amsterdam :: Creating MVC 4 Application with Umbraco

clock August 16, 2013 06:38 by author Scott

Hello, how do you do? In this article, I will gonna show you how to integrate ASP.NET MVC 4 using Umbraco. Note that Umbraco does not provide a “pure” MVC application as the Umbraco UI comes with a fair amount of webforms baggage. That said, it plays nicely with an MVC 4 project in Visual Studio and provides a flexible view rendering engine that lets you build genuinely testable page templates.

Setting up the project

Umbraco is shipped as an ASP.NET website which you can use directly, though this is not ideal. It is a better idea to create a full MVC 4 project, manage the dependencies using the Umbraco NuGet package and drop the Umbraco files directly into the site. Use the following steps to set up Umbraco as an MVC 4 project in Visual Studio:

Firstly, start an empty MVC 4 project in Visual Studio – make sure it is an empty project as you will not need any of the baggage that comes with other project templates.

Add the NuGet Umbraco Cms Core Binaries package which will manage the various dependencies and references that Umbraco 6 requires for you.

Copy all the files from the Umbraco installation ZIP archive directly into your project in Visual Studio except the App_Code and Bin folders – you won’t need the binaries as they are managed by NuGet and the App_Code folder is not used in a web application project.

The default mode for Umbraco is to use web forms rendering. You will need to switch this to use MVC by changing the defaultRenderingEngine setting in the Umbraco configuration file UmbracoSettings.config as shown below:

<templates>
  <useAspNetMasterPages>true</useAspNetMasterPages>
  <defaultRenderingEngine>Mvc</defaultRenderingEngine>
</templates>

Now you’re good to go – run the Umbraco site to set up the database and once the admin console comes up you can create a first view.

Note that you may optionally wish to remove the App_Start directory and Global.asax.cs files from your Visual Studio project – they are not used in a default Umbraco application as global.asax inherits directly from the Umbraco.Web.UmbracoApplication class and does not execute this code.

Creating a view

You can create a basic view in the Umbraco UI. In the “Settings” section create a new Document Type – call it “Home” and ensure that “Create matching template” is checked. A new file will be created in your Views folder with the following mark-up:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{

    Layout = null;
}

If you create and publish a first page based on this content type it will become your site’s home page. This is all you do to start creating pages based on MVC as Umbraco uses a default routing process that delivers the page properties to the view. You can actually build basic content pages without having to worry about the plumbing around controllers and models – this only starts to become important if you want to put more logic in behind the scenes.

Creating a custom controller

The default rendering engine for Umbraco routes requests through RenderMvcController with an IPublishedContent object as the model view. This provides a pretty simple means of  basic pages rigged up with managed content but you can extend this behavior by creating custom controllers. Umbraco refers to this technique of creating custom controllers as hijacking, though really it is just a matter of creating a controller where MVC would normally look.

To create a controller for our Home view we just create a controller called HomeController. To hook it up to Umbraco’s content API you will need to inherit from RenderMvcController and override the Index method as shown below:

public class HomeController : Umbraco.Web.Mvc.RenderMvcController
{
    public override ActionResult Index(RenderModel model)
    {
        //Do some stuff here, then return the base method
        return base.Index(model);
    }
}

Creating controllers to handle forms and actions is a little more involved as you have to create what Umbraco calls a surface controller. This is a controller like any other but one that is derived from the Umbraco SurfaceController class. These controllers can be implemented as a normal part of your MVC project (“locally declared” in Umbraco-speak) or implemented as a plug-in for shipping as part of a package.

If you want to include your own custom MVC routes then you will have to override the OnApplicationStarted method. This can be done by creating your own custom global.asax file that inherits from Umbraco.Web.UmbracoApplication.

Creating a custom model

Once you have wired up a controller it’s pretty straightforward to create in your own model and pass it into the page. You will need to change the view so that it inherits the generic version of UmbracoViewPage with your custom model specified as the generic parameter. The example below shows the view adjusted for a new model called HomeModel.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<UmbracoMvc4.Models.HomeModel>
@{

    Layout = null;
}

The controller will still accept a RenderModel object but you can pass your custom model by using the CurrentTemplate method as shown below:

public override ActionResult Index(RenderModel model)
{
    HomeModel customModel = new HomeModel();
    return CurrentTemplate(customModel);
}

If you want to take advantage of the Umbraco view helpers then you can extend the RenderModel object by creating a constructor that initialises the base class as shown below. This will ensure that your derived model still exposes the page data and current culture properly.

public class HomeModel : RenderModel
{
    public HomeModel(RenderModel model)
        : base(model.Content, model.CurrentCulture)
    { }
}

Beyond the basics

Although it is not a “pure” MVC implementation you can still get Umbraco 6 to sit quite nicely within an MVC 4 web application just so long as you set it up carefully. Beyond the basics of models, views and controllers there is support for features such as partial views and child actions as well as scope for you to use dependency injection and your IoC container of choice. So long as you’re prepared to ignore the messy webforms back-end that lurks in the background Umbraco 6 can really feel like working with an MVC 4 application.



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Create Async Controllers with MVC 4

clock August 9, 2013 08:59 by author Scott

In this post I will show how to create async controllers in MVC 4.

The way to build asynchronous controllers has been completely changed compared to how it was done in MVC3 with the AsyncController superclass. This class and the inherent complexity in using it are gone in MVC4.

Start Visual Studio 2012 and create an MVC4 Web Application and choose the Internet template. Create a folder called “Services” in the solution. Insert two classes in this folder: DatabaseService and CalculationService. They represent long running calls to external services and have the following content:

DatabaseService.cs:

public class DatabaseService
    {
        public string GetData()
        {
            StringBuilder dataBuilder = new StringBuilder();
            dataBuilder.Append("Starting GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            Thread.Sleep(2000);
            dataBuilder.Append("Results from the database. ").Append(Environment.NewLine);
            dataBuilder.Append("Finishing GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return dataBuilder.ToString();
        }
    }

CalculationService.cs:

public class CalculationService
    {
        public string GetResult()
        {
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.Append("Starting GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            Thread.Sleep(2000);
            resultBuilder.Append("This is the result of a long running calculation. ");
            resultBuilder.Append("Finishing GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return resultBuilder.ToString();
        }
    }

There should be nothing complicated in either class implementation.

Create another folder in the solution called ViewModels. Add a class called HomePageViewModel in that folder:

public class HomePageViewModel
    {
        public List<String> Messages { get; set; } 

        public void AddMessage(string message)
        {
            if (Messages == null)
            {
                Messages = new List<string>();
            }
            Messages.Add(message);
        }
    }

Navigate to the Index action of the Home controller and modify it as follows:

public ActionResult Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 
            viewModel.AddMessage(calcService.GetResult());
            viewModel.AddMessage(dataService.GetData()); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Nothing complicated here either: we’re just adding messages to the view model, show the thread ids and measure the time it takes to complete the action.

Modify Index.cshtml of the Home view as follows:

@model Mvc4.ViewModels.HomePageViewModel
@{
    ViewBag.Title = "Home Page";


<ul>
    @foreach (String message in Model.Messages)
    {
        <li>@message</li>
    }
</ul>

So when you run the web page you should see an output similar to the following:

It’s easy to see the following:

  • The Index() action blocks the thread when it calls CalculationService and DatabaseService
  • The total processing time took about 4 seconds in total
  • All involved methods executed on the same thread

Now our goal is to make this process more efficient: as it stands now the main thread is only sitting idle for most of the processing time. This can be a serious problem if we’re intending to build a scalable and responsive application.

We need to make a couple of changes to our code:

  • The Index() action needs to return a Task of type ActionResult and turned to an async method: we do not directly return an ActionResult but a Task that represents an ActionResult
  • Remember that if an action is of type async then it needs to have its pair ‘await’ somewhere in the method body
  • We have two long running method calls within the Index() action, so we’ll instruct MVC4 to await them
  • Since we’ll await those two method calls we need to insert async versions of DatabaseService.GetData() and CalculationService.GetResult() as well: they in turn must also return Tasks of type string instead of plain string

Using our experience from the Console app in the previous post we’ll include an async version of GetResult() in CalculationService.cs:

public async Task<String> GetResultAsync()
        {
            StringBuilder resultBuilder = new StringBuilder();
            resultBuilder.Append("Starting GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            await Task.Delay(2000);
            resultBuilder.Append("This is the result of a long running calculation. ");
            resultBuilder.Append("Finishing GetResult on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return resultBuilder.ToString();
        }

We’ll also insert a GetDataAsync() in DatabaseService.cs:

public async Task<String> GetDataAsync()
        {
            StringBuilder dataBuilder = new StringBuilder();
            dataBuilder.Append("Starting GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(". ");
            await Task.Delay(2000);
            dataBuilder.Append("Results from the database. ").Append(Environment.NewLine);
            dataBuilder.Append("Finishing GetData on thread id ").Append(Thread.CurrentThread.ManagedThreadId)
                .Append(".");
            return dataBuilder.ToString();
        }

Update the Index action of the Home controller to call the async method versions of the services:

public async Task Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 

            string calculationResult = await calcService.GetResultAsync();
            string databaseResult = await dataService.GetDataAsync(); 

            viewModel.AddMessage(calculationResult);
            viewModel.AddMessage(databaseResult); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Run the web app now and you may see an output similar to the following:

Note the following:

  • The Index action started on thread id 10
  • The same thread enters GetResultAsync
  • The main thread exits GetResultAsync at the await keyword and thread 9 takes over
  • Thread 9 enters GetDataAsync and exits at the await keyword and thread 5 takes over
  • Thread 5 finished Index()
  • The total processing time is still about 4 seconds, but remember from the previous post: if you want to couple asynchronous methods with concurrency you need to include the TPL as well. This will be resolved later in this post.

The output on your screen may be different when you run the sample. It is not guaranteed that 3 different threads will be involved throughout the lifetime of the Index() action. It depends on the availability of threads, may only be 2 in total.

If you are working with WCF services and add a service reference to your project then you’ll have the option to generate the Async() versions of the service calls automatically. Make sure to select the ‘Allow generation of asynchronous operations’ checkbox and the ‘Generate task-based operations’ radiobutton in the Service Reference Settings window.

.NET4.5 is now interspersed with built-in async versions of long running and/or remote methods. Typical examples include: HttpClient.SendAsync that returns a Task of type HttpResponseMessage, or HttpContent.ReadAsStringAsync that returns a Task of type String.

We can now introduce TPL to make the service calls run in parallel. As it stands now the Index action first waits for GetResultAsync to finish before it goes on with GetDataAsync. Ideally Index should wait for both actions to complete in parallel and not one after the other. We will basically hold a reference to the Task values returned by the services and await them both together.

Update the Index action as follows:

public async Task<ActionResult> Index()
        {
            DateTime startDate = DateTime.UtcNow; 

            HomePageViewModel viewModel = new HomePageViewModel();
            viewModel.AddMessage(string.Concat("Starting Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            CalculationService calcService = new CalculationService();
            DatabaseService dataService = new DatabaseService(); 

            Task<String> calculationResultTask = calcService.GetResultAsync();
            Task<String> databaseResultTask = dataService.GetDataAsync(); 

            await Task.WhenAll(calculationResultTask, databaseResultTask); 

            viewModel.AddMessage(calculationResultTask.Result);
            viewModel.AddMessage(databaseResultTask.Result); 

            DateTime endDate = DateTime.UtcNow;
            TimeSpan diff = endDate - startDate; 

            viewModel.AddMessage(string.Concat("Finishing Action on thread id ", Thread.CurrentThread.ManagedThreadId));
            viewModel.AddMessage(string.Concat("Action processing time: ", diff.TotalSeconds));
            return View(viewModel);
        }

Note the following:

  • We do not await the two service calls one by one
  • Both of them will be awaited using Task.WhenAll
  • Task.WhenAll accepts an array of Task objects that should run in parallel
  • Task.WhenAll will block until all tasks in the array have finished
  • The await keyword will make sure that Index will wait upon all tasks to complete in the array
  • To retrieve the returned value from the service calls just use the Result property of the Task object: this will be populated if the Task has a return value i.e. it is a Task of some type

When you run the updated Index page you may see something like this:

Again, your results will almost certainly differ. Which thread is allocated to which task is up to the thread scheduler. Refresh the page a couple of times to see some different results.



European ASP.NET MVC 4 Hosting - Amsterdam :: Tips to Enable and Disable Client Side Validation in MVC

clock August 5, 2013 10:38 by author Scott

In this article, I would like to demonstrate various ways for enabling or disabling the client side validation in ASP.NET MVC  3/4.

Enable Client-Side Validation in MVC

For enabling client side validation, we required to include the jQuery min, validate & unobtrusive scripts in our view or layout page in the following order.

<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

The order of included files as shown above, is fixed since below javascript library depends on top javascript library.

Enabling and Disabling Client-Side Validation at Application Level

We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level.

<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

For client-side validation, the values of above both the keys must be true. When we create new project using Visual Studio in MVC3 or MVC4, by default the values of both the keys are set to true.

We can also enable the client-side validation programmatically. For this we need to do code with in the Application_Start() event of the Global.asax, as shown below.

protected void Application_Start()
{
//Enable or Disable Client Side Validation at Application Level
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

Enabling and Disabling Client-Side Validation for Specific View

We can also enable or disable client-side validation for a specific view. For this we required to enable or disable client side validation inside a Razor code block as shown below. This option will overrides the application level settings for that specific view.

@model MvcApp.Models.Appointment
@{
ViewBag.Title = "Make A Booking";
HtmlHelper.ClientValidationEnabled = false;
}
...

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Create Custom HTML Helpers in ASP.NET MVC 4

clock July 29, 2013 08:39 by author Scott

HTML Helpers are nothing but the way of rendering HTML on the view page in ASP.NET MVC. Typically what we have in traditional ASP.NET web forms is Web Controls to achieve same functionality but with the evolution of MVC pattern , you don't have any web controls to add on to the view pages.

In simple words - it is just a method which returns you a string , and string is HTML.

Example of HTML Helpers:

ASP.NET MVC framework ships with various inbuilt HTML helpers such as ActionLink , Label.
Lets take a look at how a HTML helper is added to the view page. I am considering Razor view engine for this example.

@Html.ActionLink("Display Name of Link", "MethodName", "ControllerName");

Example above shows how OOB Action Link is used to render the HTML hyperlink on the view page.

Another example is shown as below where it is used to render the Html label tag to render Store Name property of model class. 

@Html.LabelFor(model => model.StoreName)

Why to use Html Helpers?

Question might have poped up in your mind by now that Html helpers are just going to render the string of html then why do I need to use them ? If I know the Html syntax then why not add the Html directly on to the view page? 

Answer is simple, it depends how clean and consistent you want to make your application. of course you can do the direct addition of html tags on your view pages but if you observe second example - you can see that it is simply rendering the label tag on view page for a property in model at run time. so it just for making developer's life more easy and to have the cleaner html for your view page.

Need of Custom Html Helpers?

Well, there is always need to do some custom stuff on top of what framework offers, and reason for doing this is either business requirement or to get things done in smarter way.

Writing a custom Html helper is nothing but writing an extension method. you are actually writing an extension method for HtmlHelper class.

Being a SharePoint developer I always find this task similar to creation of a web control where you override the render method of base class and do the custom Html rendering. 

Creating Custom Html Helper

All right , for demo purpose I will keep the example simple - I will simply write an Html helper which will render the header of any content on view page.

This is done simply by using the <header> tag of Html 5.

Step 1: Define your custom static class for creation of your custom Html helpers

public static class DemoCustomHtmlHelpers
{

}

Step 2: Add static method to the class and make sure that return type is MvcHtmlString. Write an input paramter of method as HtmlHelper and also a string for which the header tag needs to be generated.

You might need to add System.Web.Mvc namespace to your class.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{         


}

Step 3 : Add the rendering logic in the method , you can take help from TagBuilder class to generate Html tags to be rendered.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{
   var tagBuilder = new TagBuilder("header");
   tagBuilder.InnerHtml = content;
   return new MvcHtmlString(tagBuilder.ToString());
}

Step 4: Build the project and open any of the view page. Now you can use your custom Html helper to render the header. Make sure that your view page has correct using namespace for using your custom Html helper extension.

@Html.Header("Create")

When you observe the view page's Html , you will be finding the generated Html tag by our Custom Html helper extension

<header>Create</header>

Now, you can also try it and have fun with your own scenario.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Using MVC 4 to Run Sitecore

clock July 17, 2013 11:19 by author Scott

ASP.NET MVC is everywhere, and if you judge from the the job adverts ASP.NET Web Forms is rapidly being consigned to the “legacy” category. So where does that leave developers like me, currently using Sitecore?
Although it seems to me that Sitecore is Web Forms to it’s back teeth, there are nevertheless some signs that it too is going MVC.

From Sitecore version 6.6 there is support for MVC straight out of the tin (or the installer, at least). This is great but how do you get from that install to not just an MVC project, but MVC 4 (.NET 4.5) using Visual Studio 2012?
The steps are available around and about, but this post seeks to update the process to the latest version of Sitecore and pull it all together.

If you are really new to Sitecore MVC, probably the best place to start is here.

1. Create a Visual Studio Project from the install

a.) Using the latest version of Sitecore (Sitecore 6.6.0 rev. 130214), create a new instance
b.) Create a new Empty Website with Visual Studio 2012 using .NET 4 (but NOT MVC)
c.) Copy the Sitecore instance into your Empty Project Directory, and include the files (and Assembly References) into it. I found that the best way to get the Assemblies in was to copy them to a third directory (not the bin directory), then browse to that and Visual Studio will add them, nice and cleanly.
d.) Take the global.asax from the Sitecore Instance, pull out the inline code and paste it into a new global.asax.cs
e.) Publish the Site

2. Make the project MVC3

a.) Unload the project, then right-mouse click to edit the project file. In the project file you will find an element

<ProjectTypeGuids>

add this GUID to it at the front of the list, separated by a semi-colon:
{E53F8FEA-EAE0-44A6-8774-FFD645390401};

b.) Reload the project you now have an MVC3 Sitecore project.

c.) You should now confirm that MVC3 is working:

(this taken from John West’s blog)

Create a the subdirectory /Views containing a nested subdirectory named Sitecore.
Create the /Views/Sitecore/index.cshtml file containing some Razor code (note that the @inherits directive is not necessary if the /Views subdirectory contains the proper web.config file, such as that installed when you create an MVC project in Visual Studio):

@inherits System.Web.Mvc.WebViewPage
@{
  Layout = null;
}
<html>
  <body>
  <h4>Index.cshtml</h4>
  <div>Model:
@{
  if (Model == null)
  {
<text>null</text>
  }
  else
  {
@Model.GetType();
  }
}
    </div>
  </body>
</html>

In the Sitecore Content Editor user interface, navigate to the /sitecore/layout/Layouts/Sample Layout item that defines the default layout.
Click the Content Tab.

In the Path field, enter /Views/Sitecore/index.cshtml, and save.

Either publish the layout definition item and view the home page of the published site (http://playground – not http://playground/default.aspx), or use the Page Editor. You should see content such as the following:

Index.cshtml

Model: Sitecore.Mvc.Presentation.RenderingModel

3. Make the Project MVC 4

a.) In the project Website Properties change the Target Framework to .NET 4.5

b.) Update the references from MVC3 to MVC4

all references in .config files need to reflect these versions:
System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″
System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
System.Web.Helpers, Version=2.0.0.0, Culture=neutral, publicKeyToken=”31bf3856ad364e35″
System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35

these appSettings need to be added to the web.config:

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
  <add key="PreserveLoginUrl" value="true" />
</appSettings>

further details here:

c.) In Solution Explorer, right-click on the References and select Manage NuGet Packages. In the left pane, select Online\NuGet official package source, then update the following:

ASP.NET MVC 4
(Optional) jQuery, jQuery Validation and jQuery UI
(Optional) Entity Framework
(Optonal) Modernizr

d.) Update ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.

e.) If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="4.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages"
             publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

f.) Finally, there is an incompatability with the Sitecore login page under .NET 4.5, to do with the use of an iframe. The file sitecore/login/default.aspx contains an iframe to the SDN that .NET 4.5 doesn’t like. Replace it with a div:

<iframe id="SDN">
  <div id="StartPage" runat="server" allowtransparency="true"
 frameborder="0" scrolling="auto" marginheight="0" marginwidth="0"
 style="display: none"></div>
</iframe> 

<div id="SDN">
  <div id="StartPage" runat="server" allowtransparency="true"
 frameborder="0" scrolling="auto" marginheight="0" marginwidth="0"
 style="display: none"></div>
</div>

and you’re off to the races. More detail here.

I should point out, of course that .NET 4.5 is not supported as yet by Sitecore, but with this you can play with 4.5… until Sitecore 7 arrives.

Good luck.

 



European ASP.NET MVC 4 Hosting - Amsterdam :: Enhanced Default Template MVC 4

clock July 5, 2013 07:10 by author Scott

MVC 4 introduces many new features. In today post, I will talk about MVC 4 and enhanced default templates.

When you create a new project, the default website looks quite different from previous versions.  Besides the improved aesthetics, the default website has improved functionality thanks to a technique called adaptive rendering.

Adaptive rendering is where the page is rendered specific to the browser without any customization.  This is an absolute must for most developers today; write once, run everywhere.  The adaptive rendering is made possible thanks to a new CSS type -> media queries

@media all and (min-width: 640px) { #media-queries-1 { background-color: #0f0; } }
@media screen and (max-width: 2000px) { #media-queries-2 { background-color: #0f0; } }

After you creating a new website, you’ll be able to see the improvements in the default layout.

To see the adaptive rendering in action, open the page using a mobile device.

Here’s how the page looks on an iPhone.

And here’s how the page look on an iPad.

The page renders differently depending on the size of the screen.  Making the page do that without media queries is tricky.  Using media queries makes it simple.

One final thing to note is the default template takes advantage of jQuery UI also.  The Login and Register links show you how to use this JavaScript library to  provide a richer UI.  You can read all about the other features that are available to you with jQuery UI here.

Testing with Emulators

The best way I found to test what the site will look like is with FireFox and User Agent Switcher add-on,
which changes the user agent that’s sent to the browser.  That can be downloaded
here.



European ASP.NET MVC 4 Hosting - Amsterdam :: How to Fix CSS Problem in ASP.NET MVC 4

clock July 1, 2013 12:10 by author Scott

Some of you will face this problem when using Bundling and Minification in ASP.NET MVC 4. This post cover about how to fix relative CSS Path in ASP.NET MVC 4.

Recently, I hit a known problem with deploying to IIS virtual directories. It’s not a problem for ASP.NET which understands virtual directories and so if you ask for “~” or “/” will return “yoursite/virtualfolder”. However, JavaScript is run under IIS, which doesn’t understand this idea so well. Do “/” in JS and you’ll get back “yoursite” NOT “yoursite/virtualfolder”.

So what’s the fix? Well, for JavaScript there are a couple of answers. So I check my javascript. Based on this answer, I came up with this:

1. Add a hidden field to a masterpage:

  @Html.Hidden("HiddenCurrentUrl",  Url.Content("~"))

2. As one of the first things you do, ensure this JS runs. All it does it take the value in the field and store it:

var baseUrl = "";
baseUrl = $("#HiddenCurrentUrl").val();


3. Use baseUrl wherever you need to call things in JavaScript:

Silverlight.createObject(
            baseUrl + "ClientBin/SilverlightBridge.xap",  // source
            ...
        );

Hmm… But you know, that is not the problem. The problem is with the CSS file

    .link-button.cancel {
        background-image: url('../Images/appbar.cancel.darkgrey.png');
    }

A similar problem occures where these URLs start with a slash(/) because IIS interprets that incorrectly. You can’t invoke ASP.NET, which does know the right root into a CSS file

After some messing around, I came to this compromise, which works well. It also exposes some of the hidden power of using Bundling:

  1. For any images you reference in CSS, move them into a relative folder, such as /images near the CSS. I know, this may be an unacceptable compromise for you. But actually, it makes a lot of sense. The image is probably only used by the CSS so it makes sense to have it nearby, not in some global /images folder.  
  2. In order to make this work, you need to get your CSS (which you’ve bundled up) into the same place relative to the images you’re reference, or at least, you need to cheat the browser into thinking this happening.
  3. So, for instance:

      bundles.Add(new StyleBundle("~/Content/DataTableStyle").Include(


    comes out the other end as:

Don’t forget that all your “static” content, such as images won’t be affected by Bundling and can be referenced using the folder structure you expect, i.e. the one you’ve set up in Visual Studio.

So… when you create the Style Bundle you give it a name which reflects where you have it in your Visual Studio folder structure, then it will pop out the other end in the same place, relatively, to the image files which it’s references! And because the Bundling is happening via ASP.NET, the URL of the CSS file, and wherever it is referenced, works fine in virtual directories!



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