Celebrating 8 Successful Years
+1 (315)-715-8489

Maintain Session For login User Using ActionFilter

Action Filter

Action filters contain logic that is executed before and after a controller action executes. 

2methods we can override from the action filter.

1. OnActionExecuting :before execution 
2. OnActionExecuted  :After execution 


Check session value on Action Filter

1.       Create a class (e.g  SessionExpire ) derived from ActionFilterAttribute Class.

 

public class SessionExpire:ActionFilterAttribute

 

 

2.       Override the OnActionExecuting method in created class (SessionExpire) .

       public override void OnActionExecuting(ActionExecutingContext filterContext)

{

……….

……….

}

 

3.       In side this method check the session value is available or not, if not available then redirect to login page.

 

 

public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

        if ((HttpContext.Current.Session["UserName"] == null) ||                                                                                    

                                 (HttpContext.Current.Session["UserID"]==null))

               {

         filterContext.Result = new RedirectResult("~/Account/Login");

         return;

                      }

4.       How to use in Action Method of controller:

We can use this by the class name derived from ActionFilterAttribute in the controller.

 [SessionExpire]

        public ActionResult SubmitTimesheet()

        {

………………..

………………….

 }

These are the simple steps to check session in Action level

 

Restrict different Users for specific Action Method of  controller

1.       If we are Using Roll in Db to restrict different user for different controllers

We have to modify little bit code on that . i.e if a user of contractor want to access a method of admin then it should show you are not authorized for that page

 

Suppose we have 3 users namely below

User Roll Id

User Roll Name

1

Contractor

2

Approver

3

Admin

 

2.       While login we are storing the user type in session as below

      HttpContext.Current.Session["UserType"]=user.userid;

3.       To check the action method belongs to particular user type or not we have to pass the user type from action method to SessionExpire  class derived from ActionFilterAttribute Class.

Like:

[SessionExpire(<UserType>)]

 

[SessionExpire(1)]

        public ActionResult SubmitTimesheet()

        {

………………..

………………….\

Return view();

               }

4.       To get the User Type and validate with session value of user Type we have to modify the SessionExpire Class.

    public class SessionExpire:ActionFilterAttribute

    {

 public int sessionid { get; set; }

        public SessionExpire(int roll=999)

        {

            sessionid = roll;

        }

       public override void OnActionExecuting(ActionExecutingContext filterContext)

 {

……….

……….

 }

     }

Note: By default roll is 999 if we are not passing any value from action method if we are passing “1” then roll will be “1” and that will assign to “sessionid” property

 

 

5.       Below are the code used to check the session value with passed usertype from action method
in OnActionExecuting Method
.

 

public class SessionExpire:ActionFilterAttribute

    {

        public int sessionid { get; set; }

 

        public SessionExpire(int roll=999)

        {

            sessionid = roll;

        }

 

        public override void OnActionExecuting(ActionExecutingContext filterContext)

            {

       if ((HttpContext.Current.Session["UserName"] == null) ||

         (HttpContext.Current.Session["UserID"]==null))  (Note:Checking for session exist or not )

                {

                    filterContext.Result = new RedirectResult("~/Account/Login");

                    return;

                }

 

 

  if ((int)HttpContext.Current.Session["UserType"] != sessionid)

           (Note: Checking stored session id match to passed usertype id from action )

       {

             if ((int)HttpContext.Current.Session["UserType"] == 1)

      (Note: check with login Usertype and redirect to Unauthorized page of Login User )

                {

                filterContext.Result =

                new RedirectResult("~/Contractor/notauthorised");

                    return;

                }

  

            if ((int)HttpContext.Current.Session["UserType"] == 2)

                {

                 filterContext.Result = new RedirectResult("~/Approver/notauthorised");

                 return;

                }

            if ((int)HttpContext.Current.Session["UserType"] == 3)

                {

             filterContext.Result = new RedirectResult("~/Admin/notauthorised");

              return;

                }

         }

                base.OnActionExecuting(filterContext);

   }

}

 

 


Redirect to Particular page when Session Fails in Action Filter


When we are working in particular page and that time session fails then it will Navigate to login page and after login page it should redirect to That page instead of home page . I did this with Action filter.

 

1.       If session fails Store the Url in a session

2.       After signin redirect to session stored Url

As Code

public override void OnActionExecuting(ActionExecutingContext filterContext)

 {

        if ((HttpContext.Current.Session["UserName"] == null) ||                                                

(HttpContext.Current.Session["UserID"]==null))

(Note: Checking for session fails or not  ? if fails then store in a new session variable for redirect after login )

        {                  

HttpContext.Current.Session["Urlreturn"] = HttpContext.Current.Request.Url+"";

filterContext.Result = new RedirectResult("~/Account/Login");

return;

 

        }

 }

 

 

In Login action check if data exist in session then redirect to that page

 

if ((Session["Urlreturn"] as string) != null)

(Note :checking for stored Url is Exist after login)

                {

                    return Redirect((Session["Urlreturn"] + ""));

(Note: If exist then redirect to Stored URL where session fails)

                }

                                                  Pradeep - Software Developer                         

How to Use a EDMX file for multiple DB having same type of table and schema

1.There are 3 database are have same type of table for 3 application.

Tables are
2.Another database to manage the applications  having a table to store the Application ID ,server name, DBname, Password and username  of application database.

3. Create an EDMX file for the Application that will work as a template and another for the DB to manage the Application


4.While creating the EDMX file the class  generate by EDMX file is

5. Create a class of same class name as above with a parameterized constructor to pass the connection string to this for change the Db connection string dynamically.

6. Based on the application id we will get the database detail and pass to the function to change the connection string.

Copy the connection  string for applicationDB from web.config file and put that in a string and change the server name, DBname, Password and username  of application based on Appid.

7.GetuserDBbyAppid() function we will get the entity for the particular DB .then we can use the Entity Framework to curd operation on that DB.

Need not required to create EDMX file for same type of database which are situated in different servers and all server can manage through an application means we can create users in base application so that user can login in assigned application.

Pradeep - Software Developer

ng-if Else in Angularjs

Today i am going to share the code sample for angularjs ng-if else conditional Expression.
The angularjs not provide the if() {} else{} condition like others but we can achieve it by using the module.It is a collection of control flow directives like:
 
1. ng-if 
2. ng-if-else
3. ng-else 


Example Code Sample

<!DOCTYPE html> <html> <head> <script src="http://code.angularjs.org/1.2.0-rc.2/angularjs.js"></script> <script> function mainController($scope) { $scope.data = { FName: 'Yogendra', LName: 'Yadav' }; } </script> <body ng-app> <div ng-controller="mainController"> <h2>ng-if else in angularjs</h2> <div> <div ng-if="data.FName==='Yogendra'"> Employee Name: {{FName}} {{LName}} </div> <div ng-if="data.FName===' '"> Sample Code </div> </div> </div> </body> </html>

Yogendra - Software Developer

Executing Sql Scripts with Go Statements as CommandText

Here is the code lines for executing the sql script . we may get the errors while executing any string as CommandText that loaded with sql script. This causes due to the GO Statements. I'm providing these code lines to split that Go statements. Hope this is helpful to execute script file with Go Statements.


                 string sqlBatch = string.Empty;
                    script += "\nGO";
                    SqlCommand cmd = new SqlCommand("", conn);
                    foreach (string line in script.Split(new string[2] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.ToUpperInvariant().Trim() == "GO")
                        {
 
                            cmd.CommandText = sqlBatch;
                            cmd.ExecuteNonQuery();
                            sqlBatch = string.Empty;
                        }
                        else
                        {
                            sqlBatch += line + "\n";
                        }
                    }​


Sai Venkat - Software Developer

Get In Touch

Presentations

© Copyright 2016 by SKG Infosolution. All rights reserved