European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Nederland :: How to Schedule Job in ASP.NET MVC 3/MVC 4

clock December 31, 2013 06:50 by author Scott

As always, we try to keep our Scheduler .NET control up-to-date and easy to use. Nowadays it supports all the latest .NET frameworks and IDEs, including ASP.NET 4.5 and Visual Studio 2012.

With regard to all recent updates, your remarks and fixed bugs, we decided to give you further setup instructions. This time we explain how Scheduler .NET setup process can be reduced to only 5 steps that you can cover in less than 5 minutes.

This article represents a new step-by-step guide on how to create a simple yet elegant Google-like calendar/scheduler in ASP.NET MVC3/MVC4 Razor (C#).

1. Create a New Project

Create a new project in Visual Studio by selecting ASP.NET MVC 3/ MVC4 Web Application from the list. The project template should be empty. The view engine is Razor by default.

We will create a simple scheduler in C#.

2. Set Up the Database

The next step is to set up a database. Right-click on ‘Your_project_name’ (e.g. SimpleScheduler) ->  Add -> Add ASP.NET Folder -> App_Data -> Add New Item and name it “Sample.mdf”. 

A new database has been created. 

Note: for ASP.NET MVC4 project the folder App_Data is created automatically.

Go to the Server Explorer to create a new Table “Events”. Right-click on the Table folder to add the following query. It creates a table with all necessary fields including primary key and identity column:

CREATE TABLE [dbo].[Events](
  [id] int IDENTITY(1,1) NOT NULL,
  [text] nvarchar(250) NULL,
  [start_date] datetime NOT NULL,
  [end_date] datetime NOT NULL,
  PRIMARY KEY (id)
)

3. Scheduler Setup via NuGet

Right-click on you project name in the Solution Explorer to select “Manage NuGet Packages…”: 

For quick search type  ‘dhtmlx’ in the input. In a moment you’ll see DHMTLX Scheduler .NET library and the available samples: 

To save your time, install MVC3 Sample first. It contains the basic template of Scheduler .NET calendar control. The template includes a controller with three actions (initialization, data load and save) and view with a calendar.

Thus, the installed sample updates the project with:

  • /Controllers/CalendarController.cs  -- a controller that needs updating;
  • /Views/Calendar/Index.cshtml   -- a calendar page that requires no changes;
  • /Models/CalendarEvent.cs  -- a sample model that can be deleted.

4. Create Scheduler Model

The installed MVC3 Sample also contains a sample class model. You don’t need it and can delete it.

To create a new model right-click on the folder Models -> Add New Item. In the new opened window choose LINQ to SQL Classes and name it Sample.dbml. Double click it to open a visual editor and drag the Event table from the Server Explorer to the Editor.

5. Updating a Controller

As stated above, the controller has been created when you installed MVC3 Sample. It contains action templates for data load and save, working with static data.

Let’s update the methods in the CalendarController.cs to connect the controller with the newly created Model. 

First we need to load data from the Model. 

The default data load before update looks as follows:

public ContentResult Data()
{
    var data = new SchedulerAjaxData(
        new List<CalendarEvent>{
            new CalendarEvent{
                id = 1,
                text = "Sample Event",
                start_date = new DateTime(2012, 09, 03, 6, 00, 00),
                end_date = new DateTime(2012, 09, 03, 8, 00, 00)
            },
            ...
        });
    return (ContentResult)data;
}

Let’s update the DataAction to load data from SampleDataContext:

public ContentResult Data()
{
            var data = new SchedulerAjaxData(new SampleDataContext().Events);
            return (ContentResult)data;
}

Secondly, enable data save. The data save set by default is:

public ContentResult Save(int? id, FormCollection actionValues)
{
    var action = new DataAction(actionValues);             

    try
    {
        var changedEvent = (CalendarEvent)DHXEventsHelper.Bind(typeof(CalendarEvent), actionValues);
        switch (action.Type)
        {
            case DataActionTypes.Insert:
                //do insert
                action.TargetId = changedEvent.id;//assign postoperational id
                break;
            case DataActionTypes.Delete:
                //do delete
                break;
            default:// "update"                         
                //do update
                break;
        }
    }
}

Data save parses the request, contains a switch case for all types of operations and returns operation success. Let’s update it to enable save of actual changes:

public ContentResult Save(int? id, FormCollection actionValues)
{
     var action = new DataAction(actionValues); 

     var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), actionValues); 

     var data = new SampleDataContext(); 

     try
     {
          switch (action.Type)
          {
              case DataActionTypes.Insert: // define here your Insert logic
                  data.Events.InsertOnSubmit(changedEvent);                             

                  break;
              case DataActionTypes.Delete: // define here your Delete logic
                  changedEvent = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                  data.Events.DeleteOnSubmit(changedEvent);
                  break;
              default:// "update" // define here your Update logic
                  var eventToUpdate = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                  DHXEventsHelper.Update(eventToUpdate, changedEvent, new List<string>() { "id" });//update all properties, except for id
                  break;
              }
              data.SubmitChanges();
              action.TargetId = changedEvent.id;
         }
     }
}

We have changed the Model class used in the method. We’ve also added the required methods from LINQ to SQL and a helper that updates all object properties in the data base (except for the id).

Notes.

The initial class model in the action used to be:

public ContentResult Save(int? id, FormCollection actionValues)
        {
            var action = new DataAction(actionValues);

If a new event is added to the data base, an id assigned to the new event in the data base should be returned to the client. It returns TargetId of the object itself.

action.TargetId = changedEvent.id;

This action is implemented after changes are submitted: data.SubmitChanges();

The full code will look like this:

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

using DHTMLX.Scheduler;
using DHTMLX.Common;
using DHTMLX.Scheduler.Data;
using SimpleScheduler.Models;
namespace SimpleScheduler.Controllers
{
    public class CalendarController : Controller
    {
        public ActionResult Index()
        {
            var scheduler = new DHXScheduler(this); 

            scheduler.Skin = DHXScheduler.Skins.Terrace;
            scheduler.InitialDate = new DateTime(2012, 09, 03); 

            scheduler.Config.multi_day = true;//render multiday events 

            scheduler.LoadData = true;
            scheduler.EnableDataprocessor = true; 

            return View(scheduler);
        } 

        public ContentResult Data()
        {
            var data = new SchedulerAjaxData(
                    new SampleDataContext().Events
                ); 

            return (ContentResult)data;
        } 

        public ContentResult Save(int? id, FormCollection actionValues)
        {
            var action = new DataAction(actionValues);
            var changedEvent = (Event)DHXEventsHelper.Bind(typeof(Event), actionValues);
            var data = new SampleDataContext(); 

            try
            {
                switch (action.Type)
                {
                    case DataActionTypes.Insert: // define here your Insert logic
                        data.Events.InsertOnSubmit(changedEvent); 

                        break;
                    case DataActionTypes.Delete: // define here your Delete logic
                        changedEvent = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                        data.Events.DeleteOnSubmit(changedEvent);
                        break;
                    default:// "update" // define here your Update logic
                        var eventToUpdate = data.Events.SingleOrDefault(ev => ev.id == action.SourceId);
                        DHXEventsHelper.Update(eventToUpdate, changedEvent, new List<string>() { "id" });//update all properties, except for id
                        break;
                }
                data.SubmitChanges();
                action.TargetId = changedEvent.id;
            }
            catch (Exception a)
            {
                action.Type = DataActionTypes.Error;
            }
            return (new AjaxSaveResponse(action));
        }
    }
}

Finally, update the route from ‘Home’ to ‘Calendar’ in Global.asax.cs as follows:

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

Note: ASP.NET MVC4 project creates App_Start directory with configuration files. The controller route is changed to "Calendar" in Route.Config.cs:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Calendar", action = "Index", id = UrlParameter.Optional }
            );

That’s it! The scheduler for ASP.NET MVC3/MVC4 Razor is ready to use.



European ASP.NET MVC 5 Hosting - Amsterdam :: New Filter Overrides Feature in ASP.NET MVC 5

clock December 30, 2013 07:07 by author Scott

In this quick article, I will tell you the problem that filter overrides is trying to solve(with an example). I will also show you a quick fix of a bug that I found in ASP.NET MVC 5 regarding filter overrides.

Description:

Let say you have an Authorize filter applied on a controller and a action

[Authorize(Roles = "PowerUsers")]
public class AController : ApiController
{   

    // GET api/api
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
    [Authorize(Roles = "Admin")]
    // GET api/api/5
    public string Get(int id)
    {
        return "value";
    }
}

Now you want that all actions of above controller should only run when the user is in PowerUsers role except for second Get method which requires an Admin role. Before ASP.NET MVC 5 and ASP.NET Web API 2, it was not possible to achieve this(without using a dirty hack). But the current version make this a piece of cake, using OverrideAuthorizationAttribute. Just put this attribute on the second Get action above and then you are done. For the further understanding of this, just use this controller and custom authorize filter,

public class MyAuthorizeAttribute : AuthorizeAttribute
   {
       string name;
       public MyAuthorizeAttribute(string s)
       {
           name = s;
       }
       public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
           base.OnAuthorization(actionContext);
       }
   }
   [MyAuthorize("Controller")]
   public class AController : ApiController
   {
       [MyAuthorize("Action")]
       //[OverrideAuthorization]
       // GET api/api
       public IEnumerable<string> Get()
       {
           return new string[] { "value1", "value2" };
       }
       // GET api/api/5
       public string Get(int id)
       {
           return "value";
       }
   }

Now just put a break-point on MyAuthorizeAttribute constructor and OnAuthorization method. You will find that the constructor is invoked for both action and controller but only the controller's MyAuthorizeAttribute.OnAuthorization(by checking name variable) is called. Now just un-comment the[OverrideAuthorization], you will find that action method's MyAuthorizeAttribute.OnAuthorization is called. When you do the same in MVC 5, it will not work due to a bug(AFAIK) in MVC 5 RC. Hopefully will be fixed in RTM. But for now you can use this hack to make this work in MVC 5 as well. Here is an example,

public class OverrideAuthorizeAttribute : AuthorizeAttribute, IOverrideFilter
   {
       public Type FiltersToOverride
       {
           get { return typeof(IAuthorizationFilter); }
       }
   }
   [Authorize(Users="Admin")]
   public class HomeController : Controller
   {
       [OverrideAuthorize(Users = "Imran Baloch")]
       public ActionResult Index()
       {
           return View();
       }       

       public ActionResult About()
       {
           ViewBag.Message = "Your application description page.";
           return View();
       }

       public ActionResult Contact()
       {
           ViewBag.Message = "Your contact page.";

           return View();
       }
   }

The hack is simply creating a new OverrideAuthorizeAttribute inheriting from AuthorizeAttribute and implementing IOverrideFilter interface and then applying this to the Index action method.

 



European ASP.NET MVC 5 Hosting :: Upgrade ASP .NET MVC 5 default layout to bootstrap 3

clock December 20, 2013 06:58 by author Patrick

If you have started developing web applications with ASP .NET MVC 5 you might have noticed that it comes with bootstrap version 2 and the latest version 3. In order to upgrade the default template for version 3, you can use these files as a reference.

Right click solution -> Manage NuGet packages Updates -> Update bootstrap to version 3 >

***Views/Shared/_Layout.cshtml***

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
                           @Html.Partial("_LoginPartial")
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li class="divider"></li>
                            <li class="dropdown-header">Nav header</li>
                            <li><a href="#">Separated link</a></li>
                            <li><a href="#">One more separated link</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!--/.nav-collapse -->
        </div>
    </div>
    <div class="container">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

 

***Views/Shared/_LoginPartial.cshtml***

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-form pull-right" }))
    {
    @Html.AntiForgeryToken()
    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id
= "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id =
"loginLink" })</li>
    </ul>
}

 



HostForLIFE.eu Proudly Launches Scalable Enterprise Email Hosting

clock December 17, 2013 09:32 by author Patrick

 

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team proudly announces Enterprise Email Hosting for all costumer. HostForLIFE.eu aim to help you grow your bottom line whether it is driving direct sales from emails, driving website traffic or delivering outstanding service.

Enterprise Email is a great tool for communicating to existing customers, or individuals who know your organization well enough and have interest in opting-in to receive your e-mail. Your promotions, sales and offers get their attention, meet a need, and encourage them to do more business with you.  What e-mail marketing typically doesn’t do very effectively is attract the attention of new customers.

Robert Junior and Sophia Levine from HostForLIFE.eu say:
"Once a business has secured a domain name, we setup an email hosting account for them and they can choose any email account they wish.  Most popular email accounts for small business are sales, info and accounts, although it can be virtually anything once you own your own domain name." Robert says.

"I would expect that once more small business owners had the flexibility to mange their own email hosting, they would save money on their monthly internet costs because there are always cheaper deals being promoted. Of course email hosting does not replace your internet service, but it enables you to switch to a cheaper plan and not loose contact with your customers."  Sophia says.

"Our clients have found that they are able to save money on their internet services because once they no longer rely to manage their email, they can shop around for a better deal, save some money and take their Email Hosting with them.  Having your own domain name and email hosting also improves your business image far more that an ISP account or hotmail email address." Robert says.

"What many small business owners often struggle with is continuing to pay high internet service costs to keep their allocated ISP email address if they use their ISP email for their business.  What people do not realise is that if they were to purchase their own .com or etc domain name they have a unique email address like '[email protected]'.  It means they can move to a cheaper ISP if they find a better deal and not risk losing contact with their business contacts." Sophia Says.

HostForLIFE.eu provides a full suite of self-service marketing solutions with the following features: Total Bulk Email up to 10.000 emails/month with total maibox is 5, users receive 2 GB mailbox quota, a platform fully support Blackberry, SPF/DKIM/TXT, WebMail Access, and POP/SMTP/IMAP.

Are you sending direct mails to your customers just once a month or every three days? Simply choose the plan that suits you the most. All price plans are based on actual use of the system - from 10,000 e-mails sent out in a month starting at €8.00!

Further information and the full range of features Enterprise Email Hosting can be viewed here http://www.hostforlife.eu.



European ASP.NET MVC 5 Hosting :: Introducing ASP.Net SignalR in MVC 5

clock December 17, 2013 05:29 by author Patrick

In this article I am using the ASP.NET SignalR library in the latest MVC 5 project template. Now, what is this real-time functionality? It is used to access the server code and push the content to the connected clients instantly instead of the server waiting for the client's request.

Prerequisites

Using Visual Studio 2013. There are some prerequisites to develop the application:

  • Visual Studio 2010 SP1 or Visual Studio 2012.
  • ASP.NET and Web Tools 2012.2

Let's create an application for SignalR development using the following sections:

  • MVC 5 Application
  • Code Execution

MVC 5 Application

Step 1: Open Visual Studio 2013 and create a New Project.

Step 2: Select MVC project template.

Step 3: Open the Package Manager Console.

And write the following command:

install-package Microsoft.AspNet.SignalR

Step 4: You can see in your Solution Explorer that the SignalR was successfully added to your application.

Step 5: Add a new folder named Hubs in your application and add a class in it.

Give the name of your class ChatHub as shown below:

Step 6: Add the following code in the class:

using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void  LetsChat(string Cl_Name, string Cl_Message)
        {
            Clients.All.NewMessage(Cl_Name, Cl_Message);
        }
    }
}
Step 7: Open the Global.asax file and modify the Applicatio_Start() method as shown below:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Step 8:
Open your HomeController.cs file and modify it as shown below:
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page."
    return View();
}
public ActionResult Chat()
{
    ViewBag.Message = "Your chat page";
    return View();
}

Step 9: Generate the view for the Chat method as shown in the following parts:

Select Home folder and right-click to add Scaffold

(m8)

Select MVC 5 View in the Add Scaffold wizard

Do as directed in the following image:

Step 10: Add the following code in the Chat.cshtml file:
@{
    ViewBag.Title = "Chat";
}
<hgroup>
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
</hgroup>
<div class="container">
    <input type="text" id="TxtMessage" />
    <input type="button" id="BtnSend" value="Send" />
    <input type="hidden" id="UserName" />
    <ul id="Chats"></ul>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <script src="~/signalr/Hubs"></script>
    <script
        $(function () {
            var chat = $.connection.chatHub;
            chat.client.NewMessage=function(Cl_Name, Cl_Message) {
                $('#Chats').append('<li><strong>' + htmlEncode(Cl_Name)
                    + '</strong>: ' + htmlEncode(Cl_Message) + '</li>');
            };
            $('#UserName').val(prompt('Please Enter Your Name:', ''));
            $('#TxtMessage').focus();
            $.connection.hub.start().done(function () {
                $('#BtnSend').click(function () {
                    chat.server.LetsChat($('#UserName').val(), $('#TxtMessage').val())
                    $('#TxtMessage').val('').focus()
                });
            });
        });
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

Code Execution

Save all your application and debug the application. Use the following procedure.

Step 1: Debug your application. Open /Home/Chat in your browser like: http://localhost:12345/Home/Chat
Step 2: Enter your name in the prompt
Step 3: Enter message and send
Step 4: Copy the browser URL and open more browsers, paste the URL in the address bar and do the same thing as above.



European ASP.NET MVC 5 Hosting :: Introducing ASP.Net SignalR in MVC 5

clock December 17, 2013 05:29 by author Patrick

In this article I am using the ASP.NET SignalR library in the latest MVC 5 project template. Now, what is this real-time functionality? It is used to access the server code and push the content to the connected clients instantly instead of the server waiting for the client's request.

Prerequisites

Using Visual Studio 2013. There are some prerequisites to develop the application:

  • Visual Studio 2010 SP1 or Visual Studio 2012.
  • ASP.NET and Web Tools 2012.2

Let's create an application for SignalR development using the following sections:

  • MVC 5 Application
  • Code Execution

MVC 5 Application

Step 1: Open Visual Studio 2013 and create a New Project.

Step 2: Select MVC project template.

Step 3: Open the Package Manager Console.

And write the following command:

install-package Microsoft.AspNet.SignalR

Step 4: You can see in your Solution Explorer that the SignalR was successfully added to your application.

Step 5: Add a new folder named Hubs in your application and add a class in it.

Give the name of your class ChatHub as shown below:

Step 6: Add the following code in the class:

using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void  LetsChat(string Cl_Name, string Cl_Message)
        {
            Clients.All.NewMessage(Cl_Name, Cl_Message);
        }
    }
}
Step 7: Open the Global.asax file and modify the Applicatio_Start() method as shown below:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Step 8:
Open your HomeController.cs file and modify it as shown below:
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page."
    return View();
}
public ActionResult Chat()
{
    ViewBag.Message = "Your chat page";
    return View();
}

Step 9: Generate the view for the Chat method as shown in the following parts:

Select Home folder and right-click to add Scaffold

(m8)

Select MVC 5 View in the Add Scaffold wizard

Do as directed in the following image:

Step 10: Add the following code in the Chat.cshtml file:
@{
    ViewBag.Title = "Chat";
}
<hgroup>
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
</hgroup>
<div class="container">
    <input type="text" id="TxtMessage" />
    <input type="button" id="BtnSend" value="Send" />
    <input type="hidden" id="UserName" />
    <ul id="Chats"></ul>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <script src="~/signalr/Hubs"></script>
    <script
        $(function () {
            var chat = $.connection.chatHub;
            chat.client.NewMessage=function(Cl_Name, Cl_Message) {
                $('#Chats').append('<li><strong>' + htmlEncode(Cl_Name)
                    + '</strong>: ' + htmlEncode(Cl_Message) + '</li>');
            };
            $('#UserName').val(prompt('Please Enter Your Name:', ''));
            $('#TxtMessage').focus();
            $.connection.hub.start().done(function () {
                $('#BtnSend').click(function () {
                    chat.server.LetsChat($('#UserName').val(), $('#TxtMessage').val())
                    $('#TxtMessage').val('').focus()
                });
            });
        });
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

Code Execution

Save all your application and debug the application. Use the following procedure.

Step 1: Debug your application. Open /Home/Chat in your browser like: http://localhost:12345/Home/Chat
Step 2: Enter your name in the prompt
Step 3: Enter message and send
Step 4: Copy the browser URL and open more browsers, paste the URL in the address bar and do the same thing as above.



European ASP.NET MVC 5 Hosting :: Introducing ASP.Net SignalR in MVC 5

clock December 17, 2013 05:29 by author Patrick

In this article I am using the ASP.NET SignalR library in the latest MVC 5 project template. Now, what is this real-time functionality? It is used to access the server code and push the content to the connected clients instantly instead of the server waiting for the client's request.

Prerequisites

Using Visual Studio 2013. There are some prerequisites to develop the application:

  • Visual Studio 2010 SP1 or Visual Studio 2012.
  • ASP.NET and Web Tools 2012.2

Let's create an application for SignalR development using the following sections:

  • MVC 5 Application
  • Code Execution

MVC 5 Application

Step 1: Open Visual Studio 2013 and create a New Project.

Step 2: Select MVC project template.

Step 3: Open the Package Manager Console.

And write the following command:

install-package Microsoft.AspNet.SignalR

Step 4: You can see in your Solution Explorer that the SignalR was successfully added to your application.

Step 5: Add a new folder named Hubs in your application and add a class in it.

Give the name of your class ChatHub as shown below:

Step 6: Add the following code in the class:

using Microsoft.AspNet.SignalR;
namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        public void  LetsChat(string Cl_Name, string Cl_Message)
        {
            Clients.All.NewMessage(Cl_Name, Cl_Message);
        }
    }
}
Step 7: Open the Global.asax file and modify the Applicatio_Start() method as shown below:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Step 8:
Open your HomeController.cs file and modify it as shown below:
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page."
    return View();
}
public ActionResult Chat()
{
    ViewBag.Message = "Your chat page";
    return View();
}

Step 9: Generate the view for the Chat method as shown in the following parts:

Select Home folder and right-click to add Scaffold

(m8)

Select MVC 5 View in the Add Scaffold wizard

Do as directed in the following image:

Step 10: Add the following code in the Chat.cshtml file:
@{
    ViewBag.Title = "Chat";
}
<hgroup>
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
</hgroup>
<div class="container">
    <input type="text" id="TxtMessage" />
    <input type="button" id="BtnSend" value="Send" />
    <input type="hidden" id="UserName" />
    <ul id="Chats"></ul>
</div>
@section scripts {
    <script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
    <script src="~/signalr/Hubs"></script>
    <script
        $(function () {
            var chat = $.connection.chatHub;
            chat.client.NewMessage=function(Cl_Name, Cl_Message) {
                $('#Chats').append('<li><strong>' + htmlEncode(Cl_Name)
                    + '</strong>: ' + htmlEncode(Cl_Message) + '</li>');
            };
            $('#UserName').val(prompt('Please Enter Your Name:', ''));
            $('#TxtMessage').focus();
            $.connection.hub.start().done(function () {
                $('#BtnSend').click(function () {
                    chat.server.LetsChat($('#UserName').val(), $('#TxtMessage').val())
                    $('#TxtMessage').val('').focus()
                });
            });
        });
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}

Code Execution

Save all your application and debug the application. Use the following procedure.

Step 1: Debug your application. Open /Home/Chat in your browser like: http://localhost:12345/Home/Chat
Step 2: Enter your name in the prompt
Step 3: Enter message and send
Step 4: Copy the browser URL and open more browsers, paste the URL in the address bar and do the same thing as above.



European ASP.NET MVC 5 Hosting :: Getting Started With Areas in MVC 5

clock December 12, 2013 09:51 by author Patrick

MVC (Model, View, Controller) is a design pattern to separate the data logic from the business and presentation logic. We can also design the structure physically, where we can keap the logic in the controllers and views to exemplify the relationships.

It is also possible that we can have large projects that use MVC, then we need to split the application into smaller units called areas that isolate the larger MVC application into smaller functional groupings. A MVC application could contain several MVC structures (areas).  

How to creating a simple application for defining the area in MVC 5. MVC 5 is the latest version of MVC used in Visual Studio 2013?

You need to have the following to complete this article:

  • MVC 5
  • Visual Studio 2013

In that context, we'll follow the sections given below:MVC 5 application:

  • Adding Controller for Area
  • Adding Views for Area
  • Area Registration
  • Application Execution
  • MVC 5 Application

Use the following procedure to create a Web application based on a MVC 5 template.

Step 1: Open Visual Studio 2013.
Step 2: Create an ASP.NET Web Application with MVC 5 project template.

Step 3: In Solution Explorer, right-click on the project and click "Add" to add an area as shown below:

Step 4: Enter the name for the area, such as "News".

Step 5: Similarly add an another area named "Article".

Now from the steps above you have added two areas for your application named News and Article.

Adding Controller for Area

We have successfully added an area, now we'll add controllers for each of our areas using the following procedure.

Step 1: Right-click on the Controller in your Article area to add a controller.

Step 2: Select "MVC 5 Empty Controller".

Step 3: Enter the name as "ArticleController" .

Step 4: Similarly add the controller for "News".

Now your Area folder should be as in the following screenshot:

Adding Views for Area

We have successfully added a controller for our area, now to add a view for the area using the following procedure.

Step 1: Right-click on the "News" folder in the View to add a View for the News Area.

Step 2: Enter the view name as defined in the NewsController.

Step 3: Generate some content in the View of News as in the following screenshot:

Step 4: You can also add a view as shown in the following screenshot:

Step 5: Generate some content for the Article view.

Area Registration

Step 1: Open the "Global.asax" file.

Step 2: Add the following code in your Application_Start() method:

AreaRegistration.RegisterAllAreas();

Application Execution

Step 1: Open the project view Layout file.

Step 2: Modify the <ul> in the layout file as shown in the following code:

<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Article", "Index", "Article", new {area= "Article" }, null)</li>
<li>@Html.ActionLink("News", "Index", "News", new { area = "News" }, null)</li>
</ul>

Step 3: Debug the application, and finish!



European HostForLIFE.eu Proudly Launches Entity Framework 6 with FREE Trial Hosting

clock December 11, 2013 06:23 by author Patrick

HostForLIFE.eu offers a variety of cheap and affordable European Windows ASP.NET Shared Hosting Plans to fit any need. No matter whether you’re starting a Blog with WordPress, installing a CMS solution with Drupal, opening a Forum with PHPBB, starting an Online Store with nopCommerce, or any number ventures beyond those mentioned above, our Windows ASP.NET Web Hosting plans are exactly what you’ve been looking for. HostForLIFE.eu is Microsoft No #1 Recommended ASP.NET Host Provider.
Entity Framework 6 (EF6) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

Entity Framework is now available and there are top features to consider in this minor release:

Features that come for free. These are capabilities that are part of the core. You don’t even have to know they’re there to benefit from them, much less learn any new coding.

Level-setting features. A major enhancement is that Code First now supports mapping to Stored Procedures, something that has been supported by models created in the designer.

Another change is more interesting. With EF6, the EF APIs have been extracted from the .NET Framework; they’re now completely encapsulated in the NuGet package.

EF Designer in this category. It has been moved out of Visual Studio as of the 2013 edition, and instead provided as an extension to Visual Studio.

Ninja features. Support for asynchronous queries and saves, the return of custom Code First conventions, more extensibility using the new DbConfiguration type, support for mocking in unit tests, configurable retries on spotty connections, and even more.

For complete information about this new product, please visit our site at http://www.hostforlife.eu



European ASP.NET MVC 4 Hosting :: Tips on How To Improve MVC Application Performance

clock December 10, 2013 07:32 by author Patrick

In this post we will cover a few tips and tricks to improve ASP.NET MVC Application Performance. While working on this site, I have tried to improve page loading speeds as much as possible. There are a lot of tricks that you can do to improve the speed of your site. I have constantly been learning new things by delving into the world of site performance.

These are a few of the steps that I took to speed up my site:

Run in Release mode

Make sure your production application always runs in release mode in the web.config

  <compilation debug="false"></compilation>

or change this in the machine.config on the production servers

<configuration>
    <system.web>
          <deployment retail="true"></deployment>
    </system.web>
</configuration>

Only use the View Engines that you require

protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new RazorViewEngine());
}

Use the CachedDataAnnotationsModelMetadataProvider

ModelMetadataProviders.Current = new CachedDataAnnotationsModelMetadataProvider();

Avoid passing null models to views

Because a NullReferenceException will be thrown when the expression gets evaluated, which .NET then has to handle gracefully.

// BAD
public ActionResult Profile()
{
    return View();
}

// GOOD
public ActionResult Profile()
{
    return View(new Profile());
}

Use OutputCacheAttribute when appropriate

For content that does not change often, use the OutputCacheAttribute to save unnecessary and action executions.

[OutputCache(VaryByParam = "none", Duration = 3600)]
public ActionResult Categories()
{
    return View(new Categories());
}

Use HTTP Compression

<system.webserver>
<urlcompression dodynamiccompression="true" dostaticcompression="true" dynamiccompressionbeforecache="true"></urlcompression>
</system.webserver>

Remove unused HTTP Modules

If you run into any problems after removing them, try adding them back in.

<httpmodules>
      <remove name="WindowsAuthentication"></remove>
      <remove name="PassportAuthentication"></remove>
      <remove name="Profile"></remove>
      <remove name="AnonymousIdentification"></remove>
</httpmodules>

Flush your HTML as soon as it is generated

<pages buffer="true" enableviewstate="false"></pages>

Turn off Tracing

<configuration>
     <system.web>
          <trace enabled="false"></trace>
     </system.web>
</configuration>

Remove HTTP Headers

This is more of a security thing

<system.web>
    <httpruntime enableversionheader="false"></httpruntime>
</system.web>

<httpprotocol>
 <customheaders>
  <remove name="X-Powered-By"></remove>
 </customheaders>
</httpprotocol>

Uninstall the URL Rewrite module if not required

This saves CPU cycles used to check the server variable for each request.

Go to "Add or Remove Programs" and find "Microsoft URL Rewrite Module" and select uninstall.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in