Consuming Security Service

In this section, we will explore how we can consume the SecurityService class using ASP.NET and ASP.NET MVC.

ASP.NET

Microsoft's ASP.NET 4.5 is one of the most popular web technologies in recent times. ASP.NET is a web application development framework built on top of Common Language Runtime (CLR) which you can use to build and deploy web applications and dynamic websites on a managed platform.

Consuming Security Service using ASP.NET 4.5

The following code snippet illustrates how you can consume the SecurityService class from an ASP.NET client:

public partial class Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      BindUserDropDownList();
      BindGrid();
    }
  }

  protected void BindGrid()
  {
    SecurityService serviceObj = new SecurityService();
    var userData = serviceObj.GetAllUsers();

    if (userData.Count > 0)
    {
      grdUser.DataSource = userData;
      grdUser.DataBind();
    }
  }

  protected void BindGrid(Int32 userId)
  {
    SecurityService serviceObj = new SecurityService();
    var userData = serviceObj.GetUserByID(userId);
    if (userData.Count > 0)
    {
      grdUser.DataSource = userData;
      grdUser.DataBind();
    }

  }
  protected void BindUserDropDownList()
  {
    SecurityService serviceObj = new SecurityService();
    var userData = serviceObj.GetAllUsers();
    if (userData.Count > 0)
    {
      ddlUser.DataSource = userData;
      ddlUser.DataTextField = "UserName";
      ddlUser.DataValueField = "UserID";
      ddlUser.DataBind();
    }

    ListItem li = new ListItem("All", "0");
    ddlUser.Items.Insert(0, li);
  }

  protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
  {
    if (ddlUser.SelectedValue == "0")
    {
      BindGrid();
    }
    else
    {
      BindGrid(Convert.ToInt32(ddlUser.SelectedValue));
    }
  }
}

When you execute the ASP.NET client application, the output looks like the following screenshot:

Consuming Security Service using ASP.NET 4.5

The ASP.NET MVC Framework

The Model View Controller (MVC) design pattern was invented by Trygve Reenskaug and popularized by the Ruby on Rails framework. Scott Guthrie of Microsoft actually designed the ASP.NET MVC Framework in 2007. The ASP.NET MVC Framework is an application framework based on the popular model view controller design pattern. It helps reduce the cohesion among the components by isolating the concerns in your application.

Usage of the MVC design pattern provides the following benefits:

  • Makes your code easier to test, maintain, and deploy
  • Facilitates code re-use, maintainability, and testability

The MVC design pattern is comprised of the following major components:

  • The Model: It is the Data Access layer, and represents the business logic components and the application's data
  • The View: It is the User Interface or the or the application
  • The Controller: It is the Business Logic layer and it handles user interactions and updates the model as and when required

The most important benefit of the MVC design pattern is its ability to promote a clean separation of concerns. In doing so, applications that are designed on the MVC pattern are easier to test and maintain.

You can use the MVC design pattern to facilitate code re-use, reduce cohesion among the application's components, and facilitate easier maintenance and testing of the application's components. The ASP.NET MVC Framework is designed based on the MVC Framework, and promises to be the technology of choice for designing web applications in ASP.NET, primarily due to its improved features over the traditional ASP.NET runtime. You can get to know more about the ASP.NET MVC Framework and MVC design pattern from my book titled ASP.NET 4.0 Programming by Mc-Graw Hill Publishing at http://www.amazon.com/ASP-NET-4-0-Programming-Joydip-Kanjilal/dp/0071604103.

Consuming Security Service using ASP.NET MVC

The HomeController class extends the controller class of the ASP.NET MVC Framework. It contains a collection of action methods.

We create an instance of the SecurityService class in the HomeController class. In the Index() action method, the GetAllUsers() method is called on an instance of UserAuthenticationModel. The userList() method returns a list of users as a Json type.

The following code illustrates the controller class for the ASP.NET MVC client:

public class HomeController : Controller
{
  SecurityService serviceObj = new SecurityService();

  public ActionResult Index()
  {
    UserAuthenticationModel userModel = new UserAuthenticationModel();
    ViewBag.ListUser = new SelectList(serviceObj.GetAllUsers().ToList(), "UserID", "UserName");
    return View(userModel);
  }
  private IQueryable<T> SortIQueryable<T>(IQueryable<T> data, string fieldName, string sortOrder)
  {
    if (string.IsNullOrWhiteSpace(fieldName)) return data;
    if (string.IsNullOrWhiteSpace(sortOrder)) return data;

    var param = Expression.Parameter(typeof(T), "i");
    Expression conversion = Expression.Convert(Expression.Property(param, fieldName), typeof(object));
    var mySortExpression = Expression.Lambda<Func<T, object>>(conversion, param);

    return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
    : data.OrderBy(mySortExpression);
  }

  public JsonResult UserList(string id, string sidx = "UserId", string sord = "asc", int page = 1, int rows = 10)
  {
    var userData = serviceObj.GetAllUsers().AsQueryable();
    if (id != null)
    {
      userData = serviceObj.GetUserByID(Convert.ToInt32(id)).AsQueryable();
    }
    var sortedDept = SortIQueryable<DataAccess.UserAuthentication>(userData, sidx, sord);
    var totalRecords = userData.Count();
    var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);
    var data = (from s in userDataselect new
    {
      id = s.UserID,cell = new object[] { s.UserID, s.UserName, s.UserEmail, }
    }).ToArray();

    var jsonData = new
    {
      total = totalPages,page = page,records = totalRecords,rows = data.Skip((page - 1) * rows).Take(rows)
    };
    return Json(jsonData);
  }
}

When the ASP.NET MVC client application is executed, the output will look like the following screenshot:

Consuming Security Service using ASP.NET MVC

Asynchronous operations

Asynchronous operations help execute operations asynchronously and, hence, leverage the flexibility of the parallel processors of today. Async operations are performed in .NET 4.5 using the Task object in .NET Framework 4.5 and MVC 4. The asynchronous programming model of .NET 4.5 is built on top of the existing asynchronous programming model of NET 4.0, and enables you to write methods that return objects of the Task type. In essence, the await and async keywords together with the Task object make it easier for you to write asynchronous code in .NET 4.5. This model is also known as Task-based Asynchronous Pattern (TAP). An example of this pattern is as follows:

public void Page_Load(object sender, EventArgs e)
{
  RegisterAsyncTask(new PageAsyncTask(LoadData));
}

public async Task LoadSomeData()
{
  var employees = Client.DownloadStringTaskAsync("api/employees");
  var departments = Client.DownloadStringTaskAsync("api/departments");
  var cities = Client.DownloadStringTaskAsync("api/cities");
  await Task.WhenAll(employees, departments, cities);
  var employeeData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Contact>>(await employees);
  var departmentData = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await departments);
  var cityData = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await cities);
  listEmployees.DataSource = employees;
  listEmployees.DataBind();
}

You can also implement asynchronous operations in the ASP.NET MVC Framework using the Async controller. To do this, you should extend your controllers from the abstract AsyncController class.

The following code shows how the AsyncController class looks:

public abstract class AsyncController : Controller, IAsyncManagerContainer, IAsyncController, IController
{
  protected AsyncController();
  public AsyncManager AsyncManager { get; }
  protected virtual IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state);
  protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state);
  protected override IActionInvoker CreateActionInvoker();
  protected virtual void EndExecute(IAsyncResult asyncResult);
  protected virtual void EndExecuteCore(IAsyncResult asyncResult);
}

Note

Note that the AsyncManager class belongs to the System.Web.Mvc.Async namespace, and provides the necessary operations for the AsyncController class.

You can write your controller by deriving your custom controller class from the AsyncController class as shown in the following code:

public class HomeController : AsyncController
{
  //Usual code
}

The important point to note here is that the name of an asynchronous controller class should have the "Controller" suffix. So, the Home controller class can be named HomeController, but not "Home" or "ControllerHome". Another interesting point to note here is that you cannot have the sync and async versions of of the same method residing in the same controller.

Therefore, you cannot have both the Index() and IndexAsync() methods residing in the Index controller class. If you do this, an AmbiguousMatchException exception will be thrown.

The following code snippet illustrates a synchronous controller and its action method:

public class ProductsController: Controller 
{
  public ActionResult GetProducts(int productCode) 
  {
    //Usual code
  }
}

The following code snippet illustrates an asynchronous controller and its action method:

public class ProductsController: AsyncController 
{
  public ActionResult GetProducts(int productCode) 
  {
    //Usual code
  }
}

An async action comprises of a pair of methods that should have the "Async" and "Completed" suffixes, respectively. The following code snippet illustrates this:

public class HomeController : AsyncController 
{
  public void GetProductsAsync() 
  {
    //Some code
  }

  public ActionResult GetProductsCompleted(IList<Product> items) 
  {
    //Some code
  }
}

Note

Note that although these APIs are still supported, using the new "async/await" keywords and the Task object is a recommended way of implementing asynchronous behavior in your ASP.NET 4.5 applications.

When you define the routes to handle a request asynchronously, you should use the AsyncMvcRouteHandler and not the usual MvcRouteHandler, as in the following code snippet:

routes.Add(new Route("Default.aspx", new AsyncMvcRouteHandler())
{
  Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset