Google+ Peter Bromberg's .NET Blog | All Things Programming

Peter Bromberg's .NET Blog All Things Programming

Implementing a Custom IPrincipal in an ASP.NET MVC Application

25. January 2014 14:45 by admin in ASP.NET, C#, MVC

 I have an MVC application for which I have implemented a Custom ExtendedMembership - derived Membership class that is hosted via a WCF Service.

I have a custom MembershipProviderForwarder class that plugs right into my web.config as the Membership provider, but what it actually does is forward all Membership calls to my WCF Service, which uses the real custom Membershp provider, and returns back all the results to the app from over the wire.

In this manner I can have any number of MVC apps all using the same provider via my Webservice.

Since I have custom Membership fields, but only a couple, I didn't want to get into writing a lot of Profile code. Instead, I have a Custom User object that has these extra fields which can be returned from the UserProfile table in SQL Server.

The issue is that I only want to make Webservice calls when the user first logs in, and I want to store my custom fields in the Forms Ticket (it has a UserData property for just this purpose). In this manner I can use the PostAuthenticateRequest event to pull my custom data our of the forms cookie and attach my custom IPrincipal to the HttpContext.Current.User property for each subsequent request. Here is how I did that:


1. Create the interface


interface ICustomPrincipal : IPrincipal


    int UserId { get; set; }

    string FirstName { get; set; }

    string LastName { get; set; }



2. CustomPrincipal


public class CustomPrincipal : ICustomPrincipal


    public IIdentity Identity { get; private set; }

    public bool IsInRole(string role) { return false; }


    public CustomPrincipal(string email)


        this.Identity = new GenericIdentity(email);



    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }



3. CustomPrincipalSerializeModel - for serializing custom information into userdata field in FormsAuthenticationTicket object.


public class CustomPrincipalSerializeModel


    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }



4. LogIn method - setting up a cookie with custom information


if (Membership.ValidateUser(viewModel.Email, viewModel.Password))


    var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();


    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

    serializeModel.UserId = user.Id;

    serializeModel.FirstName = user.FirstName;

    serializeModel.LastName = user.LastName;


    JavaScriptSerializer serializer = new JavaScriptSerializer();


    string userData = serializer.Serialize(serializeModel);


    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(








    string encTicket = FormsAuthentication.Encrypt(authTicket);

    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);



    return RedirectToAction("Index", "Home");



5. Global.asax.cs - Reading cookie and replacing HttpContext.User object, this is done by overriding PostAuthenticateRequest


protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)


    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)


        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);

        newUser.UserId = serializeModel.UserId;

        newUser.FirstName = serializeModel.FirstName;

        newUser.LastName = serializeModel.LastName;

        HttpContext.Current.User = newUser;





6. Access in Razor views


@((User as CustomPrincipal).Id)

@((User as CustomPrincipal).FirstName)

@((User as CustomPrincipal).LastName)


and in code:


    (User as CustomPrincipal).Id

    (User as CustomPrincipal).FirstName

    (User as CustomPrincipal).LastName

How to Map Stored Procedure with dynamic SQL In Entity Framework

15. November 2013 12:46 by admin in

When you do a function import to a stored proc that has dynamically - generated SQL in it, Entity Framework will report that no columns were mapped.


Here is an easy, non-destrctive way to make sure EF gets the column metadata to complete your function import.


What EF does when it attempts to map your sproc is it executes the sproc with all parameters having null values.

Of course if the resultset is generated via dynamically assembled SQL or comes from a Table Variable, EF cannot "see" the results.


So what we do is the following. 


Say your sproc returns six columns. You would return each column as a null, but casting it to it's actual datatype:


if ( @deptId is null and @chkExemptOnly is null  and @chkActiveOnly is null and @msYearAC is null and @msdepttypeid is null and @Firstname is null and @lastName is null ) 
cast(null as int) as empid,
cast(null as varchar(11)) as emplID,
cast(null as int) as Active,
cast(null as varchar(25)) as lastName,
cast(null as varchar(25)) as firstName,
cast(null as varchar(25) ) as middleName

You can put this kind of code right at the beginning of the sproc just after the AS statement, and Entity Framework will correctly map the resultset for you. You do not need to worry about leaving the above SQL block in the sproc, since it only executes when all the input parameters are NULL.

How to Filter (Search) in a Table With jQuery

25. October 2013 11:28 by admin in Jquery

Click here for Working Sample

<!DOCTYPE html> 
<html > 
<head><meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>JQuery Table Search Demo</title>
<script src=""></script>
<script type="text/javascript">
jQuery.expr[':'].contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
var searchterm = $(this).val();
if(searchterm.length >2) {
var match = $('"' + searchterm + '")');
var nomatch = $('"' + searchterm + '"))');
nomatch.css("display", "none");
} else {
$('').css("display", "");
<style type="text/css">table {background-color: #FAF3DF;}table {background-color: #fff;}table td.selected-cell {color: #fff;background-color: #660000;}table {background-color: #F1EDE3;border-bottom: solid 2px #fff;font-weight: bold;}table tr.selected {background-color: #FFCC88;} </style></head> <body><p>Search term:<input type="text" name="search" /></p><table cellspacing="4"><tr class="data-header"><td>Contacts</td></tr><tr class="data-row"> <td>Jerald Mickey</td></tr><tr class="data-row"> <td>Minda Carlen</td></tr><tr class="data-row"> <td>Marlene Nida</td></tr><tr class="data-row"> <td>Daysi Cassano</td></tr><tr class="data-row"> <td>Bonny Medford</td></tr><tr class="data-row"> <td>Patria Sciortino</td></tr><tr class="data-row"> <td>Kathaleen Herwig</td></tr><tr class="data-row"> <td>Junior Chamberlin</td></tr><tr class="data-row"> <td>Belkis Fleishman</td></tr><tr class="data-row"> <td>Evangeline Ishee</td></tr><tr class="data-row"> <td>Reyes Newland</td></tr><tr class="data-row"> <td>Eleonore Federico</td></tr><tr class="data-row"> <td>Briana Launius</td></tr><tr class="data-row"> <td>Eula Bernard</td></tr><tr class="data-row"> <td>Albert Palm</td></tr><tr class="data-row"> <td>Zofia Schlachter</td></tr><tr class="data-row"> <td>Donnette Nichols</td></tr><tr class="data-row"> <td>Herta Hile</td></tr><tr class="data-row"> <td>Lurlene Pfeffer</td></tr><tr class="data-row"> <td>Teresita Wasson</td></tr><tr class="data-row"> <td>Milagros Copes</td></tr><tr class="data-row"> <td>Ai Stimac</td></tr><tr class="data-row"> <td>Brigida Rake</td></tr><tr class="data-row"> <td>Alida Paxton</td></tr><tr class="data-row"> <td>Juliann Mattingly</td></tr><tr class="data-row"> <td>Phil Cervantes</td></tr><tr class="data-row"> <td>Lauryn Salgado</td></tr><tr class="data-row"> <td>Glady Lavergne</td></tr><tr class="data-row"> <td>Shawna Koerber</td></tr><tr class="data-row"> <td>Alana Halloway</td></tr></table> </body> </html>