Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET MVC 3 Hosting - ASPHostPortal :: Implementing Dynamic DropDownList in ASP.NET MVC 3 Framework

clock February 24, 2011 06:57 by author Jervis

Creating the ViewModel:

The first step is to create a ViewModel which will represents the elements on the View. Our ViewModel revolves around the relationship between the category and products. The user will select a category from a dropdownlist which will populate all the corresponding products in another dropdownlist. The implementation bellows shows the ArticleEditViewModel:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.ViewModels
{
    public class ArticleEditViewModel
    {
        private List<SelectListItem> _categories = new List<SelectListItem>();
        private List<SelectListItem> _products = new List<SelectListItem>();
        [Required(ErrorMessage = "Please select a category")]
        public string SelectedCategory { get; set; }
        [Required(ErrorMessage = "Please select a product")]
        public string SelectedProduct { get; set; }
        public List<SelectListItem> Products
        {
            get { return _products;  }
        }
        public List<SelectListItem> Categories
        {
            get
            {
                _categories.Add(new SelectListItem(){ Text = "Ruby", Value = "1"});
                _categories.Add(new SelectListItem(){ Text = "JavaScript",Value="2"});
                return _categories;
            }
        }
    }
}

As, you can see that to keep the demo simple we have hard-coded the categories. In the next section we will demonstrate how to populate the categories dropdownlist using the ArticleEditViewModel.

Populating Categories DropDownList:

The Index action of the HomeController returns the new ArticleEditViewModel to the view. The view uses the Categories property of the ArticleEditViewModel to populate the dropdownlist. The Index action is shown below:

public ActionResult Index()
       {             

           return View(new ArticleEditViewModel());
       }

The DropDownList is populated using the code below:

<text>Select a category: </text> @Html.DropDownListFor(x => x.SelectedCategory, new SelectList(Model.Categories,"Value","Text"),"Please Select a category") 
@Html.ValidationMessageFor(x => x.SelectedCategory) 

The DropDownList is bind to the SelectedCategory property of the ViewModel. The SelectedCategory property is also decorated with the [Required] attribute which makes sure that the SelectedCategory is not left blank or on the default item. The screenshot below shows the validation being fired when the Categories DropDownlist is left at the default option and the view is submitted.



The validation is fired because the default option "Select a category" does not have any value associated with it. ASP.NET MVC framework tries to bind the empty string with the SelectedCategory property but fails since the SelectedCategory is marked with [Required] attribute.  
 
Fetching the Products and Populating the Dependent DropDownList:

Our next task is to get the selected category and then fetch the associated products using the categoryId. This will be performed by an ajax call using our beloved jQuery library. The implementation below shows the details.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $("#SelectedCategory").change(function () {
            $.get('/Home/GetProductsForCategory/' + $(this).val(), function (response) {
                var products = $.evalJSON(response);
                var ddlSelectedProduct = $("#SelectedProduct");
                // clear all previous options 
                $("#SelectedProduct > option").remove(); 
                // populate the products 
                for (i = 0; i < products.length; i++) {
                    ddlSelectedProduct.append($("<option />").val(products[i].Value).text(products[i].Text));
                }
            });
        });
    });
</script>

The code above calls the GetProductsForCategory action with the categoryId as the input parameter. The GetProductsForCategory returns the JSON response which represents the products. Before populating the DropDownList with the products we clear all the items in the DropDownList. The GetProductsForCategory action is implemented below:

 public string GetProductsForCategory(string id)
        {
           // get the products from the repository 
            var products = new List<SelectListItem>();
            if (id == "1")
            {
                products.Add(new SelectListItem() {Text = "Introduction to Ruby", Value = "1"});
                products.Add(new SelectListItem() {Text = "Ruby Unit Testing", Value = "2"});
            }
            else if(id == "2")
            {
                products.Add(new SelectListItem(){ Text = "JavaScript testing",Value = "1"});
                products.Add(new SelectListItem() { Text = "JavaScript Ninja", Value = "2"});
            }
            return new JavaScriptSerializer().Serialize(products); 
        }

The above action simply returns the hard-coded values but in actual application you will retrieve the products from a data storage system.

The screenshot below shows the final result:



Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: How to Create ASP.NET MVC 2 Controller Factory with Ninject

clock February 21, 2011 05:05 by author Jervis

Please follow this steps:

1. Please download this first.

2. Then click on the Release version of ninject.



3. Extract the zip to a folder of your choice

4. Please also download MVC if you haven’t already download it,
http://www.microsoft.com/downloads/details.aspx?FamilyID=7aba081a-19b9-44c4-a247-3882c8f749e3&displaylang=en#filelist

5. Now let's create a new MVC 2 Project

6. Once it open's we'll need to add a reference to ninject.core.dll



7. Next, let's create a helper method for our ninject controller factory called NinjectControllerFactory.cs



8. We'll need to inherit from the default controller factory. Mainly so we don't have to re-invent the wheel and we can just override one part of it.

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

namespace NinjectIoc
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
    }


9. For the purposes of this demo we'll need to create an example service and interface, to demo the Ioc process and ninject.

namespace ExampleServices
{
    public interface IExampleInterface
    {
        void Method1();
        string Property1 { get; }
    }   

    public class ExampleConcreteClass : IExampleInterface
    {

        #region IExampleInterface Members   

        public void Method1()
        {
            // Do Nothing.
        }   

        public string Property1
        {
            get
            {
                return "Hello World";
            }
        }   

        #endregion
    }
}

10. Now we can setup a ninject Module which returns our ExampleConcreteClass when given the IExampleInterface

11. We do this by creating a class which inherits from ninjects standardmodule and overrides the Load Method

private class ExampleConfigModule : StandardModule

    {

        public override void Load()

        {

            Bind<IExampleInterface>().To<ExampleConcreteClass>();

        }

    }

12. Finally we'll override the GetControllerInstance Method from the DefaultControllerFactory using ninject to return a controller complete with any parameters in the controllers constructor.

public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel kernel = new StandardKernel(new ExampleConfigModule());   

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            // We don't want to pass null to ninject as we'll get a strange error.
            return controllerType == null ? null
                                          :
(IController)kernel.Get(controllerType);
        }
    }


13. Now we'll need to tell the MVC 2 framework to use our new Controller Factory insted of the defaultControllerFactory.

14. To do this we'll need to edit the global.asax.cs file

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 = UrlParameter.Optional } // Parameter defaults
            );   

            // Setup Our new Controller Factory.
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());   

        }


15. That's it for the setup. Now we'll need to test it out.

16. Let's update the default Home Controller to include a parameter in it's constructor

public class HomeController : Controller
    {
        #region Testing Our Controller Factory   

        private IExampleInterface _example;   

        public HomeController(IExampleInterface exampleInterface)
        {
            // Test our our new Ninject Controller Factory
            _example = exampleInterface;
        }   

        #endregion   

        public ActionResult Index()
        {
            // Will it work?? 
            ViewData["Message"] = _example.Property1;   

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }

17. Now if this work's we should see the word's "Hello World" on the home page.



18. It’s worked.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Log exceptions with Health Monitoring in ASP.NET MVC3

clock February 7, 2011 10:05 by author Jervis

Out of the box, ASP.NET MVC3 applications have basic error handling. To see, let’s create an action that will deliberately throw an error.
HomeController.cs:

public ActionResult NoView() // this Action has no view, for testing error handling! 
{ 
    return View(); 
}

Now when we hit /Home/NoView (in our development environment), we get the YSOD because MVC raises an InvalidOperationException, as expected.




In our production environment the error is automatically handled nicely and the /Shared/Error view is shown:



I’m not quite sure how MVC is handling the error in production under the covers, since I am NOT specifying the [HandleError] attribute anywhere. Hmm, wait a second, what’s this?
Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)      { 
        filters.Add(new HandleErrorAttribute()); 
    }

Cool, I just learnt something. The [HandleError] attribute is registered globally when we created a new
project. That’s going to make the rest of this blog post easier…

Logging Exceptions

In our development environment, when these exceptions are thrown they appear in the eventlog. But in production, they don’t get put into the eventlog
. We need to log them somewhere!
There’s a bucketload of ways to log in ASP.NET – log4net, ELMAH, etc. But I decided I wanted to use one that comes built into ASP.NET – health monitoring.

Heath monitoring


Following the helpful chaps at 4guysfromRolla, we can enable .NET health monitoring by editing our web.config:

 <configuration> 
     <system.web> 
       <healthMonitoring enabled="true"> 
        <eventMappings> 
           <clear /> 
           <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent"
                    startEventCode="0" endEventCode="2147483647" /> 
        </eventMappings> 

        <providers> 
           <clear /> 
           <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider" />   
        </providers>     

        <rules> 
           <clear /> 
           <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider"
                    profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" /> 
        </rules> 
       </healthMonitoring> 
     </system.web> 
 </configuration>


But that’s not enough. For some reason, the ASP.NET MVC [HandleError] attribute (registered globally in Global.ascx.cs, remember) doesn’t invoke the health monitoring features. But thanks to
a helpful post by Andrew Wilinski, we can create our own HandleError attribute which will. Create a new class called HandleErrorHm.cs:

/// <seealso cref="http://weblogs.asp.net/awilinsk/archive/2008/12/11/handleerrorattribute-and-health-monitoring.aspx"/> 
public class HandleErrorHmAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext context) 
    { 
        base.OnException(context); 
        new WebRequestErrorEventMvc("An unhandled exception has occurred.", this, 103005, context.Exception).Raise(); 
    } 
}
 

public class WebRequestErrorEventMvc : WebRequestErrorEvent 
{ 
    public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, Exception exception) : base(message, eventSource, eventCode, exception) {} 
    public WebRequestErrorEventMvc(string message, object eventSource, int eventCode, int eventDetailCode, Exception exception) : base(message, eventSource, eventCode, eventDetailCode, exception) {} 
}

And now change our Global.asax.cs to use our attribute instead:

public class MvcApplication : System.Web.HttpApplication 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
        filters.Add(new HandleErrorHmAttribute()); 
    }

Our exceptions appear in the eventlog on our production web server.

Logging to a SQL database


Since I’m already using ASP.NET authentication I already have an aspnet_WebEvent_Events table. So if I follow the rest of the 4GuysfromRolla post, I can set it up to log to my existing application database:

 <connectionStrings> 
     <add name="ApplicationServices" connectionString="Data Source=.\sqlexpress;Initial Catalog=Jobs;Integrated Security=True" providerName="System.Data.SqlClient" /> 
   </connectionStrings> 
 ... 
   <system.web> 
     <healthMonitoring enabled="true"> 
       <eventMappings> 
         <clear /> 
         <!-- Log ALL error events -->
         <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent" startEventCode="0" endEventCode="2147483647" /> 
         <!-- Log application startup/shutdown events -->
         <add name="Application Events" type="System.Web.Management.WebApplicationLifetimeEvent" startEventCode="0" endEventCode="2147483647"/> 
       </eventMappings> 
       <providers> 
         <clear /> 
         <!-- Provide any customized SqlWebEventProvider information here (such as a different connection string name value -->
         <add connectionStringName="ApplicationServices" maxEventDetailsLength="1073741823" buffer="false" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider" /> 
       </providers> 
       <rules> 
         <clear /> 
         <add name="All Errors Default" eventName="All Errors" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" /> 
         <add name="Application Events Default" eventName="Application Events" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" /> 
       </rules> 
     </healthMonitoring>

And now my errors are logged to my SQL database (although they’re not very readable).

What about 404 errors?


We don’t really want 404 errors to be handled in the same way – we should show the user a “page not found” error page instead of the generic “an error occured” page.
Web.Release.config:

<system.web> 
  <compilation xdt:Transform="RemoveAttributes(debug)" /> 
  <customErrors mode="On" xdt:Transform="Replace"> 
    <error statusCode="404" redirect="/Home/NotFound"/> 
  </customErrors> 
</system.web>

HomeController.cs:

public ActionResult NotFound() // web.config sends 404s here 
{ 
    return View(); 
}

Then in Views/Shared, add a new view called NotFound.cshtml:

@{ 
    ViewBag.Title = "404 Not Found"; 
} 

<h2>@ViewBag.Title</h2> 

Sorry, but we couldn't find that page.

Note that in our dev environment it will still show the YSOD for 404s, but in production our users will get redirected correctly.



One final note: if you follow these steps, 404s are NOT logged by health monitoring.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET MVC 3 Hosting - ASPHostPortal :: Rolling with Razor in MVC v3 Preview

clock February 4, 2011 04:59 by author Jervis

Razor is an alternate view engine for asp.net MVC.  It was introduced in the “WebMatrix” tool and has now been released as part of the asp.net MVC 3 preview 1.  Basically, Razor allows us to replace the clunky <% %> syntax with a much cleaner coding model, which integrates very nicely with HTML.  Additionally, it provides some really nice features for master page type scenarios and you don’t lose access to any of the features you are currently familiar with, such as HTML helper methods.

First, download and install the ASP.NET MVC Preview 1.  You can find this at
http://www.microsoft.com/downloads/details.aspx?FamilyID=cb42f741-8fb1-4f43-a5fa-812096f8d1e8&displaylang=en.

Now, follow these steps to create your first asp.net mvc project using Razor:

1. Open Visual Studio 2010
2. Create a new project.  Select File->New->Project (Shift Control N)
3. You will see the list of project types which should look similar to what’s shown:



4. Select “ASP.NET MVC 3 Web Application (Razor).”  Set the application name to RazorTest and the path to c:projectsRazorTest for this tutorial. If you select accidently select ASPX, you will end up with the standard asp.net view engine and template, which isn’t what you want.

5. For this tutorial, and ONLY for this tutorial, select “No, do not create a unit test project.”  In general, you should create and use a unit test project.  Code without unit tests is kind of like diet ice cream.  It just isn’t very good.



Now, once we have this done, our brand new project will be created.    In all likelihood, Visual Studio will leave you looking at the “HomeController.cs” class, as shown below:



Immediately, you should notice one difference.  The Index action used to look like:

public ActionResult Index ()
{
ViewData[“Message”] = “Welcome to ASP.Net MVC!”;
Return View();
}


While this will still compile and run just fine, ASP.Net MVC 3 has a much nicer way of doing this:

public ActionResult Index()
{
ViewModel.Message = “Welcome to ASP.Net MVC!”;
Return View();
}


Instead of using ViewData we are using the new ViewModel object, which uses the new dynamic data typing of .Net 4.0 to allow us to express ourselves much more cleanly. 

This isn’t a tutorial on ALL of MVC 3, but the ViewModel concept is one we will need as we dig into Razor.

What comes in the box?
When we create a project using the ASP.Net MVC 3 Template with Razor, we get a standard project setup, just like we did in ASP.NET MVC 2.0 but with some differences.  Instead of seeing “.aspx” view files and “.ascx” files, we see files with the “.cshtml” which is the default razor extension. 

Before we discuss the details of a razor file, one thing to keep in mind is that since this is an extremely early preview, intellisense is not currently enabled with the razor view engine.  This is promised as an updated before the final release. 

Just like with the aspx view engine, the convention of the folder name for a set of views matching the controller name without the word “Controller” still stands.  Similarly, each action in the controller will usually have a corresponding view file in the appropriate view directory.  Remember, in asp.net MVC, convention over configuration is key to successful development!

The initial template organizes views in the following folders, located in the project under Views:

- Account – The default account management views used by the Account controller.  Each file represents a distinct view.
- Home – Views corresponding to the appropriate actions within the home controller.
- Shared – This contains common view objects used by multiple views.  Within here, master pages are stored, as well as partial page views (user controls).  By convention, these partial views are named “_XXXPartial.cshtml” where XXX is the appropriate name, such as _LogonPartial.cshtml.  Additionally, display templates are stored under here.

With this in mind, let us take a look at the index.cshtml file under the home view directory. 

When you open up index.cshtml you should see

1:   @inherits System.Web.Mvc.WebViewPage
2:  @{
3:          View.Title = "Home Page";
4:       LayoutPage = "~/Views/Shared/_Layout.cshtml";
5:   }
6:  <h2>@View.Message</h2>
7:  <p>
8:     To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC    
9:    Website">http://asp.net/mvc</a>.
10:  </p>


So looking through this, we observe the following facts:

Line 1 imports the base page that all views (using Razor) are based on, which is System.Web.Mvc.WebViewPage.  Note that this is different than System.Web.MVC.ViewPage which is used by asp.net MVC 2.0

Also note that instead of the <% %> syntax, we use the very simple ‘@’ sign.  The View Engine contains enough context sensitive logic that it can even distinguish between @ in code and @ in an email.  It’s a very clean markup. 

Line 2 introduces the idea of a code block in razor.  A code block is a scoping mechanism just like it is in a normal C# class.  It is designated by @{… }  and any C# code can be placed in between.  Note that this is all server side code just like it is when using the aspx engine and <% %>. 

Line 3 allows us to set the page title in the client page’s file.  This is a new feature which I’ll talk more about when we get to master pages, but it is another of the nice things razor brings to asp.net mvc development.

Line 4 is where we specify our “master” page, but as you can see, you can place it almost anywhere you want, because you tell it where it is located.  A Layout Page is similar to a master page, but it gains a bit when it comes to flexibility.  Again, we’ll come back to this in a later installment. 

Line 6 and beyond is where we display the contents of our view.  No more using <%: %> intermixed with code.  Instead, we get to use very clean syntax such as @View.Message.  This is a lot easier to read than <%:@View.Message%> especially when intermixed with html.  For example:

<p>
My name is @View.Name and I live at @View.Address
</p>


Compare this to the equivalent using the aspx view engine

<p>
My name is <%:View.Name %> and I live at <%: View.Address %>
</p>

While not an earth shaking simplification, it is easier on the eyes.  As  we explore other features, this clean markup will become more and more valuable. 


Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.


You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



Silverlight 4 Hosting - ASPHostPortal :: Integratng Microsoft Translator Service into Silverlight and Windows Phone

clock February 2, 2011 05:34 by author Jervis

Sample of the control in Silverlight 4 App



Sample of the control in Windows Phone 7 Application



It just has one important property you have to set, the Application Id of Microsoft Translator. You can get one here (
http://developer.live.com).



The control has two events.



To translate text from one language (de-de = Germany) into one other (en-us = English US) is extremly simple. Problems like synchronizing the background thread into the UI-Thread is hidden in the control.

The following code demonstrates the easiness of using.

private void MicrosoftTranslator_Translated(object sender, TheOliver.Controls.TranslatorEventArgs args)
{
    _out.Text =args.TranslatedText;
}

private void MicrosoftTranslator_TranslationError(object sender, TheOliver.Controls.TranslatorErrorEventArgs args)
{
    _out.Text= args.Error.Message;
}

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
    _mts.Translate(_in.Text, "de-de", "en-us");

Here is the complete code of the Microsoft Translator Service:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace TheOliver.Controls
{
    public class MicrosoftTranslator : UserControl, InotifyPropertyChanged
    {
        private string _appId;
        public string AppId
        {
            get { return _appId; }
            set { _appId = value; }
        }

        private bool _isBusy = false;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                OnPropertyChanged("IsBusy");
                this.IsIdle = !_isBusy;
            }
        }

        private bool _isIdle = true;
        public bool IsIdle
        {
            get { return _isIdle; }
            set
            {
                _isIdle = value;
                OnPropertyChanged("IsIdle");
            }
        }

        private byte[] _bytes;

        public MicrosoftTranslator()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                StackPanel sp = new StackPanel();
                sp.Background = new SolidColorBrush(Colors.Red);

                TextBlock tb = new TextBlock();
                tb.Text = "[Microsoft Translator Service]";

                sp.Children.Add(tb);
                this.Content = sp;
            }
        }

        public void Translate(string sourceText, string sourceLanguage, string targetLanguage)
        {
            if (this.AppId == string.Empty || this.AppId == null)
            {
                MessageBox.Show("No AppId for Translator service defined. You can get an AppId at http://dev.live.com.");
                return;
            }

            this.IsBusy = true;

            // Creating a string with the request URL
            // The URL includes the Bing developer appId and in this case hardcoded to translate from
            // English to Spanish
            string translateUri =             "http://api.microsofttranslator.com/V1/Http.svc/Translate?appId=" + _appId
                + "&from=" + sourceLanguage
                + "&to=" + targetLanguage;

            // Create a web request to the URL
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(translateUri);

            // Set the request method to POST
            httpWebRequest.Method = "POST";

            // Set the content type (needs to be text/plain for POST methods)
            httpWebRequest.ContentType = "text/plain";

            // Encode the txtInput value bytes for the POST
            _bytes = Encoding.UTF8.GetBytes(sourceText);

            // Create a stream for the request
            httpWebRequest.BeginGetRequestStream(new AsyncCallback(OnGetRequestStream), httpWebRequest);
        }

        private void OnGetRequestStream(IAsyncResult iar)
        {
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)iar.AsyncState;
                Stream os = httpWebRequest.EndGetRequestStream(iar);

                os.Write(_bytes, 0, _bytes.Length);

                if (os != null)
                {
                    // Close the stream when finished
                    os.Close();
                }

                // Send the request and get the response
                httpWebRequest.BeginGetResponse(new AsyncCallback(OnGetResponse), httpWebRequest);
            }
            catch (Exception exc)
            {
                RaiseError(exc);
            }
        }

        private void OnGetResponse(IAsyncResult iar)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)iar.AsyncState;

                if (!iar.IsCompleted)
                {
                    Debug.WriteLine("Not completed");
                }
                WebResponse response = request.EndGetResponse(iar);

                // Open a stream for the response
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);

                // Create a string for the contents of the web response
                string output = reader.ReadToEnd();

                // Return the output string
                OnTranslated(output);
            }
            catch (Exception exc)
            {
                RaiseError(exc);
            }
        }

        public event TranslatorEventHandler Translated;
        public event TranslatorErrorEventHandler TranslationError;

        private void OnTranslated(string output)
        {
            this.IsBusy = false;
            if (Translated != null)
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        TranslatorEventArgs args = new TranslatorEventArgs();
                        args.TranslatedText = output;
                        Translated(this, args);
                    });
            }
        }

        private void RaiseError(Exception exc)
        {
            this.IsBusy = false;
            if (TranslationError != null)
            {

                Dispatcher.BeginInvoke(() =>
                    {
                        TranslatorErrorEventArgs args = new TranslatorErrorEventArgs();
                        args.Error = exc;
                        TranslationError(this, args);
                    });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                Dispatcher.BeginInvoke(() =>
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                    });
            }
        }
    }

    public delegate void TranslatorEventHandler(object sender, TranslatorEventArgs args);

    public class TranslatorEventArgs : EventArgs
    {
        public string TranslatedText { get; set; }
    }

    public delegate void TranslatorErrorEventHandler(object sender, TranslatorErrorEventArgs args);

    public class TranslatorErrorEventArgs
    {
        public Exception Error { get; set; }
    }
}

I hope you like this sample and the translator app.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

-
DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



ASP.NET 4 Hosting - ASPHostPortal :: CSS Friendly Menu Control in ASP.NET 4.0

clock February 1, 2011 06:49 by author Jervis

It is very much easier to apply CSS when we have ul,li elements as the HTML content. If we look into ASP.NET Menu Control till Version 3.5, its render as Table-TR-TD Tag. Though Table/Tr/Td is quite useful to display tabular data but sometime  creates  a big problem when we need to do more work with CSS. To overcome this problem we generally used CSS Friendly adapter to render the ASP.NET Control in ul/li mode.

ASP.NET 4.0 makes the things easier for web developer by providing “RenderingMode” properties. Here we can specify RenderMode of a ASP.NET Menu control. Which define the what will be the HTML Render Content Type. Bydefault mode is “List” which means control will be render as ul/li. 



As per the above diagram we can see that there are three mode available. We can use any one of them as per the requirement.

Let’s see one small  example by using the ASP.Net menu web  control and check how it renders as HTML in ASP.Net 4.0.  Assume that we are having the following piece of code

<asp:Menu runat="server" ID="customeMenu" RenderingMode="List" >
            <Items>
                <asp:MenuItem Text="File" Value="File"></asp:MenuItem>
                <asp:MenuItem Text="Edit" Value="Edit"></asp:MenuItem>
                <asp:MenuItem Text="View" Value="View"></asp:MenuItem>
                <asp:MenuItem Text="WebSite" Value="WebSite"></asp:MenuItem>
            </Items>
        </asp:Menu>


This Menu control will be render as below html code  in  ASP.NET 4.0 as, we have mentioned “List” as the rendering mode.

<ul>
        <li><a  href="#">File</a></li>
        <li><a  href="#">Edit</a></li>
        <li><a  href="#">View</a></li>
        <li><a  href="#">WebSite</a></li>
    </ul>

To test the above scenario run the web application that contain the menu control and after page rendered complete Right Click on  view source of the aspx page. The output will be look like as bellow.



We can also generate the Menu Control as HTML Table like earlier version by using RenderingMode=”Table”.

So, for the same block of code,


<asp:Menu runat="server" ID="customeMenu" RenderingMode="Table" >
           <Items>
               <asp:MenuItem Text="File" Value="File"></asp:MenuItem>
               <asp:MenuItem Text="Edit" Value="Edit"></asp:MenuItem>
               <asp:MenuItem Text="View" Value="View"></asp:MenuItem>
               <asp:MenuItem Text="WebSite" Value="WebSite"></asp:MenuItem>
           </Items>
       </asp:Menu>

HTML Rendered output will be as follows

<table > 
     <tr > 
        <td><table> 
             <tr> 
                 <td >File</a></td> 
             </tr> 
         </table></td> 
     </tr><tr> 
         <td><table > 
             <tr> 
                 <td>Edit</a></td> 
             </tr> 
         </table></td> 
     </tr><tr> 
         <td><table > 
             <tr> 
                 <td >View</a></td> 
             </tr> 
         </table></td> 
     </tr><tr > 
         <td><table > 
             <tr> 
                 <td>WebSite</a></td> 
             </tr> 
         </table></td> 
     </tr> 
 </table>



Note: With the above html content ASP.NET engine automatically adds few client side script along like onmouseover=”Menu_HoverStatic(this)” onmouseout=”Menu_Unhover(this)” onkeyup=”Menu_Key(this)” id=”customeMenun0″ with rendered menu items. Which helps the developer to handel the client side events.

Reasons why you must trust ASPHostPortal.com

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

- DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in