Common Asp.Net Tips and Tricks 3

Introduction

This is a series articles on ASP.NET Tips and Tricks. Under my previous article Common ASP.Net Tips and Tricks, we learned configuration tips and tricks. The article explained common exceptions we encounter while development and best practices for code implementation.

Tips and Tricks



LINQ to Entities does not recognize ToString


Sometimes LINQ to Entities does not recognize the method "System.String ToString()" and this method cannot be translated into a store expression.

Solution

This type of exception frequently occurs when we are working with LINQ or Entity Framework.

For example:

  1. var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();  

According to the preceding syntax, when we convert “status.ToString()”, in the where condition the exception "Expression not found such method in SQL" occurs where the condition returns an IQueryable result. So if we convert the result to IEnumerable, then the preceding type of exception never occurs.

For example:

  1. var result=dc.Tests. AsEnumerable().Where(i=>i.status==status.ToString()).FirstOrDefault();

ToString() vs Convert.ToString()

Which is best, ToString() or Convert.ToString()?

Solution

Always use Convert.ToString() conversion for strings since it handles null values also, whereas ToString() leads to an exception when we convert a string from null.

string or StringBuilder

What to use, string or StringBuilder, for string manipulation?

Solution

Always use StringBuilder that stores a string for manipulation or appends a string to it. Whereas each string concatenation leads to copying a string to another string variable instead of preserving one memory allocation.

If(isBool==true) vs if(isBool)


What to use, If(isBool==true) or if(isBool)?

Solution

Always use if(isBool) like if condition since it is comfortable to read easily.

If(strValue==”some Value”) vs If(strValue.ToLower()==”some value”)

What to use, If(strValue==”some Value”) or If(strValue.ToLower()==”some value”)?

Solution

Whereas we filter records with search parameter always, first convert to lower case or upper case, then compare the result, since some search results do not work as expected with case sensitive words.

“” or string.Empty

What to use, “” or string.Empty, when initializing or reinitializing a string variable?

Solution
Best practices are to use string.Empty since no new instance is created, setting a “” value creates a new memory location to store the value into it.

Detecting which control is responsible for a postback event

How to detect which control is responsible for a postback event in an ASP.Net web form?

Solution
ASP.NET internally uses a “__EVENTTARGET” hidden field that stores the ID of the control that caused the postback and acts accordingly. So we can easily detect a Checkbox change, Radio button change, Dropdownlist change and so on.

Resource Files not being compiled into DLLs


What to do when resource files are not being compiled into DLLs?

Solution
This type of error or problem occurs when we are using a resource file and a proper build action is not set.

Step 1


Right-click on the resource file that you have added or just selected and press F4 that displays the Properties window.

Step 2


Change the Build Action to Embedded Resource.

Then when we publish the website with a third-party DLL or tools on Go Daddy or another hosting platform sometimes a System.Security.Security Exception occurs due to trust level.

For example, Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Solution

To allow third-party tools or DLL to run without website we need to put the following configuration on the web.config :

<configuration> 
<system.web> 
<trust level="Full" /> 
</system.web> 
</configuration>

Conclusion

I hope you found my previous article on ASP.NET Tips and Tricks Part 1 useful. In this article, we learned common exceptions and their solutions with some best practices when developing to build a better product. I will provide other useful tips in my next series of articles. Thanks!

Validate CKEditor using jQuery validate

Introduction

In this article we learn about how to validate CKEditor control using jquery validate
Prerequisite. Below JavaScript library are used to validate CKEditor control.
  1. Jquery-1.11.1.js
  2. Jquery.Vaidate.js

Description

When we configure CKEditor control in our html page it render in Iframe so jquery validate library fails to check weather this control is empty or not and we face issue while validating this control. Let’s see example:
HTML:
<form>
    <textarea id="txtDemo1" name="txtDemo1"></textarea>
        <textarea id="txtDemo2" name="txtDemo2"></textarea>
    <input type="submit" value="submit">
</form>

Let’s assume we have configured CKEditor for both text area control and both fields are required in system. For validation we have implemented following validation for both control as shown below:


SCRIPT:

$("form").validate({
ignore: [],
rules: {
txtDemo1: {
ckrequired: true //Custom required field 
}
, txtDemo2: {
 required: true  //Default required field fails
}
}});

Extention method for check CKEditor Control

jQuery.validator.addMethod("customfunctionanme",validationfunction,validationmessage);


jQuery.validator.addMethod("ckrequired", function (value, element) {
var idname = $(element).attr('id');
var editor = CKEDITOR.instances[idname];
var ckValue = GetTextFromHtml(editor.getData())
    .replace(/<[^>]*>/gi, '').trim();
    if (ckValue.length === 0) {
//if empty or trimmed value then remove extra spacing to current control
      $(element).val(ckValue);
      } else {
       //If not empty then leave the value as it is
       $(element).val(editor.getData());
       }
        return $(element).val().length > 0;
 }, "This field is required");

function GetTextFromHtml(html) {
            var dv = document.createElement("DIV");
            dv.innerHTML = html;
            return dv.textContent || dv.innerText || "";
        }


From above code we have used both default required validation and ckrequired custom required method by extending jquery validate library. Along with custom method we have use one JavaScript utility function to extract text from html value after that we have trimmed value to validate trim value with extra space.

Hope this article is useful for validate CKEditor control as well as create custom validation method using jquery validate.

Conclusion

In this article we learn about validating CKEditor using custom jquery validation method.

Common Asp.Net Tips and Tricks Part -2

Introduction
In previous series of Asp.Net Tips and Tricks we learn basic configuration for Asp.Net application and exception handling. You can also visit Part-1  In this article we learn new tips which is useful for both web form and Asp.Net MVC application.

Description

In this article we learn some tips which will helpful while we development.
Problem: When we are using Response.Redirect method inside Try Catch Block ThreadAbortException occurs
Solution 1: Response.Redirect(“redirectUrl”,false);

This method stops current execution of request and error is prevented.

Solution 2: Second way to prevent ThreadAbortException error is to handle error in try catch block
    try {
       Response.Redirect(“redirectToSomeUrl”);
     } catch(ThreadAbortException e) 
     {
     }

Problem:Server cannot set status after HTTP headers have been sent

Solution: This error occurs with number of reason in Asp.Net MVC application
When we use export to excel or any other format of export this type of error occurs to prevent this type of error use return type new EmptyResult() for ActionResult.

Problem:Different type of ActionResult  in Asp.Net MVC
Solution:
ViewResult: Renders a view as Html page

PartialViewResult: This is reusable component. Renders a small person of view in Page

RedirectResult: Redirect to another action method

RedirectToRouteResult: Redirect to another action method. Route parameter are required e.g. Action Name and Controller Name

ContentResult: Returns user defined content types

JsonResult: Returns a serialize JSON object

JavaScriptResult: Returns a script that can be executed to client

FileResult: Returns a binary output to write to the response

EmptyResult: Returns a null result

Problem: What is difference between string.Empty and  “”
Solution : string.Empty is runtime constant. Its value is evaluated runtime.
We cannot pass string.Empty as default argument  in any method as parameter because default parameter in Methods required compile time constant


public  static void  SomeMethod(string p1=string.Empty){
//To Do Write some code }
This method not complied success fully
public  static void SomeMethod(string p1=””)
{//To Do Write some code
}
Compilation failed because string.Empty is runtime constant
Problem: Unfamiliar behavior of  string.Trim() function
Solution:
When we use trim function for null value NullRefrence Exception occurs so best way to prevent this error is to always check null safe and then use Trim function.
To check online behavior of Trim function visit IdeOne

public static void Main() {
// your code goes here
string s1=null;
string s2=string.Empty;
Console.WriteLine(s2.Trim());
Console.WriteLine(s2.Trim().Length);
//Below code returns runtime error
//    Console.WriteLine(s1.Trim());
//    Console.WriteLine(Convert.ToString(s1).Trim());
}

Conclusion

In this article we learn basis tips and tricks for asp.net MVC and Common errors.

New Feature in Visual Studio 2015 RC

Introduction

In this Visual Studio 2015 RC have major changes ever, an integrated suite of developer productivity tools, cloud services, and extensions that enable you and your team to create great apps and games for the web, for Windows Store, for the desktop, for Android, and for iOS. This article highlights some of the most important features in visual studio IDE.
New Feature in Visual Studio 2015 RC 



Description

 1)    Sign In across multiple accounts

You can work with multiple user accounts in Visual Studio by adding them as you go or through the new Account Manager. Then, you can switch between those accounts on the fly when connecting to services or accessing online resources. Visual Studio remembers the accounts you add so you can use them from any instance of Visual Studio or Blend.
 


Figure1: You can add multiple accounts in visual studio by clicking on Add an account link

2)    Choose your target platform(s)
 Visual Studio 2015 supports cross-platform mobile device development. You can write apps and games that target iOS, Android, and Windows and share a common code base, all from within the Visual Studio IDE. You’ll see all these new project types in the File, New Project dialog.
And also support for classic desktop applications is better than ever, with lots of improvements to languages, libraries, and tools. Below are different platform.
•    Cross-platform mobile apps in C# with Xamarin for Visual Studio
•    Cross-platform mobile apps in HTML/CSS/JavaScript with Apache Cordova
•    Cross-platform mobile games in C# with Unity
•    Classic desktop and Windows Store
•    Cross-platform mobile games in C# with Unity
•     Cross-platform apps and libraries for native C++
•    Web
ASP.NET 5 is a major update to MVC, Web API and SignalR, and runs on Windows, Mac, and Linux. ASP.NET 5 has been designed from the ground up to provide you with a lean and composable .NET stack for building modern cloud-based apps. The Visual Studio 2015 RC tooling is more closely integrated with popular web development tools such as Bower and Grunt

3)    Live code analysis (Light Bulbs)
 In Visual Studio 2015 RC, light bulbs display in the left margin (when using the keyboard) or a tool tip (when hovering over an error with the mouse). The light bulb tells in real time that the compiler (possibly using a custom rule set) has detected an issue in your code and also has a suggestion for how to fix the issue. When you see a light bulb, click on it for actionable suggestions
 


Figure-2 Live code analysis - image reference from MSDN site
4)    Design your UI
The Blend experience for designing XAML user interfaces has been significantly enhanced. Blend has been completely redesigned to provide a more intuitive UI, more powerful XAML editing capabilities, and better integration with Visual Studio.

5)    Diagnose Issue
•    Advance Breakpoints
Breakpoints in the debugger are significantly more configurable, and the UI for interacting with breakpoints is consolidated into a peek window so that you never have to leave the code editor


Figure 3- Breakpoints with expression condition -Image reference from MSDN site
•    Performance Tips
Performance tips display the execution time of methods during debugging, enabling you to quickly spot bottlenecks without having to invoke the profiler


Figure 4- Elapsed time -Image reference from MSDN site
•    Error List
The error List now supports filtering on any column. It is also scalable enough to show a live view of errors, warnings, and code analysis across your entire C# or Visual Basic solution as you type, even when a code change produces thousands of warnings. The new Error List is back-compatible with existing usage.
•    GPU Usage Tool
The GPU Usage Tool helps you collect and analyze GPU usage data in DirectX apps and games and troubleshoot whether performance bottlenecks are originating in the CPU or GPU.
6)    Connect To Service
Add Connected Service wizard also integrates with the new Account Manager to make it easy to work with multiple user accounts and subscriptions. In Visual Studio 2015 RC, support for the following services is provided out of the box (assuming that you have an account):
•    Azure Mobile Services
•    Azure Storage
•    Office 365 (mail, contacts, calendars, files, users & groups)
•    Salesforce


Figure-5 Add Connected Service- Image reference from MSDN site
7)    Synchronized Settings (Roaming Settings)
Visual Studio 2015 improves on this experience by synchronizing more of your settings and synchronizing settings across Visual Studio family of applications like Professional, Enterprise, Express SKUs, and Blend. Setting includes Settings for some of the most commonly configured settings such as Text Editor, Key bindings, Theme & Fonts & Colors, Startup, and Environment Aliases
8)    High Resolution Images and Touch Support
The Visual Studio IDE now has true high resolution images on denser displays (in areas like menus, context menus, tool window command bars, and in some projects in Solution Explorer). And on a touch-screen in the Visual Studio code editor window, you can now use gestures such as touch and hold, pinch, tap and so on to zoom, scroll, select text, and invoke context menus.
9)    Title Case Menu
Visual Studio menus are once again title-case by default. However if you happen to like the ALL CAPS style, you can set it on start up or in the Tools > Options > General property page:


Figure-6 Title Case Menu- Image reference from MSDN site
10)    Custom Layouts
You can create store and roam custom window layouts. For example, you can define one preferred layout for use on your desktop machine, and different layout for use on a laptop or small screen device. Or you may prefer one layout for a UI project and another for a database project. Key bindings enable you to rapidly switch between layouts. These layouts are available on any instance of Visual Studio when you are signed in.


Figure-7 Custom Layout- Image reference from MSDN site
11)    Notification Hub
The UI for the notification hub has been streamlined to make it easier to scan quickly. Additional kinds of notifications have been added including performance issues, rendering issues, and crashes, and you can now tell Visual Studio to stop showing a notification.


Figure-8 Notification Hub- Image reference from MSDN site
12)    Code Lens: Find what happened to your code (Enterprise and Professional editions only)
You can review changes and other history for work items, bugs, code reviews, and so on for code that’s stored in Visual Studio Online (VSO) or in Team Foundation Server (TFS).
In Visual Studio Enterprise and Visual Studio Professional, you can now:
•    Get history for an entire code file in the Visual Studio editor.


Figure-9 Code Lens- Image reference from MSDN site
•    See a graph that shows the people who changed your code. This can help you find patterns in your team's changes and assess their impact.


Figure-10 Code Lens- Image reference from MSDN site
•    Easily see when your code was last changed.
•    Find changes in other branches that affect your code.
Reference
Main Reference: MSDN library https://msdn.microsoft.com  for image reference also
Conclusion
This article covers almost all new general features of Visual Studio 2015 RC IDE. Visual Studio by default provides support for C#, C and C++, JavaScript, F#, and Visual Basic. Third parties as well as Microsoft offer extensions to support many other languages, including Python, Unity for Game and Apache Cordova. Hope you enjoy this article.

JUICE UI - ASP.NET Web Forms with jQuery UI

Introduction

JUICE UI is open source ASP.NET Web Forms components for jQuery Widgets. We use all jQuery UI components like ASPX Server side control. Here we learn and use JUICE UI control in Aspx Web Form. JUICE UI Control also available for ASP.NET MVC Control also as helper method.

Description


Juice UI requires .NET 4.0. Please ensure the proper version of .NET is installed before attempting to integrate Juice UI Controls. Juice UI can be installed through the NuGet Package Manager:
PM> Install-Package Juice UI

Note: While use JUICE UI Control TargetControl attribute is required to set with ASPX Control ID. Before Use JUICE UI Control Add ScriptManager in Page.
All jQuery Widget and JUICE UI Control have same attribute

Date Picker Control

<asp:TextBox runat="server" ID="txtDate" />
<juice:datepicker runat="server" targetcontrolid="txtDate" mindate="-20" maxdate="+1M +10D" />
Juice UI Date Picker control support all attribute which is supported by JQuery UI Date Picker

Autocomplete Control


<asp:TextBox runat="server" ID="txtLanguage" placeholder="Type Word" />

<asp:TextBox runat="server" ID="txtLanguagerFromWebAPI" placeholder="Type Word" />

<juice:Autocomplete ID="_Autocomplete" runat="server" TargetControlID="txtLanguage" Source="ActionScript, AppleScript, Asp, BASIC, C, C++, Clojure, COBOL, ColdFusion, Erlang, Fortran, Groovy, Haskell, Java, JavaScript, Lisp, Perl, PHP, Python, Ruby, Scala, Scheme" />

<juice:Autocomplete ID="_Autocomplete1" runat="server" TargetControlID="txtLanguagerFromWebAPI" SourceUrl="/API/Service/GetLanguage" />

To implement auto complete control with JUICE UI Auto Complete, it requires source to bind data (Array data or key value pair) as auto complete. In this demo I have use both static as well as dynamic Ajax or Web API based source to bind with JUICE UI Autocomplete.

Dialog Control


<asp:TextBox runat="server" ID="txtDate" />
<juice:datepicker runat="server" targetcontrolid="txtDate" mindate="-20" maxdate="+1M +10D" />
To open dialog it requires adding JavaScript function to trigger dialog to open.
<script type="text/javascript">
    // Click Link to open Dialog
    $("#lnkDialog").click(function(e) {
        e.preventDefault();
        // Open the dialog    
        $("#_Default").dialog("open");
    });

</script>

Slider Control


    <asp:Literal runat="server" ID="currentValue" />
</div>
<juice:Slider ID="slider2" runat="server" Max="150" />
<p>Two Value Slider</p>
<div><span id="slider2Value"></span>
</div>
<juice:Slider ID="_Range" runat="server" Range="true" Min="0" Max="500" Values="75, 300" />
Slider Control work same as jQuery UI Slider and all property also supported in JUICE UI Slider Control

Menu Control



<juice:Menu ID="_Menu" runat="server">
    <juice:MenuItem ID="Menuitem1" runat="server">
        <Content><a href="#">Item 1</a>
        </Content>
    </juice:MenuItem>
    <juice:MenuItem ID="Menuitem2" runat="server">
        <Content><a href="#">Item 2</a>
        </Content>
    </juice:MenuItem>
    <juice:MenuItem ID="Menuitem3" runat="server">
        <Content><a href="#">Item 3</a>
        </Content>
        <Items>
            <juice:MenuItem ID="Menuitem4" runat="server">
                <Content><a href="#">Item 3-1</a>
                </Content>
            </juice:MenuItem>
            <juice:MenuItem ID="Menuitem5" runat="server">
                <Content><a href="#">Item 3-2</a>
                </Content>
            </juice:MenuItem>
            <juice:MenuItem ID="Menuitem6" runat="server">
                <Content><a href="#">Item 3-3</a>
                </Content>
            </juice:MenuItem>
            <juice:MenuItem ID="Menuitem7" runat="server">
                <Content><a href="#">Item 3-4</a>
                </Content>
            </juice:MenuItem>
            <juice:MenuItem ID="Menuitem8" runat="server">
                <Content><a href="#">Item 3-5</a>
                </Content>
            </juice:MenuItem>
        </Items>
    </juice:MenuItem>
    <juice:MenuItem ID="Menuitem9" runat="server">
        <Content><a href="#">Item 4</a>
        </Content>
    </juice:MenuItem>
    <juice:MenuItem ID="Menuitem10" runat="server">
        <Content><a href="#">Item 5</a>
        </Content>
    </juice:MenuItem>
</juice:Menu>

In this menu control I have provided nested menu example also

Tab Control


<juice:Tabs ID="_Tabs" runat="server" PanelTemplate="<div>!</div>" AutoPostBack="true">
    <juice:TabPage Title="Tab 1" ID="Tab1">
        <TabContent>
            <p>This should display on tab 1.</p>
            <asp:TextBox ID="_Textbox" runat="server" /> </TabContent>
    </juice:TabPage>
    <juice:TabPage Title="Tab 2" ID="Tab2">
        <TabContent>
            <p>This should display on tab 2.</p>
        </TabContent>
    </juice:TabPage>
</juice:Tabs>

Accordion Control


<juice:Accordion ID="_Accordion" runat="server">
    <juice:AccordionPanel Title="Panel 1">
        <PanelContent> First Panel content.
            <asp:TextBox runat="server" ID="dob1" ClientIDMode="Static" />
            <juice:Datepicker ID="Datepicker1" runat="server" TargetControlID="dob1" /> </PanelContent>
    </juice:AccordionPanel>
    <juice:AccordionPanel Title="Panel 2">
        <PanelContent> Second Panel content. </PanelContent>
    </juice:AccordionPanel>
</juice:Accordion>

This control create Accordion like jQuery UI

Reference


1.    https://github.com/appendto/juiceui
Note: I have use demo from JUICE UI Open Source GitHub Repository as above.

Conclusion


In this article we learned new way to use jQuery UI Control using Server Side Control JUICE UI Library. We have seen Most used JUICE UI control like Date Picker, Accordion, Auto complete etc. Hope you enjoy this article.

Common Asp.Net Tips and Tricks


Introduction

This article is useful for all developer who faces this type of exception in their software development time. Article also provides tips for common error. I will provide you solution of common exception and issue facing during development.

Tips and Tricks


1) 500 Error occurs while publishing website in IIS. Most configuration error occurs because of this.
 Solution
Figure1: Configuration Steps related to publish website in IIS
Step 1: Choose appropriate application pool and if target framework is missing  in application pool then follow below steps as per your pc.
  • Open command Prompt using Run as administrator 
  • Change the directory path for proper framework in command prompt
CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319
After changing directory path hit enter "aspnet_regiis i" this command register aspnet_regiis is available into directory.
Step 2: Select proper publish code 

Step 3: Check the Physical path is accessible for current user or IUSR by verify using “Test Settings”
2) If you have publish your website to live server and you want to change some minor code behind file and want to upload to live server what is best way?
Solution: Instead of publish whole site,
Step 1: Just build the project without error and go to project bin folder find "projectname.dll" and "projectname.pdb" (If available)

Step 2:Then put this two file to live project's bin folder and just replace it. Now Website runs with latest change. Because all our .cs file(code behind file) is converted to DLL and our page searches method reference from DLL file.

3) How to resolve "Maximum request length exceeded" Exception while working with web service or JSON data.
 Solution: The 4MB default is set in machine.config, but you can override it in you web.config. For instance, to expand the upload limit to 20MB, add below code to web.config:
     
IIS7(and later version) has a built-in request scanning which imposes an upload file cap which defaults to 30MB. To increase it, you also need to add the lines below
    
        
             
    
4)  The request filtering module is configured to deny a request that

exceeds the request content length (IIS 7)

Solution: You have to add below configuration to web.config file



    
        
             
    


5)  The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler.If the file should be downloaded,add a MIME map(For Json file)

Solution:  You have to add below configuration to web.config file


    
         

    

6)     When I integrating WebAPI2 in existing MVC web application some dependency error occurs.

Solution:

I have reinstall "system.web.http.webhost" package using Nuget and add WebApiConfig file. In ”appstart” folder  and register  to global.asax file before RouteConfig. If routeconfig added before webapiconfig then WebApi not working properly.

WebApiConfig.cs

public static void Register(HttpConfiguration config)   
{  
// Web API routes
    config.MapHttpAttributeRoutes();  

    config.Routes.MapHttpRoute(  
    name: "DefaultApi",  
    routeTemplate: "api/{controller}/{id}",  
    defaults: new
    {  
        id = RouteParameter.Optional  
    });  
//To return json format data
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
}
In global.asax file
AreaRegistration.RegisterAllAreas();  
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
//added before RouteConfig
GlobalConfiguration.Configure(WebApiConfig.Register);  
RouteConfig.RegisterRoutes(RouteTable.Routes);  
BundleConfig.RegisterBundles(BundleTable.Bundles); 

7)   How to speedup page request in asp.net

Solution:  Just add below configuration to web.config file and it will take care automatically.

    
        
        
            
            
            
            
        
        
            
            
            
            
        
    
    



Conclusion:

In this article we learn basic configuration tips as well as common exception and its solution which is common while developing web application. I will update this article with other useful tips

Store Role in Form Authentication Cookie for SSO Authorization



Introduction

This article explains about Customize Form Authentication for store role information with username in Form Authentication Cookie. Storing role in authenticated cookie help when we use SSO -Single Sign On functionality for authentication and role value used in authorize user.

Description

I am working on SSO- Single Sign On Functionality with Disconnected Architecture. SSO for Cross Domain or  Sub Domain. I have three sub domain web site which share common Authentication but hosted at different place like GoDaddy, BlueHost, Big Rocks etc. These system first request for valid authentication and then further processing is done. As all user info is store in main server other Sub Domain do not contain any information about user or role.So Any How I need Functionality for Single Sign On With Authentication as well as Authorization and Finally I  found this solution for requirement.I will guide you internal structure of Form Authentication and also customize Form Authentication Cookie for store Role or other information which is useful for SSO- Single Sign On for Authentication  as well as Authorization.


 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
       username,
       DateTime.Now,//Cookie Issue Date
       DateTime.Now.AddMinutes(30),//Expire Date
       isPersistent,//Is cookie Persistent or not
       userData,//Custom data here we store current authenticated user's role
       FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie with authenticated ticket.
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

In above code once user is  successfully authenticated with valid credential web can create FormAuthenticatationTicket by storing current user's role information. I have reference above code from MSDN . For More information you can visit this link.

How to access this role information while request in other system?


                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(FormsAuthentication.FormsCookieName);
                String data = ticket.UserData;
                String[] roles = data.Split(',');//If you have store multiple role or data with Comma value 

As from above code  we can decrypt authenticated cookie and extract all information we have set like Username,Cookie Issue Date, Expire Date,Userdata etc. As Previously we have store role information in userdata property we can retrieve User's Role value and check weather user have valid access right or not.

Conclusion

In this article we learn store role information with username in Form Authentication Cookie by Customizing Form Authentication Ticket. So we use this custom field in SSO- Single Sign On Authentication and Authorization on Sub Domain project.

Dynamic Query in LINQ using Predicate Builder

Introduction This tutorial explains how to create a dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query an...

Learn More