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 4.5.2 Hosting with ASPHostPortal :: How to Publish and Deploy an ASP.NET Application in IIS

clock September 16, 2014 12:08 by author Kenny

Simple Way to Publish and Deploy an ASP.NET Application in IIS

ASP.NET is an open source server-side Web application framework designed for Web development to produce dynamic Web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. While Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family. IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

In this post, we will describe you how to publish and deploy your ASP.NET application in IIS. Actually it is so simple thing, you can publish your web application to the File System and copy paste all the files to your server. After that, you can add a new website from IIS. If you are not sure what files you should include, it's better to choose 'All files in the project' from the Package/Publish Web. Otherwise choose 'Only files needed to run this application'. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

You can add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder

Best and Cheap ASP.NET Hosting

Are you looking for best and cheap ASP.NET Hosting? Look no further, ASPHostPortal.com is your ASP.NET hosting home! Start your ASP.NET hosting with only $1.00/month. All of our .NET hosting plan comes with 30 days money back guarantee, so you can try our service with no risk. Why wait longer?



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: Token Based Authentication using ASP.NET Web API 2, Owin, and Identity.

clock July 22, 2014 09:26 by author Kenny

In this article, we are going to explain about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. As you know that a token is a piece of data created by server, and contains information to identify a particular user and token validity. The token will contain the user's information, as well as a special token code that user can pass to the server with every method that supports authentication, instead of passing a username and password directly.

What is Token Based Authentication?

Token-based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server. An authentication is successful if a user can prove to a server that he or she is a valid user by passing a security token. The service validates the security token and processes the user request. After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

What is ASP.NET Web API 2, Owin, and Identity?

This article is about Token Based Authentication using ASP.NET Web API 2, Owin, and Identity. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. ASP.NET Identity is the reworked, flexible replacement for the old membership system that has been around since ASP.NET 2.0. ASP.NET Identity is more well designed and flexible than the old membership system and uses Owin middleware components for external logins such as Facebook, Google and Twitter.

Building the Back-End API

Step 1: Creating the Web API Project

Now create an empty solution and name it “AngularJSAuthentication” then add new ASP.NET Web application named “AngularJSAuthentication.API”, the selected template for project will be as the image below. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Step 2: Installing the needed NuGet Packages:

Now we need to install the NuGet packages which are needed to setup our Owin server and configure ASP.NET Web API to be hosted within an Owin server, so open NuGet Package Manger Console and type the below:

Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.1.2

Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0

The  package “Microsoft.Owin.Host.SystemWeb” is used to enable our Owin server to run our API on IIS using ASP.NET request pipeline as eventually we’ll host this API on Microsoft Azure Websites which uses IIS.

Step 3: Add Owin “Startup” Class

Right click on your project then add new class named “Startup”. We’ll visit this class many times and modify it, for now it will contain the code below:
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

[assembly: OwinStartup(typeof(AngularJSAuthentication.API.Startup))]

namespace AngularJSAuthentication.API

{

    public class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.UseWebApi(config);

        }

    }

}

What we’ve implemented above is simple, this class will be fired once our server starts, notice the “assembly” attribute which states which class to fire on start-up. The “Configuration” method accepts parameter of type “IAppBuilder” this parameter will be supplied by the host at run-time. This “app” parameter is an interface which will be used to compose the application for our Owin server.

The “HttpConfiguration” object is used to configure API routes, so we’ll pass this object to method “Register” in “WebApiConfig” class.

Lastly, we’ll pass the “config” object to the extension method “UseWebApi” which will be responsible to wire up ASP.NET Web API to our Owin server pipeline.

Usually the class “WebApiConfig” exists with the templates we’ve selected, if it doesn’t exist then add it under the folder “App_Start”. Below is the code inside it:

    public static class WebApiConfig
    {
       public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

           var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
}

Step 4: Delete Global.asax Class

No need to use this class and fire up the Application_Start event after we’ve configured our “Startup” class so feel free to delete it.

Step 5: Add the ASP.NET Identity System

After we’ve configured the Web API, it is time to add the needed NuGet packages to add support for registering and validating user credentials, so open package manager console and add the below NuGet packages:

Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1

Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.0.1

The first package will add support for ASP.NET Identity Owin, and the second package will add support for using ASP.NET Identity with Entity Framework so we can save users to SQL Server database.

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “AuthContext” then paste the code snippet below:

public class AuthContext : IdentityDbContext<IdentityUser>
    {
        public AuthContext()
            : base("AuthContext")
            }

As you can see this class inherits from “IdentityDbContext” class, you can think about this class as special version of the traditional “DbContext” Class, it will provide all of the Entity Framework code-first mapping and DbSet properties needed to manage the identity tables in SQL Server.

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so add new class named “AuthRepository” and paste the code snippet below:

    public class AuthRepository : IDisposable
    {
        private AuthContext _ctx;

        private UserManager<IdentityUser> _userManager;
        public AuthRepository()
        {
            _ctx = new AuthContext();
            _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
        }

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
          IdentityUser user = new IdentityUser
            {            UserName = userModel.UserName
            };
            var result = await _userManager.CreateAsync(user, userModel.Password);
            return result;
        }
        public async Task<IdentityUser> FindUser(string userName, string password)
        {
        IdentityUser user = await _userManager.FindAsync(userName, password);
            return user;
        }
        public void Dispose()
        {
            _ctx.Dispose();
            _userManager.Dispose();
        }
}

Step 7: Add our “Account” Controller

Now it is the time to add our first Web API controller which will be used to register new users, so under file “Controllers” add Empty Web API 2 Controller named “AccountController” and paste the code below:

[RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
          private AuthRepository _repo = null;
          public AccountController()
        {
           _repo = new AuthRepository();
        }
        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
         if (!ModelState.IsValid)
            {
              return BadRequest(ModelState);
            }
            IdentityResult result = await _repo.RegisterUser(userModel);
            IHttpActionResult errorResult = GetErrorResult(result);
            if (errorResult != null)
            {
              return errorResult;
            }
              return Ok();
        }
        protected override void Dispose(bool disposing)
        {
           if (disposing)
            {
              _repo.Dispose();
            }
            base.Dispose(disposing);
        }
        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
          if (result == null)
            {
             return InternalServerError();
            }
            if (!result.Succeeded)
            {
              if (result.Errors != null)
                {
                  foreach (string error in result.Errors)
                    {
                     ModelState.AddModelError("", error);
                    }
                }
                if (ModelState.IsValid)
                {
                // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }
                return BadRequest(ModelState);
            }
            return null;
        }
}

Step 8: Add Secured Orders Controller

Now we want to add another controller to serve our Orders, we’ll assume that this controller will return orders only for Authenticated users, to keep things simple we’ll return static data. So add new controller named “OrdersController” under “Controllers” folder and paste the code below:

[RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
     [Authorize]
        [Route("")]
        public IHttpActionResult Get()
        {
         return Ok(Order.CreateOrders());
        }
    }
    #region Helpers
    public class Order
    {
   public int OrderID
     {
      get;
      set;
     }
        public string CustomerName
         {
           get;
           set;
         }
        public string ShipperCity
        {
          get;
          set;
      }
        public Boolean IsShipped
       {   
         get;
         set;
      }
        public static List<Order> CreateOrders()
        {
         List<Order> OrderList = new List<Order>
            {
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };
            return OrderList;
        }
   }
    #endregion

Step 9: Add support for OAuth Bearer Tokens Generation

Till this moment we didn’t configure our API to use OAuth authentication workflow, to do so open package manager console and install the following NuGet package:

Install-Package Microsoft.Owin.Security.OAuth -Version 2.1.0

After you install this package open file “Startup” again and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implemntation for this method as below:

public class Startup
    {
    public void Configuration(IAppBuilder app)
        {
          ConfigureOAuth(app);
                    //Rest of code is here;
        }
        public void ConfigureOAuth(IAppBuilder app)
        {
          OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }}

Step 10: Implement the “SimpleAuthorizationServerProvider” class

Add new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
      public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
  context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
       {
   context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            using (AuthRepository _repo = new AuthRepository())
            {
   IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
                if (user == null)
                {context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
         }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
            context.Validated(identity);
        }
    }

Step 11: Allow CORS for ASP.NET Web API

First of all we need to install the following NuGet package manger, so open package manager console and type:

Install-Package Microsoft.Owin.Cors -Version 2.1.0

Now open class “Startup” again and add the highlighted line of code (line 8) to the method “Configuration” as the below:

public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureOAuth(app);
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);        }

Step 12: Testing the Back-end API

Assuming that you registered the username “Taiseer” with password “SuperPass” in the step below, we’ll use the same username to generate token, so to test this out open your favorite REST client application in order to issue HTTP requests to generate token for user “Taiseer”. For me I’ll be using PostMan.



ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: SEO Tips for Your ASP.NET Site

clock June 16, 2014 06:43 by author Kenny

In this article I will give you SEO tips for your ASP.NET site. Search Engine Optimization is the process of improving the visibility of a website on organic ("natural" or un-paid) search engine result pages (SERPs), by incorporating search engine friendly elements into a website. SEO helps to ensure that a site is accessible to a search engine and improves the chances that the site will be found by the search engine.

ASP.NET (originally called ASP+) is the next generation of Microsoft's Active Server Page (ASP), a feature of their Internet Information Server (IIS). The latest version of ASP.NET is ASP.NET 4.5.2. Well, here are 10 tips on SEO for your ASP.NET website.

1. PAGE TITLE

Every page in your website should have a unique and descriptive page title that can describe what the page offers. You can set the Page Title either declaratively or in the code behind file.
This is very easy to achieve, and has a big influence on your site's ranking: don't use static titles. The <title> tag is one of the best ways to optimize a site for a special topic or keyword. Don't use a dozen keywords in the title tag, because you're "paying in" for each and every keyword - "paying in" means, that the weight of your site gets divided for all the keywords mentioned in the title tag. Choose one or two keywords, or a keyword-combination, to achieve relevance and a good ranking.

2. HYPERLINK

Make sure all your links in your page are hyperlinks. Search engines can crawl a page only if it is linked through a hyper link (anchor tag). JavaScript navigations are not search engine friendly since search engines will not understand it.

3. META KEYWORD AND META DESCRIPTION

Add Meta keyword and Meta description tag with relevant contents. Search engines will use these tags to understand what the page offers.

4.  DESCRIPTIVE URL

Make your website URL descriptive. URL’s that has lots of query string values, numeric ids are not descriptive. It will provide enough information what the page offers. For example, http://asphostportal.com/products.aspx?plan=B11E9918-BEC3-4DAA-A54B-0EC7E8742D9E is not descriptive as http://asphostportal.com/Windows-Shared-Hosting-Plans

5. ALT FOR IMAGES, TITLE FOR ANCHOR

Add ALT text for images and Title for hyperlinks. The ALT text will be displayed when the browser cannot display the image for some reasons. Search engines will not be able to read the image and ALT text will give some hint about the image which the search engine can use.

6.  DESIGN YOUR PAGE LIGHTER

Try to design your page with very less media contents like images, flash objects, Silverlight objects, ActiveX objects, etc. Search engines can only read HTML contents. A page that is entirely build on flash or Silverlight are not search engine friendly since the search engine robots cannot find any textual contents in those pages.

7. HEADER TAGS

Use Header tags (H1, H2, H3, H4, H5 and H6) wherever appropriate instead of styling the text in SPAN tags. These Header tags are search engine friendly. You can use this tag efficiently to organize your page headings and sub headings.
For example, you can put your page top most heading in H1, sub heading in H2, sub-sub heading in H3, etc that represents a proper hierarchy of your page contents.

8. LIMIT THE NUMBER OF LINKS PER PAGE

Previously there was a limit in number of links (100 links per page) the Google search engine will index on a page. This restriction is now no more. But it is still advisable to have limited number of links in your pages to avoid any adverse effect on your site rank.  This is to prevent link spamming and to preserve the page rank.

9. BUILD SITEMAP

Always have a sitemap file that can guide users and search engines to navigate your site pages easily. It is really necessary to have 2 site maps for a site, an xml sitemap file used by the search engines and an html sitemap file for the website users. You can submit your xml sitemap or RSS feed to Google Webmaster tools.

10.  MAKE SEO FRIENDLY PAGERS

Always construct search engine friendly pager links when displaying list of items in a summary page. For example, product list, article list page, etc. A link is called search engine friendly if it is anchor tag (<A>) that has a reachable url in its href property through GET request.



ASP.NET 4.5.2 Hosting in Saudi Arabia with ASPHostPortal.com :: What’s New in ASP.NET 4.5.2? – QueueBackgroundWorkItem

clock June 9, 2014 11:56 by author Kenny

ASP.NET is built on the .NET framework, which provides an application program interface (API) for software programmers. The .NET development tools can be used to create applications for both the Windows operating system and the Web. You've probably heard the word ASP.net fairly often these days, especially on developer sites and news. This article will explain what the fuss is all about. ASP.NET is not just the next version of ASP; it is the next era of web development. ASP.NET allows you to use a full featured programming language such as C# (pronounced C-Sharp) or VB.NET to build web applications easily.

New version of ASP.NET, .Net 4.5.2 was released on May 5th. Starting with the recently released version 4.5.2 of the .NET Framework, ASP.NET now supports the HostingEnvironment.QueueBackgroundWorkItem which lets you queue background threads from within an ASP.Net web application.

Well, the new HostingEnvironment.QueueBackgroundWorkItem method that lets you schedule small background work items. ASP.NET tracks these items and prevents IIS from abruptly terminating the worker process until all background work items have completed. These will enable ASP.NET applications to reliably schedule Async work items.

Remember that the QueueBackgroundWorkItem can only be called inside an ASP.NET managed app domain. It won't work if the runtime host is either Internet Explorer or some Windows shell. This is useful for long running tasks that don’t need to complete before returning a response to the user.

 using System;
 using System.Diagnostics;
 using System.Threading;
 using System.Threading.Tasks;
 using System.Web.Hosting;
 using System.Web.Mvc; 
 
 namespace QueueBackgroundWorkItem.Controllers
 {
     public class HomeController : Controller
     {
         // notice that the action did need to be declared async
         public ActionResult Index()
         {
             Func<CancellationToken, Task> workItem = DelayWrite;
             HostingEnvironment.QueueBackgroundWorkItem(workItem);
              // the view is returned before the work item is complete
            return View();
         } 
         // Background work items should use async/await to avoid tying up IIS threads
         // the runtime will provide the cancellation token
         private async Task DelayWrite(CancellationToken cancellationToken)
         {
             // perform a long running operation, e.g. network service call, computation, file IO
             await Task.Delay(5000);
             Trace.WriteLine("Executed from a background work item");         
         }  
     }
 }


ASP.NET 4.5.2 Hosting with ASPHostPortal.com :: New Features of ASP.NET 4.5.2 - Event Tracing Changes

clock June 5, 2014 06:36 by author Kenny

ASP.NET 4.5.2 is the latest ASP.NET version; it is a highly compatible, in-place update to the .NET Framework 4, 4.5 and 4.5.1. The new ASP.NET 4.5.2 some new features that very useful for ASP.NET developer. What's new in this release of .NET 4.5.2 Framework?

  • New APIs for ASP.NET apps;
  • Resizing in Windows Forms controls;
  • New workflow features;
  • Profiling improvements;
  • Debugging improvements;
  • Event tracing changes.

Well, now I will be talking about one of them. It is about “Event tracing”. As you know that Event Tracing for Windows or ETW is an efficient kernel-level tracing facility that lets you log kernel or application-defined events to a log file. It makes you can consume the events in real time or from a log file and use them to debug an application or to determine where performance issues are occurring in the application.

And not only that, ETW has more function again. ETW lets you enable or disable event tracing dynamically, allowing you to perform detailed tracing in a production environment without requiring computer or application restarts. Use ETW when you want to instrument your application, log user or kernel events to a log file, and consume events from a log file or in real time.

In the new ASP.NET 4.5.2 Event Tracing has great change. The new .NET Framework 4.5.2 enables out-of-process, Event Tracing for Windows based activity tracing for a larger surface area. Not only that, this enables Advanced Power Management (APM) vendors to provide lightweight tools that accurately track the costs of individual requests and activities that cross threads. These events are raised only when ETW controllers enable them; therefore, the changes don’t affect previously written ETW code or code that runs with ETW disabled.

Are you interest with other new features in ASP.NET 4.5.2? So just stay tune in this blog. We will always give you up to date news about ASP.NET.



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