ASP.NET 4.5 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.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.



ASPHostPortal Web Hosting Announces Release of New Free 7 Days ASP.NET MVC 5.2 Hosting

clock June 6, 2014 07:48 by author Ben

Windows and ASP.NET hosting specialist, ASPHostPortal.com, has announced the availability of new hosting plans that are optimized for the latest update of the ASP.NET MVC  technology. The ASP.NET MVC 5.2 Release Candidate is now available to developers for immediate download. ASP.NET MVC 5.2 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. This package contains the runtime assemblies for ASP.NET MVC. ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and that gives you full control over markup. ASP.NET MVC 5.2  brings bootstrap into the default MVC template, authentication filters, filter overrides and attribute routing.  Attribute Routing on ASP.NET MVC 5.2 now provides an extensibility point called IDirectRouteProvider, which allows full control over how attribute routes are discovered and configured.

ASPHostPortal.com - a cheap, constant uptime, excellent customer service, quality and also reliable hosting provider in advanced Windows and ASP NET technology. ASPHostPortal.com hosts its servers in top class data centers that is located in United States to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from ASPHostPortal.com include 24×7 support and 30 days money back guarantee.

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5.2 hosting services, we hope that developers and our existing clients can try this new features. Now, you don’t need to spend a lot of money to get ASP.NET MVC 5.2 hosting.”

For more information about new ASP.NET MVC 5.2, please visit http://asphostportal.com/ASPNET-MVC-52-Hosting.

As a leading hosting provider, ASPHostPortal.com offers a comprehensive range of services including domain name registrations, servers, online backup solutions and dedicated web hosting. ASPHostPortal.com is well placed to deliver a high quality service.

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.



ASP.NET MVC 5.1.2 Hosting with ASPHostPortal.com :: Loading a Knockoutjs Model from a ASP.NET MVC Controller Using AJAX

clock May 21, 2014 11:51 by author Kenny

Knockout.js is a javascript library that allows us to bind html elements against any data model. It provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM(UI) and any changes to the DOM are automatically reflected to the data model.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. The MVC model defines web applications with 3 logic layers: The business layer (Model logic),The display layer (View logic),The input control (Controller logic).

This article will demonstrate how to load a KnockoutJS view model from a C# controller using ajax in an ASP.NET MVC project. I’m just going to jump straight into the code for this sample.  To get started we need to create a new action in the controller.  For the purposes of this sample this action will return a randomly populated Person object (see the previous articles for the definition) so that we can see the content changing.  Here is the action:

public class SampleController : Controller
{
    public ActionResult AjaxModelLoading()
    {
        Person model = CreateRandomModel();
        if (Request.IsAjaxRequest())
        {
            return new JsonNetResult(model);
        }
        return View(model);
    } 
    private static Person CreateRandomModel()
    {
        Random random = new Random();
        string[] firstNames = { "Billy", "Kevin", "Michael", "Steve" };
        string[] lastNames = { "Jordan", "Smith", "Wild", "Walker" };
        string firstName = firstNames[random.Next(firstNames.Length)];
        string lastName = lastNames[random.Next(lastNames.Length)]; 
        return new Person
        {
            FirstName = firstName,
            LastName = lastName,
            EmailAddress = string.Format("{0}@{1}.com", firstName, lastName),
            PhoneNumber = random.Next(int.MaxValue).ToString("D10"),
            DateOfBirth = DateTime.Today.AddYears(random.Next(-50, -10))
        };
    }
}


This action creates the Person object and then detects if the HTTP request was made using ajax.  If it was then it serializes the model as JSON and if it is a standard HTTP request it returns the view.  This is a handy technique for implementing a simple refresh of data in the view without retrieving all the HTML from the server again.

On line 9 you can see that I have not used the standard ASP.NET JSON serializer.  Instead I went with my own ActionResult which makes use of JSON.NET to give myself more control over the generated JSON.  For reference the code for my JsonNetResult class is below:
public class JsonNetResult : ActionResult
{
  
    private const string ContentType = "application/json"; 
    private readonly object data;
    private readonly Formatting formatting;
    private readonly JsonSerializerSettings serializerSettings; 
    public JsonNetResult(object data)
    {
        this.data = data;
        formatting = Formatting.None;
        serializerSettings = new JsonSerializerSettings
       {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
    }
    public override void ExecuteResult(ControllerContext context)
    {
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = ContentType;
        if (data != null)
        {
            JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = formatting };
            JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
            serializer.Serialize(writer, data);
            writer.Flush();
       }
    } 
    public object Data
    {
        get { return data; }
    }
}


Next we need to create the KnockoutJS view model to bind to the view.
var AjaxModelLoading = function(url) {
    var self = this;
    self.isLoaded = ko.observable(false);
    self.isLoading = ko.observable(false); 
    self.getRandomModel = function () {
        self.isLoading(true);
        self.isLoaded(false);
 
        // Setting a timeout so the loading text is visible in the sample
        setTimeout(function() {
            $.ajax(url, {
                type: "GET",
                cache: false,
            }).done(function(data) {
                ko.mapping.fromJS(data, {}, self);
                self.isLoaded(true);
                self.isLoading(false);
            });
        }, 1000);
    };
};


This view model defines a function which will be used to handle a click event from the view in order to refresh the data. It also does some basic state management to determine if the content has been loaded or is in the process of loading.  I have put in a short delay between the click in the view and executing the ajax request in order to make the loading state management more apparent for the sample.

Lastly we need to create the view.
@model Quickstart.Web.Models.Person 
@section scripts
{
    <script type="text/javascript" src="/Scripts/ViewModels/AjaxModelLoading.js"></script>
    <script type="text/javascript">
        var viewModel = new AjaxModelLoading("@Url.Action("AjaxModelLoading")");
        ko.applyBindings(viewModel); 
        viewModel.getRandomModel();
    </script>
}
 
<h2>Ajax Model Loading Sample</h2>

<div data-bind="if: isLoading()">
    Loading...
</div>
 
<div data-bind="if: isLoaded()">
    <div>
        <label>First Name:</label>
        <input type="text" data-bind="value: firstName"/>
    </div>
 
    <div>
        <label>Last Name:</label>
        <input type="text" data-bind="value: lastName"/>
    </div>

    <div>
        <label>Email Address:</label>
        <input type="text" data-bind="value: emailAddress"/>
    </div>
 
    <div>
        <label>Phone Number:</label>
        <input type="text" data-bind="value: phoneNumber"/>
    </div>
 
    <div>
        <label>Date of Birth:</label>
        <input type="text" data-bind="value: dateOfBirth"/>
    </div>
</div>
<a href="#" data-bind="click: getRandomModel">Get random person</a>



ASP.NET MVC 5 Hosting - with ASPHostPortal.com :: How to Rendering ASP.NET MVC 1.0, 2.0 RC, 3 and 4 Razor Views to String

clock March 14, 2014 07:44 by author Diego

The ASP.NET MVC Razor implementation is closely tied to ASP.NET and MVC and the View template (WebViewPage class) includes a few MVC-specific features as well as back references to the controller. In other words MVC Razor is designed with MVC in mind. With Razor, you can create a custom Razor Engine that can be used in any .NET environment. Razor is the best view engine available for MVC as its much cleaner and easy to write and read. This view engine is compatible with unit testing frameworks. In this article, I will demonstrate how you can render ASP.NET MVC Razor Views in ASP.Net MVC 1.0, 2.0 RC, 3 and 4 .
Basically, all you do is create a fake HttpContext for the view to render itself.  This is an extensions method of the HtmlHelper that processes a partial view through the default MVC view engine and then renders it to the response stream.

Thisworks on ASP.NET MVC 1.0 (changing Headers on the original HttpResponse doesn't throwthe "Server cannot set content type after HTTP headers have been sent"exception).
/// <summary>Renders a view to string.</summary>
public static string RenderViewToString(this Controller controller, string viewName, object viewData) {


Create memory writer.

var sb = new StringBuilder();
var memWriter = new StringWriter(sb);


Create fake http context to render the view.

    var fakeResponse = new HttpResponse(memWriter);
    var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
    var fakeControllerContext = new ControllerContext(
        new HttpContextWrapper(fakeContext),
        controller.ControllerContext.RouteData,
        controller.ControllerContext.Controller);
    var oldContext = HttpContext.Current;
    HttpContext.Current = fakeContext;
  Use HtmlHelper to render partial view to fake context.
    var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), new ViewDataDictionary(), new TempDataDictionary()),
        new ViewPage());
    html.RenderPartial(viewName, viewData);
Restore context.
    HttpContext.Current = oldContext;  
    //Flush memory and return output
    memWriter.Flush();
    return sb.ToString();}
Fake IView implementation used to instantiate an HtmlHelper.
public class FakeView : IView {
    #region IView Members
    public void Render(ViewContext viewContext, System.IO.TextWriter writer) {
        throw new NotImplementedException();
    }    #endregion
}

In ASP.NET MVC 2.0 RC, the code changes a bit because we have to pass in the StringWriter used to write the view into the ViewContext:
Use HtmlHelper to render partial view to fake context.

//...
var html = new HtmlHelper(
    new ViewContext(fakeControllerContext, new FakeView(),
        new ViewDataDictionary(), new TempDataDictionary(), memWriter),
    new ViewPage());
html.RenderPartial(viewName, viewData);
//...

In MVC 3 you can used this code :
public static string RazorRender(Controller context, string DefaultAction)
{
string Cache = string.Empty;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.TextWriter tw = new System.IO.StringWriter(sb);
RazorView view_ = new RazorView(context.ControllerContext, DefaultAction, null, false, null);
view_.Render(new ViewContext(context.ControllerContext, view_, new ViewDataDictionary(), new TempDataDictionary(), tw), tw);
Cache = sb.ToString();
return Cache;
}
public static string RenderRazorViewToString(string viewName, object model)
        {
ViewData.Model = model;
using (var sw = new StringWriter())
            {
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public static class HtmlHelperExtensions
        {
public static string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData)
            {
ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName);
if (result.View != null)
                {
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
                    {
using (HtmlTextWriter output = new HtmlTextWriter(sw))
                        {
ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output);
result.View.Render(viewContext, output);
}
}
return sb.ToString();

}
return String.Empty;
            }
        }

This code worked in MVC 4 :
public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

I hope you will enjoy this Article, and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates with ASPHostPortal



ASP.NET MVC 5 Hosting - with ASPHostPortal.com :: What are Differences ViewBag, ViewData and TempData in Asp.Net MVC 5 ?

clock March 12, 2014 05:49 by author Diego

In Asp.Net MVC 5 (Model-View-Controller) there are three options ViewBag, ViewData, and TempData to pass small amount of data from controller to view. In this article i am going to explain what is ViewBag, ViewData and TempData and their use in Asp.Net MVC 5.

A. ViewData & ViewBag objects.
ViewData
is a dictionary object that you put data into, which then becomes available to the view.It is an in-built dictionary object that is derived from ViewDataDictionary class that can be accessed and set with string type key values. It is a used to pass data from Controller to View. ViewData's value become null if redirection occur because its life lies only during current request.

Key points to remember about ViewData.

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewData requires typecasting for complex data type and it is recommended to check for null values to avoid error.
  • ViewData is used to pass small amount of data from controller to view, so it helps to maintain data when moving from controller to view.
  • ViewData has short life i.e.  Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewData is to provide a way to transfer/pass data from controllers and views.
  • ViewData is faster than ViewBag.

ViewData Example.
In View:

@ViewData["Name"]

ViewBag is dynamic object, meaning we can add properties to it in the controller, and read them later in the view. Its value becomes null when redirection occurs because its life lies only during current request. This is because the aim of ViewBag is to provide a way to transfer/pass data from controllers and views.

ViewBag Example:
In View:

@ViewBag.Name

Similarities between ViewBag & ViewData :
Both the ViewData and ViewBag objects are great for accessing extra data (i.e., outside the data model), between the controller and view. Since views already expect a specific object as their model, this type of data access to extra data, MVC implements it as a property of both views and controllers, making usage and access to these objects easy. Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

B. TempData Object.The problem with the ViewData and ViewBag for transferring data from controller to view is that the data is only alive for current request. The data is lost if a redirection takes place i.e. if one Action redirects to another action. But when we need to persist the data between actions/redirection then asp.net MVC offers another dictionary object called TempData for that purpose. It is derived from TempDataDictionary and created on top of session. It will live till the redirected view is fully loaded. “TempData”  Helps to maintain data when you move from one controller to other controller or from one action to other action.The benefit is that if you have a chain of multiple redirections it won’t cause TempData to be emptied the values will still be there until you actually use them, then they clear up after themselves automatically.

When to use TempData in ASP.NET MVC ?
Example condition :

I came across this problem where I had a basic list of items and for each if these items I wanted to add a delete action on my controller. I wanted to add some error checking around the delete action so if someone attempted to modify the URL and enter a incorrect parameter into my controller, I wanted to redirect back to the previous controller and notify the user of this mistake. Take this example. I have a Product Controller and the Index Action and View lists all of the products. I have a delete action on the Product Controller which checks if the productId parameter is valid and then removes the product and redirects to the Index action using the RedirectToAction method.

The solution :
When validating the productId, if its NOT valid simply add a new key/value to the TempData object and call the RedirectToAction method. TempData stores data for short periods of time for the current and next HTTP request. In your index view, you can check to see if your key/value pair exists and display a error message. If you refresh the page, you will notice the data from the TempData will be gone. Remember to use RedirectToAction where possible as this is more friendly with Unit Testing rather than using the HttpResponse redirect method.

I hope you have got what is ViewBag, ViewData and TempData in Asp.Net MVC and I hope you will refer this article for your need. Stay tuned and stay connected for more technical updates.



ASP.NET MVC 5.1.1 Hosting with ASPHostPortal.com :: Difference between ASP.NET Web Forms and ASP.NET MVC

clock March 5, 2014 09:53 by author Kenny

Now I wiil expose the main difference between ASP.NET Web Form and ASP.NET MVC.
ASP.NET Web Forms is a part of the ASP.NET web application framework. Web Forms are pages that your users request through their browser and that form the user interface (UI) that give your web applications their look and feel. These pages are written using a combination of HTML, server controls, and server code. When users request a page, it is compiled and executed on the server, and then it generates the HTML markup that the browser can render. Using Visual Studio, you can create ASP.NET Web Forms using a powerful IDE. For example, this lets you drag and drop server controls to lay out your Web Forms page. You can then easily set properties, methods, and events for controls or for the page in order to define the page's behavior, look and feel, and so on. To write server code to handle the logic for the page, you can use a .NET language like Visual Basic or C#.

Based on ASP.NET, ASP.NET MVC allows software developers to build a web application as a composition of three roles: Model, View and Controller. A model represents the state of a particular aspect of the application. A controller handles interactions and updates the model to reflect a change in state of the application, and then passes information to the view. A view accepts necessary information from the controller and renders a user interface to display that information.
ASP.NET developers have two options when building new Web projects: ASP.NET Web Forms or ASP.NET MVC framework.
There are the different
between ASP.NET Web Form and ASP.NET MVC:



ASP.Net Hosting – ASPHostPortal.com :: Adding Email Confirmation to ASP.NET Identity in MVC 5

clock February 19, 2014 09:14 by author Diego

One of the mainline features about ASP.NET Identity is to make it easy to Adding Email Confirmation. This process will send an email to the user with a link they can click on to confirm their registration and log in to the system. Prior to confirmation they will not be able to log in.

 

This post shows how you can adding email confirmation to ASP.NET Identity in MVC 5.

First I started by creating a new MVC 5 application.  You no longer select whether you want an Internet or Intranet application, you just select the MVC template and select the authentication type you want to use. For an Internet type application you select Individual User Accounts.  Once your web application is created open IdentityModels.cs in the Models directory.  You will see a class called ApplicationUser which is analogues to the UserProfile in SimpleMembership.  It is an empty class that inherits from IdentityUser which has these properties.

You must to modify the user information to store a the confirmation token and a flag indicating whether confirmation was completed or not.

Now let’s implement the method in the AccountMembershipService class:

 

Here, we’re setting the confirmationGuid to user. This is the GUID stored in the database that uniquely identifies the user. We then set the verifyUrl to the Verify action on the Account controller – passing the confirmationGuid as the ID parameter. The redirect to the RegisterStepTwo action just displays a view to the user that tells them to look for the email to complete the registration process.

Once the user gets the email they click on the link that will take us back to the controller action RegisterConfirmation. With that configured, when the user clicks the register button, they’ll be sent an email with the confirmation link it, and they’ll be redirected to the confirmation page. If we find a user we set IsConfirmed to true and return true from the method; otherwise we return false. If the user is confirmed they will be able to log in.


That is all there is to setting up email confirmation using ASP.NET Identity in MVC 5.
Thanks.

 



ASP.NET MVC 5.1 Hosting :: ASPHostPortal.com Proudly Launches ASP.NET MVC 5.1 Hosting

clock January 28, 2014 07:48 by author Ben

ASPHostPortal.com officially launches ASP.NET MVC 5.1  hosting at affordable prices. Instant Setup, Fast and Friendly Support!

ASPHostPortal.com, a leading innovator in Windows Hosting, announces the launch of ASP.NET MVC 5.1 Hosting. The ASP.NET MVC 5.1 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET.

ASP.NET MVC 5.1 contains a number of advances over previous versions, including the ability to define routes using C# attributes and the ability to override filters,Enum support in Views, Support for current Context in Unobtrusive Ajax, Filter Overrides and etc. The user experience of building MVC applications has also been substantially improved.

The company believes in providing top-notch service at affordable price. They offer ASP.NET MVC 5.1 hosting with the following features such as Unlimited Domain, Unlimited Subdomain, 5 GB Disk Space, 2 SQL Database and Unlimited Email Account.
 
“Our customers have been asking us about MVC 5.1 and we are happy to deliver a hosting platform that supports all the latest in the Microsoft Web Stack.” said said Dean Thomas, Manager at ASPHostPortal.com.  "And it proves that we remain at the forefront in Microsoft technology".

Where to look for the best ASP.NET MVC 5.1 hosting service? How to know more about the different types of hosting services? Read more about it on http://www.asphostportal.com.


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.



ASP.NET MVC 5 Hosting :: Customizing ASP.NET MVC 5/Web API 2 Scaffolding Templates in Visual Studio 2013

clock January 20, 2014 17:25 by author Mike

In this article, I showed you how you can easily customize the default code generation(scaffolding) templates in ASP.NET MVC 5 and ASP.NET Web API 2 using Visual Studio 2013.

Scaffolding in ASP.NET allows you to automatically generate code in web application. This make it easy to quickly add boilerplate code in your application. There is a nice introduction of scaffolding in ASP.NET application using Visual Studio 2013 at here. The default templates are good for a lot of cases, but sometimes you want to customize these scaffolding templates for all your applications and sometimes you need to use different scaffolding templates in different projects. In this article, I will show you how to customize the default scaffolding t4 templates in ASP.NET MVC 5 and ASP.NET Web API 2 globally and per project.

Description:

If you need to customize the scaffold templates globally then just navigate to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates(depending upon where Visual studio reside),

In the above explorer, you can globally update the t4 templates of ASP.NET MVC 5 and ASP.NET Web API 2.

Now for per project base, just create a CodeTemplates folder in your application root and paste the above folders inside CodeTemplates folder,

Hopefully this article useful for someone.



ASP.NET MVC 5 Hosting - ASPHostPortal.com :: How to create Default User Roles in ASP.NET MVC 5

clock January 15, 2014 07:02 by author Ben

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more.

In this article, We'll look into how to create default user roles in ASP.NET MVC 5. Let's begin by establishing where the user role is assigned, and that is the registration stage. In the default template, you have the AccountController that contains a Register action. The default implementation looks like this:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    // If we got this far, something failed, redisplay form
    return View(model);
}


What's missing here is the role assignment, so let's add that. Right after the CreateUserAndAccount call, we can check whether a specific role exists, and if it is - add the registered user to it. In case the role is new, create it.

if (!Roles.RoleExists("Standard"))
    Roles.CreateRole("Standard");
Roles.AddUserToRole(model.UserName, "Standard");


Here I am working with a role called Standard, but obviously you can use another identifier for it. If you open the database that is carrying the app data, you will notice that there are two new tables introduced in the existing context - Roles and UsersInRoles.

As the data skeleton is established, you can now limit content access based on roles. In views, you could use the Authorize attribute:

[Authorize(Roles = "Admin")]

Or you could check for the role directly:


@if (Roles.GetRolesForUser().Contains("Admin"))
{
}

That's the tutorial How to create Default User Roles in ASP.NET MVC 5, for more information about ASP.NET MVC 5 Hosting please feel free to visit ASPHostPortal.com.

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, .NET 4.5.1/ASP.NET 4.5, ASP.NET MVC 5.0/4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information.

 



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