Showing posts with label Custom HTML Helper. Show all posts
Showing posts with label Custom HTML Helper. Show all posts

Monday, September 21, 2015

Custom Authentication using IAuthenticationFilter


Requirement: Only validated users/Logged in users should be able to view application pages, others should be redirected to login screen.

Assuming you already have a login page and users are being validated against DB.

Step 1: Create a folder named "CustomAttributes" in the root of your MVC website.

Step 2: Create a class named "CustomUserAuthenticationAttribute" under the newly created folder.

Step 3: Inherit and implement the class using System.Web.Mvc.ActionFilterAttribute, IAuthenticationFilter

public class CustomUserAuthenticationAttribute : System.Web.Mvc.ActionFilterAttribute, IAuthenticationFilter
{
 //Implemention goes here
}

Step 4: Use following Namespaces:

using System.Web.Mvc;
using System.Web.Mvc.Filters;

Step 5: Create methods shown below:

     /// <summary>
        /// This is Called when a Controller/Action decorated with [CustomUserAuthentication] is executed.
        /// </summary>
        /// <param name="context">The context.</param>
        public void OnAuthentication(AuthenticationContext context)
        {
            //Get Logged in User info from Session
            var currentUserSessionInfo = Common.GetFromSession<UserSessionInfo>(Common.SessionKeys.UserSessionInfo);

            //Return unauthorized result if user info is null
            if (currentUserSessionInfo == null)
            {
                context.Result = new HttpUnauthorizedResult();
            }
            //If User is not logged in OR Branch Logged in is null, logout user and return unauthorized result 
            else if (!currentUserSessionInfo.IsUserLoggedIn || string.IsNullOrEmpty(currentUserSessionInfo.BranchLoggedIn))
            {
                var usr = currentUserSessionInfo.LoggedInUser;
                if (usr != null)
                {
                    usr.Logout();
                    usr.Dispose();
                }
                context.Result = new HttpUnauthorizedResult();
            }

        }


        /// <summary>
        /// This gets called after OnAuthentication has returned its result
        /// </summary>
        /// <param name="context">The context.</param>
        public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
        {
            //If an unauthorizedResult is detected, redirect to login screen
            if (context.Result == null || context.Result is HttpUnauthorizedResult)
            {
                context.Result = new RedirectToRouteResult("Default",
                    new System.Web.Routing.RouteValueDictionary{
                        {"controller", "Account"},
                        {"action", "Login"},
                        {"returnUrl", context.HttpContext.Request.RawUrl}
                    });
            }
        }

Step 6: Now decorate a controller with [CustomUserAuthentication].

I wanted to allow only authenticated users to access my home page, my controller looked like this:

[CustomUserAuthentication]
    public class HomeController : BaseController
    {

        public ActionResult Index()
        {
            return View();
        }

    }

Every time home page is called, users are validated using IAuthenticationFilter. This prevents home page from any unauthenticated user's access. If I need more such pages, I just need to decorate the new page's controller/ action.

Monday, August 31, 2015

Custom HTML Helpers with HTML Attributes

 Requirement: Create custom Help control that takes HTML markup and HTML Attributes as input.

Assuming you already have an MVC website created with KendoUI core package installed.

Step 1: Create a folder named "Helpers" in the root of your MVC website.

Step 2: Create a static class named "HtmlHelper" under the newly created folder.

Step 3: Use following Namespaces:

using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

Step 4: Create a static function as follows:

public static IHtmlString HelpIcon(this HtmlHelper helper, string Id, Func<object, object> toolTipMarkup = null, object htmlAttributes = null)
 {
     //StringBuilder for creating a string from htmlAttributes parameter
     var attributes = new StringBuilder();

     //Read HTML Attributes and construct string out of it
     if (htmlAttributes != null)
     {
         foreach (var prop in htmlAttributes.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
         {
             attributes.Append($"{prop.Name}= '{prop.GetValue(htmlAttributes, null)}'");
         }
     }
    
     //StringBuilder for holding the entire markup while it is being constructed
     var sb = new StringBuilder();

     //Construct markup from the provided child controls
     var markup = (toolTipMarkup == null ? "" : toolTipMarkup.DynamicInvoke(helper.ViewContext).ToString());

     //Construct final control with markup and htmlAttributes
     sb.Append($"<span class='glyphicon glyphicon-info-sign info-in-panelHeader' {attributes} title='{markup}'></span>");

     //Return as HTML String
     return new HtmlString(sb.ToString());
 }

Step 5: Compile the project.

Step 6: Open the view in which you want to render the above control.

Step 7: Add references to the newly created control and Kendo UI on top of your view:

@using Kendo.Mvc.UI

@using <Your ProjectName>.<FolderName>
Example @using HtmlHelpers.Helpers

Step 8: Invoke KendoToolTip script:

  $(document).ready(function () {
      $(". info-in-panelHeader ").kendoTooltip({
          filter: "span.glyphicon-info-sign", width: "375px", position: "right", autoHide: true, content: kendo.template($("#TooltipTemplate").html()),
          animation: {
              open: {
                  duration: 200
              }
          }
      });
  });

 <script id="TooltipTemplate" type="text/x-kendo-template">
        <p class="TooltipHeader"><span class="glyphicon glyphicon-info-sign"></span>&nbsp; Help</p>
        <p>#=target.data('title')#</p>
    </script>

Step 9: Add following markup:

@Html.HelpIcon("hlpFeatureHelp", @<text>
     <ul>
         <li>This is help text shown as bullet 1</li>
         <li> This is help text shown as bullet 2.</li>
     </ul>
 </text>, new {style= "margin-top:10px; z-index:999999;" })


Run your website, you will find a help icon rendered on your view.  



Hover over the icon to activate the tooltip.  


Custom HTML Helpers without HTML Attributes



Requirement: Create custom container DIV control that takes in HTML markup as input.

Assuming you already have an MVC website created.

Step 1: Create a folder named "Helpers" in the root of your MVC website.

Step 2: Create a static class named "HtmlHelper" under the newly created folder.

Step 3: Use following Namespaces:

using System;
using System.Text;
using System.Web;
using System.Web.Mvc;

Step 4: Create a static function as follows:

public static IHtmlString Div(this HtmlHelper helper, string Id, Func<object, object> innerHTML = null)
 {
     //Declare StringBuilder to hold the control's markup
     var sb = new StringBuilder();

     //This reads the markup dictionary from the input parameters
     var markup = (innerHTML == null ? "" : innerHTML.DynamicInvoke(helper.ViewContext).ToString());

     //This constructs the markup for final control
     sb.Append($"<div id='div_{Id}' class='caption'>{markup}</div>");
    
     //Finally returns the control markup as string
     return new HtmlString(sb.ToString());
 }

Step 5: Compile the project.

Step 6: Open the view in which you want to render the above control.

Step 7: Add reference to the newly created control on top of your view:

@using <Your ProjectName>.<FolderName>

Example @using HtmlHelpers.Helpers

Step 8: Add following markup:

@Html.Div("divMyCustomDiv", @<text>
         <div>My Custom Markup</div>
         <span>More Stuff</span>
         </text>)