ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Core 1.0 Hosting - ASPHostPortal :: Publish Your First ASP.NET Core Project

clock October 7, 2016 20:37 by author Jervis

Here are simple tutorial how to build your ASP.NET Core application. It’s just simple steps and you can follow it easily.

Install .NET Core First

First, please make sure you install .NET Core SDK for Windows

With that installed, it’s time to build your first application.

Open up a command prompt (or use the in-built terminal in Visual Studio Code) and start by creating a folder for your application, then initialising it.

mkdir CoreApp
cd CoreApp
dotnet new

When you run the dotnet command for the first time you’ll see some information about how .NET Core collects usage data and initially populates a local package cache. Once you’ve seen this message you won’t see it again on the same machine.

Project.json and Program.cs File

One of the most striking things about getting started with .NET Core is that you don’t end up with lots of files and dependencies right out of the gate, just the minimum you need for an empty web site.

In fact, all you’ll be left with is a project.json and Program.cs file.

At this point, this is just a .net Core app (not web) which prints “Hello World” to the console.

If you take a look at project.json you’ll see the minimum dependencies your new .net core app needs to run.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

When you create a new .net core application like this, it’s dependencies are not downloaded automatically. To do that, you simply need to issue a new command to restore the dependencies and then to run the app.

dotnet restore
dotnet run

Launch the Application

So your app just compiled and launched. It looks suspiciously like a console application, because it is a console application.

Up until now, everything you’ve done has resulted in a minimal .net core console application.

So how do you turn it into a web site?

Well you need to update project.json to tell it to add the Kestrel HTTP server as a dependency.

Kestrel is a lightning fast cross-platform web server which can be used to self-host your web application. In other words, you can tell your new web app that Kestrel is a dependency and then run your site on it without relying on IIS or IIS Express.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  }
}

You’ve added a dependency so now you need to download that dependency using the restore command.

dotnet restore

Incidentally, in case you’re wondering where donet restore is restoring packages to, the default location is %userprofile%\.nuget\packages

Next up, you’ll need to create a Startup.cs file. This will define how incoming web requests should be handled.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http; 

namespace ConsoleApplication {
    public class Startup{
        public void Configure(IApplicationBuilder app){
            app.Run(context => {
                return context.Response.WriteAsync("Hello world");
            });
        }
    }
}

This is about as simple as it comes, you simply tell your app to always return a response and write the text “Hello world” to it (for any request to your web application).

At this point, you haven’t told your app to start Kestrel (to start accepting web requests). You can do that by updating Program.cs.

using System;
using Microsoft.AspNetCore.Hosting; 

namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!"); 

            var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build(); 

            host.Run();
        }
    }
}

Should you wish, you can happily delete Console.WriteLine("Hello World!") as you’ve replaced it with something far more useful, you’ve told Core to launch Kestrel using the Startup class you just created.

Go ahead and run your app.

dotnet run

You’ll see a message telling you that your app is up and running and where you can access it.

Hosting environment: Development
Content root path: C:\Users\Jervis\CoreApp\bin\Debug\netcoreapp1.0
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

Hit http://localhost:5000 in a browser!

 



ASP.NET Hosting Tips - ASPHostPortal :: Simple Steps to Enable SSL in Visual Studio

clock January 15, 2016 20:14 by author Jervis

Hi… Happy New Year for you all. It’s long holiday and this is time to write new tips to open this year. This is only simple tutorial how to setup SSL for your ASP.NET project in Visual Studio.

You have your own ASP.NET project now and you want to run it on SSL. So, how to make it works?

The first step is easy. You just select the MVC/Web API project name in the solution and locate the property called “SSL Enabled” in properties window:

The same properties window will also show the HTTPS url for the application. In the above example it’shttps://localhost:44300/. Copy that URL and go to the project properties window. Locate the Web tab and override the Project Url property with the https address:

Start the application. You’ll likely get a message in the browser saying that the localhost address is not trusted, you can continue to the website at your own risk as you can see on figure below:

The problem is that the certificate that was installed automatically for you by Visual Studio is not trusted. You can locate the certificate in the Personal folder of the computer-level certificates in the certificates snap-in:

If you double-click the certificate you’ll see that it’s not trusted:

The message also provides the solution: the certificate must be imported into the trusted root certification authorities folder. You’ll see that as a folder in the same snap-in just below “Personal”. So how can we do that?

Right-click the certificate, then select All Tasks, Export… from the context menu. Click Next on the certificate export wizard. Leave the “Do not export the private key” option untouched, click Next. Accept the default on the next screen, i.e. “DER encoded binary X.509” should stay selected, then click Next. Then you’ll need to provide a name and a location for the exported file. Call it “localhost” and save it in a location where you can easily find it. Click Next and the Finish. There should be a popup message saying that the export was successful.

Next right-click the folder called Trusted Root Certification Authorities and select All Tasks, Import… from the context menu. Leave the “Local Machine” option untouched in the certificate import wizard, click Next. Browse to the certificate you saved just before. Click Next and accept all the default values along the way until you reach the end of the wizard. There should be a message saying that the import was successful.

If you now go back to the Personal store and double-click the localhost certificate then you should see that it’s trusted:

 

OK, let’s start the .NET web project again, the opening page should open without any warning. If you still see the same issue then test it a brand new browser session, e.g. here in IE:

It’s easy, right?



ASP.NET 4.5 Hosting - ASPHostPortal :: Timeout in Regular Expressions ASP.NET 4.5

clock December 10, 2015 21:07 by author Jervis

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems.

Lets start by the new Regex Api introduced with the framework. The improvement that has been made is minor yet handy at certain cases. The Regex class of .NET 4.5 supports Timeout. Lets take a look how to work with it.

Lets try to write a simplest RegEx validator to look into it. 

Try
{
    Regex regexpr =
new Regex("[A-Z ]{10}", RegexOptions.Singleline, TimeSpan.FromMilliseconds(1));
    Match mch = regexpr.Match(
"ABHISHEK SUR");
   
if (mch.Success)
        Console.WriteLine(
"Match found");
   
else
        Console.WriteLine(
"Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine(
"Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(
true);
}

Here in the code you can see I simply check a string with a Regular expression. It eventually finds success as Pattern matches the string. Now this code is little different than what we have been doing for last few years. The constructor overload of Regex now supports a Timespan seed, which indicates the timeout value after which the Regular expression validator would automatically generate a RegexMatchTimeoutException. The Match defined within the Regex class can generate timeout after a certain time exceeds.

 You can specify Regex.InfiniteMatchTimeout to specify that the timeout does not occur. The value of InfiniteMatchTimeout is -1ms internally and you can also use Timespan.Frommilliseconds(-1) as value for timespan which will indicate that the Regular expression will never timeout which being the default behavior of our normal Regex class. Regex also supports AppDomain to get default value of the Timeout. You can set timeout value for "REGEX_DEFAULT_MATCH_TIMEOUT" in AppDomain to set it all the way through the Regular expressions being used in the same AppDomain. Lets take a look how it works.

Try
{
    AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(2));

    Regex regexpr = new Regex("[A-Z ]{10}", RegexOptions.Singleline);
    Match mch = regexpr.Match("ABHISHEK SUR");
    if (mch.Success)
        Console.WriteLine("Match found");
    else
        Console.WriteLine("Not matched");

}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine("Regex Timeout for {1} after {2} elapsed. Tried pattern {0}", ex.Pattern, ex.Message, ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.ToString());
}
finally
{
    Console.ReadKey(true);
}

Now this works exactly the same as the previous one. Here the Regex constructor automatically checks the AppDomain value and applies it as default. If it is not present, it will take -1 as default which is Infinite TImeout and also if explicitely timeout is specified after the default value from AppDomain, the Regex class is smart enough to use the explicitly set value only to itself for which it is specified. The Regex Constructor generates a TypeInitializationException if appdomain value of Timespan is invalid. Lets check the internal structure.

This is the actual code that runs in background and generates the timeouts. In fact while scanning the string with the pattern, there is a call to CheckTimeout which checks whether the time specified is elapsed for the object. The CheckTimeout throws the exception from itself.

The Constructor sets DefaultMatchTimeout when the object is created taking it from AppDomain data elements.

If you read MSDN thoroughly, it suggests to use Timeouts when specifying the Regular expressions. If the pattern is supplied from external or you are not sure about the pattern that needs to be applied to the string, it is always recommended to use Timeouts. Basically you should also specify a rational limit of AppDomain regex default to ensure no regular expression can ever hang your application.

This is a small tip on the new Regex enhancements introduced with .NET 4.5 recently.  

 



ASP.NET Hosting Tips - ASPHostPortal :: SQLParameters in ASP.NET C#

clock November 16, 2015 22:10 by author Jervis

SqlParameter represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. Parameter names are not case sensitive. 

To initialize a new instance of SqlParameter class, we can use many constructors such as SqlParameter(), SqlParameter(String, SqlDbType), SqlParameter(String, Object), SqlParameter(String, SqlDbType, Int32), SqlParameter(String, SqlDbType, Int32, String). 

SqlParameter() constructor initialize a new instance of SqlParameter class. Sqlparameter(String, SqlDbType) constructor require parameter name and data type. SqlParameter(String, Object) constructor require parameter name and a value of the new SqlParameter. SqlParameter(String, SqlDbtype, Int32) constructor require parameter name, SqlDbType and size. SqlParameter(String, SqlDbtype, Int32, String) constructor require parameter name , SqlDbType, size and the source column name. 

SqlParameter class have many useful properties such as CompareInfo, DbType, Direction, IsNullable, Offset, ParameterName, Precision, Scale, Size, SourceColumn, SqlDbType, SqlValue, TypeName, Value, XmlSchemaCollectionName etc. 

ParameterName property get or set the SqlParameter name. SqlDbType property get or set the SqlDbType (SQL Server specific data type) for the parameter. SqlDbType enumeration values are BigInt, Binary, Bit, Char, Date, DateTime, Decimal, Float, Image, Int, Money, Real, Text, Time, Timestamp etc. SqlParameter Size property get or set the maximum size in bytes of the data within the column. Direction property get or set a value that indicate whether the parameter is input only, output only, bidirectional or a stored procedure return value parameter. Value property get or set the value of parameter. 

The following c# example source code describe you more about SqlParameter in ASP.NET. 

Create a web form name SqlParameterExample.aspx. Now add a GridView control. We populate the GridView control with SqlDataSource Data. But here we filter the data by SqlParameter. In this example we select the NorthWind database Products table data and filter it with SqlParameter product name. The source code of SqlParameterExample.aspx is here.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>

<!DOCTYPE html>

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e) {
        if (!Page.IsPostBack) {
            SqlConnection MyConnection;
            SqlCommand MyCommand;
            SqlDataReader MyReader;
            SqlParameter ProductNameParam;

            MyConnection = new SqlConnection();
            MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;

            MyCommand = new SqlCommand();
            MyCommand.CommandText = "SELECT * FROM PRODUCTS WHERE PRODUCTNAME = @PRODUCTNAME";
            MyCommand.CommandType = CommandType.Text;
            MyCommand.Connection = MyConnection;

            ProductNameParam = new SqlParameter();
            ProductNameParam.ParameterName = "@PRODUCTNAME";
            ProductNameParam.SqlDbType = SqlDbType.VarChar;
            ProductNameParam.Size = 25;
            ProductNameParam.Direction = ParameterDirection.Input;
            ProductNameParam.Value = "CHAI";

            MyCommand.Parameters.Add(ProductNameParam);

            MyCommand.Connection.Open();
            MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

            GridView1.DataSource = MyReader;
            GridView1.DataBind();

            MyCommand.Dispose();
            MyConnection.Dispose();
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SqlParameter example: how to use SqlParameter in asp.net</title>
</head>
<body>
   
<form id="form1" runat="server">
   
<div>
       
<asp:GridView ID="GridView1" runat="server">
       
</asp:GridView>
   
</div>
   
</form>
</body>
</html>

 



ASP.NET 4.6 Hosting - ASPHostPortal :: How to Upgrade to ASP.NET 4.6 Projects?

clock November 9, 2015 21:59 by author Jervis

The updates in the .NET Framework provide many improvements, including support for new language features in c#, garbage collection, enhancements in cryptography support, feature toggles, new classes in the BCL and others. The RyuJIT compiler adds significant performance gains for 64bit applications, even those not originally targeting the 4.6, improves startup times and can reduce the memory footprint of your application.

While the explicit modification of your projects may not be required to gain some of the 4.6 benefits, there may be other organizational factors that lead you down that path. We’ll work through the mechanics of the upgrade to 4.6 in this post.

Upgrading Your ASP.NET Projects

Every project we create references a specific version of the .NET Framework. This has been true throughout the history of .NET, and though the way we will do it in the future will change with the new project system, the premise remains the same.

For now, you can simply open the properties tab for your project and change the target Framework.

You will be prompted to let you know that some changes may be required.

Now, if you were to try to build the Bootcamp project when you’re only partway through the upgrade, you’d see something similar to the following:

With a message that reads:

“The primary reference “x” could not be resolved because it was built against the “.NETFramework,Version=v4.6” framework. The is a higher version than the currently targeted framework “.NETFramework,Version=4.5.1”.”

You may run into this in other scenarios, as well, especially if you you have references to packages or libraries that get out of sync in your upgrade process. A project that takes on dependencies must be at (or higher than) the target framework of the compiled dependencies. To remedy this, we simply need to complete the upgrade process on the rest of the projects.

Why Upgrade?

Moving from 4.5.x to 4.6 is not a required step in our conversion to an MVC 6 project. In fact, MVC 6 indeed runs on a different framework altogether. To that end, any environment where you have 4.6 installed will “pull up” other assemblies because it is a drop-in replacement for pervious versions.

Perhaps your primary motivator to move to 4.6 is the perf bump in the runtime, or it might be the new language features (which only require a framework install, not a version bump in your target). But it also ensures we’re compatible with other projects in our organization, particularly when we consider the default target for new projects in VS 2015 is against 4.6. If we want to leverage these from other projects in our organization, we want to make sure that we’re not the lowest common denominator in the mix.



ASP.NET Hosting with ASPHostPortal :: Identity Impersonation with IIS and ASP.NET

clock August 12, 2015 08:50 by author Jervis

ASP.NET applications running on IIS7 and IIS8 use the NETWORK SERVICE account by default to access resources on the computer.  This post explains how to enable impersonation to have ASP.NET use a different account.

IIS7

When an anonymous request arrives (ie not using Windows Authentication), IIS will by default tag the request as coming from the built in account IUSR.  This behaviour is defined in applicationHost.config:

<anonymousAuthentication enabled="true" userName="IUSR" />

IIS then passes the request to ASP.NET where Forms Authentication can be used to independently authenticate the user (note that IIS can still use "anonymous" authentication, even though ASP.NET later applies Forms Authentication).

ASP.NET itself then makes requests for system resources using the NETWORK SERVICE account, by default.  The account used is determined by the Application Pool that the web site belongs to, where all application pools are initially configured to use NETWORK SERVICE as determined in applicationHost.config:

<applicationPoolDefaults>
    <processModel identityType="NetworkService" />
</applicationPoolDefaults>

If we want ASP.NET to use a different account instead of NETWORK SERVICE, we can tell it to use impersonation by adding the following to the web application's web.config:

<system.web>
    <identity impersonate="true" />

In our scenario, this will then impersonate the account IUSR, since this is the identity IIS provided for the request.

If IIS was using Windows Authentication (instead of anonymous authentication) then this would allow us to make resource requests from ASP.NET while impersonating the Windows identity of whoever was logged on.  This might be necessary to give access to specific resources restricted to that user.

Alternatively, regardless of what mode of authentication IIS was using, we could provide a valid Windows identity to be used for all requests, by adding the following to web.config:

<system.web>
    <identity impersonate="true" userName="DOMAIN\UserName" password="Password" />

IIS Config File

The Internet Information Services Manager lets you configure IIS, but the configuration is ultimately stored in the file:

%windir%\system32\inetsrv\config\applicationHost.config



ASP.NET SignalR Hosting - ASPHostPortal.com :: How to Send Notification using ASP.NET SignalR

clock September 4, 2014 12:00 by author Jervis

What is SignalR?

ASP.NET SignalR is a library for developing applications needing real-time communication. In such applications as soon as data is generated on the server or some interesting event happens on the server the client needs to be updated with the latest data. The traditional approach to achieve this functionality is to make Ajax calls to the server periodically. However, this approach has its own pitfalls. Another way is to use HTML5 Web Sockets or Server Sent Events (SSE) to perform real-time communication. However, both of these techniques work only on the browsers supporting HTML5. SignalR uses HTML5 Web Sockets if the target browser supports them, otherwise it falls back to other techniques. The best part is that - as a developer you need not know these internal implementation details. Additionally, SignalR makes connection management, grouping and authorization easy. You can work with the high level API exposed by SignalR in your web applications without worrying too much about the internals of the communication technique used.

You can use SignalR in variety of situations, some of them are listed below:

  • Chat applications where two or more end users chat with each other in real-time.
  • Broadcasting notifications or messages to all or selected clients.
  • Real-time gaming applications.
  • Social networking websites.
  • Discussion boards where admins or members can communicate to other admins or members.

Example

To illustrate how SignalR can be used in an ASP.NET application you will develop a web form application as shown below:

The web application consists of two simple web forms, viz. AdminForm.aspx and ClientForm.aspx. The former web form is supposed to be used by an administrator to send notifications to all the clients connected at a given point of time. The later web form displays the notifications sent from the administrator to the end user. The notifications are displayed in a balloon that disappears after 5 seconds.

Getting SignalR

In order to develop the above application you should first install the SignalR library. You can get SignalR in couple of ways. Firstly you can install it as a NuGet package. To do so, open Tools > Library Package Manager > Package Manager Console and then issue the following command:

install-package Microsoft.AspNet.SignalR

Not only easier, but the recommended way is to install Microsoft ASP.NET and Web Tools 2012.2. Doing so will add certain project item templates in the Add New Item dialog as shown below:

You can use these templates (more on that later) instead of manually creating the respective project items.

Developing the Admin Web Form

Now let's develop the admin web form first. Begin by creating a new blank ASP.NET web forms application. Then right click on the project in the Solution Explorer and select Add New Item. Then add a new SignalR Hub Class to the project. This creates a new class that inherits from Hub base class.

namespace SignalRDemo
{
    public class MyHub1 : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}

The Hub class resides in the Microsoft.AspNet.SignalR namespace. A hub class can have any number of developer defined methods. These methods can then be called from a client side script. SignalR hubs provide a higher level RPC framework for your application. Additionally, you will find certain script files under the Scripts folder.

In this example you need a method - SendNotifications() - inside the hub class as shown below:

public void SendNotifications(string message)
{
    Clients.All.receiveNotification(message);
}

As you can see, the SendNotifications() method accepts a string parameter. Inside, it uses the Clients.All property to access all of the clients currently connected with the server. The receiveNotification() is a client side callback function that you will write in your jQuery code later. This way a notification is broadcast to all the connected clients. How the clients make use of the message is governed by the receiveNotification() client side function.

Next, add a Global.asax file to your web application and write the following code in the Application_Start event handler.

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHubs();
}

The MapHubs() method registers default routes for SignalR hubs.

Now, add a web form to the project and name it as AdminForm.aspx. Add the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Admin Form Sending Notifications</title> 

    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script> 

    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            $("#button1").click(function () {
                proxy.server.sendNotifications($("#text1").val());
            });

            $.connection.hub.start();
        });
    </script> 

</head>
<body>
    <input id="text1" type="text" />
    <input id="button1" type="button" value="Send" />
</body>
</html>

The AdminForm.aspx refers SignalR script files in the head section. Notice the code marked in the bold letters. First a variable named proxy is declared to hold a reference to a proxy of the remote hub class (NotificationHub). Make sure that the client side code uses camel casing in naming conventions. For example, NotificationHub is referred as notificationHub in the client code.

Next, the click event handler of the button is wired to a function. The client event handler calls the sendNotifications() method on the proxy object and passes the notification message entered in the textbox (see earlier figure to know what the admin form looks like).

Finally, the start() method of the hub is called to start the connection.

Developing the Client Web Form

Now that you have completed AdminForm.aspx let's develop the client web form. Add another web form to the project and name it ClientForm.aspx. Key-in the following markup in the web form:

<!DOCTYPE html>
<html>
<head>
    <title>Client Form Receiving Notifications</title>
    <script src="/Scripts/jquery-1.8.2.min.js" ></script>
    <script src="/Scripts/jquery.signalR-1.0.0.js"></script>
    <script src="/signalr/hubs"></script>
    <script type="text/javascript">
        $(function () {
            var proxy = $.connection.notificationHub;

            proxy.client.receiveNotification = function (message) {
                $("#container").html(message);
                $("#container").slideDown(2000);
                setTimeout('$("#container").slideUp(2000);', 5000);
            };

            $.connection.hub.start();
        });
    </script>
</head>
<body>
    <div class="notificationBalloon" id="container">
    </div>
</body>
</html>

The client code also declares a variable to hold a reference to the proxy hub object. It then wires a callback function receiveNotification (recollect that you used this name in the server side NotificationHub class). The receiveNotification() function receives the notification message sent by the server and displays it to the user after animating it using slideDown() and slideUp() jQuery functions. The notification message is automatically discarded after 5 seconds using the setTimeout() JavaScript function.

Finally, a connection is started by calling the start() method on the hub.

That's it! Run the AdminForm.aspx and load ClientForm.aspx in two or three browser windows or tabs. Now enter some message in the textbox from AdminForm.aspx and click on the Send button. All the browser windows showing ClientForm.aspx should show the notification message.

Summary

SignalR is a library that allows ASP.NET applications to perform real-time communication. If the target browser supports HTML5 SignalR uses Web Sockets otherwise fallback techniques are used. Additionally, SignalR provides an easy way for connection management, connection grouping and security for the communication. This article demonstrated a basic use of SignalR to send notifications to all the connected clients in real-time.



ASP.NET MVC 5 Hosting - ASPHostPortal :: How to Perform Code First Migration in MVC 5

clock July 16, 2014 08:39 by author Jervis

In today post, I will explain Code Migration in MVC application. This migration helps you to update and change the data model that you’ve created for application and you don't need to re-create or drop your database.

 

How to Apply Code First Migration

The data model in the database usually changes after developing the new application. When the data model changes, it becomes out of sync with the database. We've configured our Entity Framework in the app to drop and recreate the data model automatically. When any type of change is done in the entity classes or in the DbContext class, the existing database is deleted and the new database is created that matches the model and sees it with test data.

When the application runs in production, we do not want to lose everything each time we make changes like adding a column. The Code First Migration solved this problem by enabling the code first to update the database instead of dropping or recreating.

The procedure is following:

1. Disable the Database Initializer in the Web.Config file.

The following is the example:

<!--<contexts>

      <context type="Vag_Infotech.DAL.CollegeDbContext, Vag_Infotech">
        <databaseInitializer type="Vag_Infotech.DAL.CollegeDatabaseInitializer, Vag_Infotech"></databaseInitializer>
      </context>
</contexts>--> 

And also you need to change your Global.asax file:

// Database.SetInitializer(new CollegeDatabaseInitializer()); 

2. Change your database name in your web.config file:

<connectionStrings
  <add name="CollegeDbContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=VInfotechNew;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</
connectionStrings> 

3. Open the Package Manager Console and enter this command:

enable-migration

add-migration InitialCreate 

Then, you will see the solution explorer below:

How to Edit Seed Method

Now, we add new code for updating our data model in this method. When we do not use the migration, the data model is dropped or re-created during the execution of the application each time, but now the data is retained after database changes.

Here are the steps to edit seed method:

1. Modify your configuration.cs file with this code:

namespace Vag_Infotech.Migrations
{
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using Vag_Infotech.Models;
 
    internal sealed class Configuration : DbMigrationsConfiguration<Vag_Infotech.DAL.CollegeDbContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
 
        protected override void Seed(Vag_Infotech.DAL.CollegeDbContext context)
        {
            var New_Students = new List<Student>
            {
                new Student{FirstName="Louis",LastName="Fordsen",
                    EnrollmentDate=DateTime.Parse("2009-07-01")},
                new Student{FirstName="David ",LastName="Roger",
                    EnrollmentDate=DateTime.Parse("2009-07-01")},
                new Student{FirstName="Mike",LastName="Upson",
                    EnrollmentDate=DateTime.Parse("2009-07-05")},
            };
            New_Students.ForEach(ns => context.Students.AddOrUpdate(p => p.LastName, ns));
            context.SaveChanges();
 
            var New_Courses = new List<Course>
            {
                new Course{CourseID=201,Name="MCA",Credit=3,},
                new Course{CourseID=202,Name="M.Sc.IT",Credit=2,},
                new Course{CourseID=203,Name="M.Tech.CS",Credit=2,},
                new Course{CourseID=204,Name="M.Tech.IT",Credit=4,}
            };
            New_Courses.ForEach(ns => context.Courses.AddOrUpdate(p => p.Name, ns));
            context.SaveChanges();
 
            var New_Enrollments = new List<Enrollment>
            {
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="Louis").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="MCA").CourseID,
                    Grade=StudentGrade.A
                },
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="David").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.IT").CourseID,
                    Grade=StudentGrade.B
                },
                new Enrollment{
                    StudentID= New_Students.Single(ns=>ns.FirstName=="Mike").ID,
                    CourseID=New_Courses.Single(nc=>nc.Name=="M.Tech.CS").CourseID,
                    Grade=StudentGrade.D
                },
            };
 
            foreach (Enrollment et in New_Enrollments)
            {
                var NewEnrollDb = context.Enrollments.Where(
                    ns => ns.Student.ID == et.StudentID &&
                        ns.Course.CourseID == et.CourseID).SingleOrDefault();
                if (NewEnrollDb == null)
                {
                    context.Enrollments.Add(et);
                }
            }
            context.SaveChanges();
        }
    }
}

In the code above the Seed() takes the context object as an input argument and in the code the object is used to add the entities to the database. We can see how the code creates the collection for the database for each entity type and then saves it by SaveChanges() and adds it through the DbSet property. It is not necessary to call the SaveChanges() after each group of entities.

2. Build the solution

How to Execute the Migration

Here are steps:

1. Enter this command on Package Manager Console:

Update-database

2. Run the application and you’ll see the change



ASPHostPortal.com Expand Further into Asia with New Data Center in Singapore

clock May 21, 2013 07:59 by author Jervis

ASPHostPortal.com is a premiere web hosting company that specialized in Windows and ASP.NET-based hosting, announces their global expansion into Asia with a new datacenter location in Singapore. Advanced Windows 2008/R2 hosting and SQL hosting are available in the new Singapore-based datacenter.

This Singapore Data Center is supported with Multiple connections to major Internet backbone carriers via SingTel, SingNet, NTT Communication, Deutsche Telekom AG, Hurricane Electric and PCCW with OC-12 connections using BGP-4 routing protocol. This Singapore Data centre hosting is suitable to anyone who plans to do an online business in Asia or it is suitable to those who are targetting Asian markets.

“We have a large Asia customer base and we wanted to address their concerns of website latency issues due to data transport over long distances,” said Dean Thomas, Manager at ASPHostPortal. “We are serious in global hosting business and this is why we provide options to our customers to select from our three data centres.”

“From now, customer can select the data center location where they desire to host their website as part of our online ordering process and after successful order submission, the website account will be instantly setup. And we did not leave out our existing customers; we have a team ready to assist in datacenter location migration," added Dean Thomas. “We are extremely proud with this new launch of Asia data center.”

ASPHostPortal.com Singapore Data centre hosting server supports the newest Intel Xeon Processor with a minimum 8 GB RAMs and 2000 Mbps connection line. All the latest ASP.NET Framework  and SQL 2012 hosting are ready on all the servers. This data centre is provided as an addition to our two existing data centres, i.e. Houston (US Data center) and Amsterdam (European Data center).

ASPHostPortal.com is one of the Microsoft recommended hosting partner (http://www.microsoft.com/web/hosting/HostingProvider/Details/962) that provide most stable and reliable web hosting platform. With this new data center, it will continue to keep ASPHostPortal.com as one of the front runners in the web hosting market.

About ASPHostPortal.com:

ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal.com strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



$50.00 Cheap and Reliable Windows Cloud Server with ASPHostPortal.com

clock May 6, 2013 11:49 by author Jervis

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for details. Now, ASPHostPortal.com proudly announces the most affordable, reliable and cheap Windows Cloud Server on our hosting environment.

 

Microsoft literally built in to Windows Server 2012 hundreds of enhancements and new features. Below are several points highlighted by Microsoft:

  1. Powerful. It delivers the power of many servers, with the simplicity of one. Windows Server 2012 offers you excellent economics by providing an integrated, highly available, and easy-to-manage multiple-server platform.
  2. Continuous availability. New and improved features offer cost-effective IT service with high levels of uptime. Servers are designed to endure failures without disrupting services to users.
  3. Open. Windows Server 2012 enables business-critical applications and enhances support for open standards, open source applications, and various development languages.
  4. Flexible. Windows Server 2012 enables symmetrical or hybrid applications across the data center and the cloud. You can build applications that use distributed and temporally decoupled components.

From just $50.00/month, you can get a dedicated cloud server with the following specifications:

- Windows 2008 R2 / Windows 2012 Standard Edition OS
- 1 Core Processor
- 1 GB RAM
- 100 GB SAN Storage
- 1000 GB Bandwidth
- 100 Mbps Connection Speed
- Full 24/7 RDP Access
- Full 24/7 Windows Firewall Protection
- Choice of United States, European (Amsterdam), and Asia (Singapore) Data Center

“As a leader in Windows Hosting, and having worked closely with Microsoft to reach this point, we’re moving forward with expectant anticipation for serving our loyal clients with Windows Cloud Server Solutions.” Said Dean Thomas, Manager at ASPHostPortal.com.

For more details, please visit http://www.asphostportal.com/Windows-Cloud-Server-Hosting-Plans.aspx.

About ASPHostPortal.com:


ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



Cheap ASP.NET 4.5 Hosting

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

Tag cloud

Sign in