Search in Help for developer site.

Friday 29 December 2017

Resharper Increase your .Net Productivity

ReSharper: Turbocharge your .NET Development

OverView :


Hi folks.. wassup..hope you doing great..!!!.

Today i have come infront of you  guys to share some information about
useful add-in to visual studio.Yes.. today i am gonna explain you all about
ReSharper tool and its key features and also i will be explaining you
why do i recommend you guys to use it in your daily development routine.

What is ReSharper :

ReSharper is a popular developer productivity extension for Microsoft 
Visual Studio. It automates most of what can be automated in your coding 
routines. It finds compiler errors, runtime errors, redundancies, and code 
smells right as you type, suggesting intelligent corrections for them.

ReSharper helps you explore code by visualizing the structure of files, 
type and style hierarchies, call and value chains, project dependencies. 
It allows you to instantly traverse your entire solution and jump right to 
the exact file and line that you are looking for, decompiling library code 
if necessary.

Why ReSharper :



You can spend less time on routine, repetitive manual work and instead 
focus on the task at hand. A robust set of features for automatic 
error-checking and code correction cuts development time and 
increases your efficiency. You'll find that ReSharper quickly pays back its 
cost in increased developer productivity and improved code quality. 
With ReSharper, .NET developers can truly experience what we mean 
when we say "Develop with pleasure!"


Key Features :

·         Error Highlighting and Quick-Fixes


·         Advanced Coding Assistance


·         Numerous Refactorings 


·         Navigation and Search


·         Unit Testing


·         Code analysis and quick fixes


·         Code generation and templates etc.



Some  Important  Links





https://www.jetbrains.com/resharper/docs/ReSharper_DefaultKeymap_VSscheme.pdf


Download Link


      https://marketplace.visualstudio.com/items?itemName=JetBrains.ReSharper


Thank you guys and feel free to drop  your queries in comment box.

Thursday 2 November 2017

Roles based authorization attribute in Controller or Action level in ASP.NET MVC

Overview :

Modern web development has many challenges, and of those security is both very important and often under-emphasized.

The modern software developer has to be something of a Swiss army knife. Of course, you need to write code that fulfills customer functional requirements. It needs to be fast. Further you are expected to write this code to be comprehensible and extensible, sufficiently flexible to allow for the evolutionary nature of IT demands, but stable and reliable.

Somewhere, way down at the bottom of the list of requirements, behind, fast, cheap, and flexible is “secure”. That is, until something goes wrong, until the system you build is compromised, then suddenly security is, and always was, the most important thing.

As when 'web security' word comes into the discussion, I just would like to brief out about Authorization and Authentication concepts before heading towards my article..

1. What is Authentication?


Authentication is any process by which you verify that someone is who they claim they are. This usually involves a username and a password, but can include any other method of demonstrating identity, such as a smart card, retina scan, voice recognition, or fingerprints. Authentication is equivalent to showing your drivers license at the ticket counter at the airport.

2. What is Authorization?


Authorization is finding out if the person, once identified, is permitted to have the resource. This is usually determined by finding out if that person is a part of a particular group, if that person has paid admission, or has a particular level of security clearance. Authorization is equivalent to checking the guest list at an exclusive party, or checking for your ticket when you go to the opera.

Well, without wasting time we shall get into the topic. So.., as far as security is concerned, today I am going to show you all how to implement "Role based authorization".

Scenario :

Let's assume that we have one MVC application which has various web screens.So,
here I want users who use this app should be able to access the specific screen once they are fully authorized to use it based on their roles. To enable this feature in my app, I am going to implement 'roles based authorization'.

Step 1 : Create MVC app and name it something like 'BookStore'.

Step 2 : Add controller and name it as 'Home'. My controller looks something like as below.

    [CustomAuthorizeByRole("Admin")]   //Only admin can access.
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

    }

Allright,as you can see above I have used custom attribute called 'CustomAuthorizeByRole'.Well., let me brief you what it actually does. So, whenever if you want to enable the app user to access only specific controller or action method, you should decorate them using this custom attribute.

As you can see above I am restricting user from being access home page who are not a part of 'Admin' role. In addition, I am able to allow the app users to access the home screen who are part of multiple roles. So to enable this, you just have to write  similar like below:  
 
   [CustomAuthorizeByRole("Admin","Manager","Analyst")]

Look at above line of code, I am restricting users from being access home page who are not part of 'admin' or 'manager' or 'analyst'.


Step 3 : Implement custom role based authorization

 A. Create a class and name it as 'CustomAuthorizeByRole'.

 B. Add below lines of code.





using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace CustomAuthorization
{
    public class CustomAuthorizeByRole : AuthorizeAttribute
    {
        private readonly string[] allowedroles;
        public CustomAuthorizeByRole(params string[] roles)
        {
            this.allowedroles = roles;
        }

        private List<string> GetCurrentUserSkills()
        {
            var userSkills = new List<string>();
            userSkills.Add("Admin");
            userSkills.Add("Manager");
            userSkills.Add("ReadOnlyUser");
            //This values can come from database also.
            return userSkills;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
        protected override bool AuthorizeCore(HttpContextBase context)
        {
            bool result = false;
            result = IsUserAuthorized();
            if (result)
                base.AuthorizeCore(context);
            return result;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new ViewResult { ViewName = "UnAuthorized" };
        }

        private bool IsUserAuthorized()
        {
            var IsValidUser = false;
            var currentUserRoles = GetCurrentUserSkills();
            foreach (string UserRole in allowedroles)
            {
                IsValidUser = currentUserRoles.Contains(UserRole);
                if (IsValidUser)
                    return IsValidUser;
            }
            return IsValidUser;
        }
    }
} 


As you can see above block of code, my constructor is accepting roles as string array which in turn validate the current user roles accessibility. If any of the roles of current user is containing in  roles string array which is being passed as parameter in constructor method.,  then that user would be able to access the home page.

So for demonstration purpose, I have hard coded the roles for the current user and will use them to check whether or not any of user roles is present in given string array.
And if user roles do not contain in any of the passed roles., then app will take the user to 'UnAuthorize' view, and it would look like below.




Note : Your custom authorize class must inherit 'AuthorizeAttribute'  filter class.

That's it. Now run your application and see the result, it should work.!!!

Thank you.

Please feel free to share your doubts and queries. I will be glad to help you out.


Articles You May Like.


How to create custom code snippets in visual studio





How to generate C# Model Class or Data Object of a Database Table

How to overcome difficulties facing in jquery ajax call and handling it to get proper response from ASP NET MVC Action Method


Tuesday 31 October 2017

Implement custom helper methods in ASP.NET MVC

Overview :

In the world of MVC web development , you might have built various rich UI web application by using HTML user interface components say textbox, checkbox,dropdown etc.

Most of the time while designing your UI, you might have used normal HTML controls or built-in MVC helper methods.. isn't it?. but there may be a situation where MVC built-in helper methods or conventional HTML controls will not full fill your requirements. i.e., at times you may want to load dropdown items based on some condition or logic.

So to overcome this situation, we will be using custom helper methods using which we can formulate the data by adding business logic of our own.

Well, today I am going to explain how to create custom dropdown helper method in MVC.


Step 1 : Create a MVC app using VS tool.

Step 2 : Add Controller , name it as 'Home'. And create action method , name it as 'Index'.

Step 3 : Create view for Index action method.

I have added following code inside the view.

@using CustomHelperMethod
<br />
 &nbsp;<span style="font-weight:bold">Add Student Form</span>
<hr />
<table>
    <tr>
        <td>
            Name :
        </td>
        <td>
            @Html.TextBox("studentName")
        </td>
    </tr>
    <tr>
        <td>
            Gender :
        </td>
        <td>
            @Html.CustomGenderDropDownList("studentGender", "--Select--")
        </td>
    </tr>
</table>
<hr />
<footer>
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

</footer>

As you can observe above lines of code., I have created simple student form where  I have added a custom dropdown control 

 "@Html.CustomGenderDropDownList("studentGender","--Select--")".

MVC does not have this type of helper method in its assembly. It is an extension method. 
Now run the application and check the result.


 

As you can see above picture, I am able to load gender dropdown items using custom dropdown helper method.
Follow below steps to implement custom dropdown helper method.

Step 1 : Create a class and name it as you like.

Step 2 : Add below line of code inside it.





using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace CustomHelperMethod
{
    public static class HelperMethod
    {
        public static MvcHtmlString CustomGenderDropDownList(this HtmlHelper helper, string controlName,
                       string optionalLabel = "", object htmlAttributes = null)
        {

            IEnumerable<SelectListItem> selectList = null;
            List<SelectListItem> genderList = new List<SelectListItem>();
            genderList.Add(new SelectListItem() { Text = "Male", Value = "1" });
            genderList.Add(new SelectListItem() { Text = "Female", Value = "2" });
            selectList = (IEnumerable<SelectListItem>)new SelectList(genderList, "Value", "Text");
            if (htmlAttributes != null && htmlAttributes is RouteValueDictionary)
            {
                RouteValueDictionary htmlAttr = htmlAttributes as RouteValueDictionary;
                if (!string.IsNullOrEmpty(optionalLabel))
                    return helper.DropDownList(controlName, selectList, optionalLabel, htmlAttr);
                else
                    return helper.DropDownList(controlName, selectList, htmlAttr);
            }
            if (!string.IsNullOrEmpty(optionalLabel))
                return helper.DropDownList(controlName, selectList, optionalLabel, htmlAttributes);
            else
                return helper.DropDownList(controlName, selectList, htmlAttributes);
        }
    }
}
 
As you can have a look at above,
I have written a method called 'CustomGenderDropDownList' which is expecting multiple parameters such as name, optional label and html attributes.

Here ,
1. 'name' parameter indicates control's name
2. 'Optional Label' indicates whether or not you want to display '--select--' as first item in your dropdown control.

 I added sample list of items and added them into IEnumerable of SelectListItem object
and pass them to 'helper.DropdownList' method and return it as . MvcHtmlString object.

Note: You can pull object list from DB and add them to 'IEnumerable of SelectListItem' object

That's it. You are done.

Note :

1. If you would like to add strongly typed dropdown control , write a helper method as below

public static MvcHtmlString CustomGenderDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string optionalLabel, object htmlAttributes = null)
{
    --Add your logic--
}
Thank you.

Please feel free to ask your querries. I will be glad to help you all. And Hope this article will help you guys.


 User reads below articles also:

 The Various Ways of Binding MVC DropDownList

How to Disable Required Attribute for Value Types in MVC