Monday, April 19, 2010

Single Sign on (SSO) Using Cookie in asp.net

There are various ways to use Single Sign on(SSO) in asp.net web application. We can use cookies, session (state server), SAML and web services etc. Now we would like to give a brief overview of how to use cookie to implement Single Sign on(SSO) in asp.net web application.

Assume that we have two web application hosted on different virtual directory but under same domain. As for example, our root domain is: http://www.cookietest.com and
Other two virtual directory hosted under this domain are
http://www.cookietest.com/cookiesite1/Login.aspx
http://www.cookietest.com/cookiesite2/Default.aspx

If we login successfully in cookiesite1 then it writes the login information in cookie and now opens another tab or a new window in same browser (IE, FF whatever you like). Place this address http://www.cookietest.com/cookiesite2/Default.aspx in address bar logged in automatically in cookiesite2. When we try to access in cookiesite2 –> Default.aspx it checks the login information from cookie. If desired value found in cookie then you logged in automatically. Remember you need to enable cookie in your browser for all of these activities.

Configuration:
1. Web.Config
Before coding we need to some configure in our web.config file. Though cookiesite1 and cookiesite2 are in different virtual directory their web.config file must contains the same machine validationKey, decryptionKey and validation.

Like this,

<machineKey validationKey="282487E295028E59B8F411ACB689CCD6F39DDD21E6055A3EE480424315994760ADF21B580D8587DB675FA02F79167413044E25309CCCDB647174D5B3D0DD9141"
decryptionKey="8B6697227CBCA902B1A0925D40FAA00B353F2DF4359D2099"
validation="SHA1" />


2. IIS
In IIS->Directory security tab add the "ASPNET Machine Account" user and set the full rights.

Coding:
Write cookie after login complete:
Place this code in cookiesite1->Login.aspx.cs
If(login_Successful)
{
//Create a new cookie, passing the name into the constructor
HttpCookie cookie = new HttpCookie(“strCookieName”);

//Set the cookies value
cookie.Value =”set_cookie_value”;

//Set the cookie to expire in 5 minute
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 0, 5, 0);
cookie.Expires = dtNow + tsMinute;

//Add the cookie
Response.Cookies.Add(cookie);

Response.Write("Cookie written. ");
}
Check cookie is exist or not on page_load
Place this code in cookiesite2->Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//Grab the cookie
HttpCookie cookie = Request.Cookies[“strCookieName”];

//Check to make sure the cookie exists
if (cookie != null)
{
ReadCookie();
}
Else
{
lblCookie.Text = "Cookie not found. ";
}

}

Read cookie when page load:
Add this method in cookiesite2->Default.aspx.cs

protected void ReadCookie()
{
//Get the cookie name the user entered

//Grab the cookie
HttpCookie cookie = Request.Cookies[“strCookieName”];

//Check to make sure the cookie exists
if (cookie == null)
{
lblCookie.Text = "Cookie not found. ";
}
else
{
//Write the cookie value
String strCookieValue = cookie.Value.ToString();
lblCookie.Text = "The cookie contains: " + strCookieValue + "";
}
}

Test the application in localhost.And for more information:
http://msdn.microsoft.com/en-us/library/aa289495%28VS.71%29.aspx#vbtchaspnetcookies101anchor10

http://www.aspnettutorials.com/tutorials/network/cookies-csharp.aspx

http://www.developer-corner.com/Resources/KnowledgeBase/tabid/118/articleType/ArticleView/articleId/23/PageID/10/Single-Sign-On-across-multiple-ASPNET-applications.aspx

Thursday, March 25, 2010

Request format is unrecognized for URL unexpectedly ending in

Today I want to share with you a new problem which I had faced yesterday.
Problem:
It was about web service related error. I have used Web Method() in my application to fill up a country dropdown. Everything was going well but when I had used this web method it showed me an error like this:

System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/GetCountyList'.

Information:
After googling, I have found the solution.
This error was occured because GET and POST are disabled by default in ASP.NET 2.0 and greater.
Now I would like to share this with you. From msdn I have got some relative information which may help you to get understand clearly.

The .NET-connected Web services support HTTP GET, HTTP POST and SOAP protocols. By default, in .NET Framework 1.0, all three protocols are enabled. By default, in .NET Framework 1.1 or greater, HTTP GET and HTTP POST are both disabled. This is for security reasons.

Applications that use HTTP GET or HTTP POST to invoke a Web service fail when the Web service is upgraded to .NET Framework 1.1 or greater. These applications receive a exception: System.InvalidOperationException: Request format is unrecognized.

Solution:
HTTP GET and HTTP POST may be enabled by editing the Web.config file for the vroot where the Web service resides. The following configuration enables both HTTP GET and HTTP POST:

<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>

For more info pls visits these links:
http://support.microsoft.com/default.aspx?scid=kb;en-us;819267
http://forums.asp.net/t/1459560.aspx
http://aspadvice.com/blogs/ssmith/archive/2007/09/04/FIX-Request-format-is-unrecognized-for-URL-unexpectedly-ending-in.aspx
http://forums.asp.net/t/988377.aspx

Monday, March 22, 2010

How to show Page loading progress with modal background

Problem:
In my recent application development I have faced a strange problem to show modal background with page loading progress. I had tried in different way but not working perfectly. Then I have solved it. I think that there is another efficient way to solved it but now this time it is working for me.

Solution:

In css class:
.divModalBackground
{
filter: alpha(opacity=50); -moz-opacity:0.5; opacity: 0.5;
width:100%;
background-color: #999988;
position: absolute;
top: 0px;
left: 0px;
z-index: 800;
}

In aspx page:
<asp:Panel ID="Panel1" runat="server" Height="900px" Width="100%" CssClass="divModalBackground" Visible="true" >
<asp:Image runat="Server" ID="ImageLoader" CssClass="LoadingProgress" ImageUrl="../../App_Themes/Black/images/ajax-loader.gif" />
</asp:Panel>


In aspx.cs page I put the code like this:
//to show modal popup at page startup
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Panel1.Visible = true;
}

In aspx page place this
// to clear the modal background when page load complete, place this code at the end of your page just before the end of the form tag
<script type="text/javascript" >
function init()
{
var objdiv=document.getElementById('<%=Panel1.ClientID%>')
if(objdiv)
{
objdiv.style.visibility = 'hidden';
}
}

init();
</script>

Thursday, March 4, 2010

Prevent Duplicate record insertion on page refresh in asp.net

Problem:
Today I have faced a new problem(new for me), when I press save button it works fine and then refresh(F5 or Refresh button on browser) the page but this time it is execute the button click event again. For this duplicate data posting on the server.

I try to find out the problem, nothing wrong in my code. Now turn to google and figure out the problem with solution. I have got several solutions. Now I would like to share this solution which solved my problem ......

Solution:

Assume that in Test.aspx page you have a button and a TextBox:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="110px" OnClick="btnSubmit_Click" />
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>

In Test.aspx.cs..:
public partial class Test : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
btnSubmit.Click += new EventHandler(btnSubmit_Click);base.OnInit(e);
}
protected void Page_Load(object sender, EventArgs e)
{

}
private void Save_Click(object sender, EventArgs e)
{
if (CheckIfDuplicateRequest())

{
return;

}
//Your code to insert the value of the SomeText textbox into the database.
//Set the value of one of the key fields in your web form in session
Session["Refresh"] = TxtName.Text;

}

private Boolean CheckIfDuplicateRequest()
{
if (Session["Refresh"] == null)
{
//Probably submitting the page for the first time
return false;
}
String previousValue = Session["Refresh"].ToString();
if (previousValue != TxtName.Text)
{
//Submitting the page with a different set of values
return false;
}
//Duplicate request.
return true;
}

}

you can get more help from these post:
http://aspalliance.com/687
http://forums.asp.net/p/1296011/3702515.aspx
http://forums.asp.net/p/1190997/2045619.aspx

Monday, February 15, 2010

How to speed up your web site/application

In my recent experience I have faced some performance issues one of them is web application becomes very much slow. To identify this problem I have searched over the net and I have found a lots of topics.

Now I want to share some of the topics with you in summarized way:

1.Minimize HTTP Requests
2.Use a Content Delivery Network
3.Add an Expires or a Cache-Control Header
4.Gzip Components
5.Put Stylesheets at the Top
6.Put Scripts at the Bottom
7.Avoid CSS Expressions
8.Make JavaScript and CSS External
9.Reduce DNS Lookups
10.Minify JavaScript and CSS
11.Avoid Redirects
12.Remove Duplicate Scripts
13.Configure ETags
14.Make Ajax Cacheable
15.Flush the Buffer Early
16.Use GET for AJAX Requests
17.Post-load Components
18.Preload Components
19.Reduce the Number of DOM Elements
20.Split Components Across Domains
21.Minimize the Number of iframes
22.No 404s
23.Reduce Cookie Size
24.Use Cookie-free Domains for Components
25.Minimize DOM Access
26.Develop Smart Event Handlers
27.Choose over @import
28.Avoid Filters
29.Optimize Images
30.Optimize CSS Sprites
31.Don't Scale Images in HTML
32.Make favicon.ico Small and Cacheable
33.Keep Components under 25K
34.Pack Components into a Multipart Document
35.Enable HTTP Keep-Alives
36.Adjust Connection Timeouts
37.Enable HTTP Compression

Wednesday, February 10, 2010

Dynamically add control in asp.net

Recently I have faced a problem when try to dynamically add controls in asp.net, like this,
In test.aspx page

<body>
    <form id="form1" runat="server">
    <div>
        <asp:PlaceHolder ID="PlaceHolder1" runat="server" >    </asp:PlaceHolder>

    </div>
    </form>
</body>

In test.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "btnSave";
this.PlaceHolder1.Controls.Add(btn);
}

Problem:

It is working fine but when I press any button I mean any post back occur It disappears.
After search for a long time I got the proper solution, now I would like to share this with you.

Solution:
To avoid this problem one should dynamically load the controls during Page_Init because we may want to hook up our events with proper handler at an early stage.

protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "btnSave";
btn.Click+=new EventHandler(btn_Click);
this.PlaceHolder1.Controls.Add(btn);
}

Some Tips:
In addition I have got more tips on it,

Control's Lify cycle:

1.Initialization
2.Load view state
3.Process postback data
4.Load
5.Send postback change notifications
6.Handle postback events
7.Prerender
8.Save state
9.Render
10.Dispose
11.Unload

You will get details from here:http://msdn.microsoft.com/en-us/library/aa719775%28VS.71%29.aspx

1.During Page_Init you cannot assign dynamic control property,because in Page_Init event Initialization happens before loadViewState in control's life cycle.The value assigned to the properties during Initialization will simply get overwritten by the ViewState values.

2.If you are expecting your ViewState to retain after the postback, always assign same ID to the dynamic control,if you use like this,

protected void Page_Init(object sender, EventArgs e)
{
TextBox t = new TextBox();
t.ID = Guid.NewGuid().ToString();
this.form1.Controls.Add(t);
}

It will not work. You should use same id or fixed id ,
like this, t.ID="txtName";


Original info:
http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx

Tuesday, February 9, 2010

Use Master page <body> tag in Content page of asp.net

How to use the <body> onclick from content page in asp.net?

Master page is introducing from asp.net 2.0, this is the main layout page for whole application content page just inherit it.

So that,we get the <body> tag only in Master page,in content page there is no body tag. But I need to use this body tag from content page.

After search it I found a solution in asp.net forum. Original link: http://forums.asp.net/t/1062445.aspx

Sample:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" Title="Test Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">

function ClearBox()
{
var divBoxID=document.getElementById('BoxDiv');
divBoxID.style.display='none';
}

document.body.onclick= ClearBox;

</script>


    <input id="Button1" type="button" value="button" />
 
</asp:Content>



For more info pls visit:
http://msdn.microsoft.com/en-us/library/7a9d6h4f.aspx
http://forums.asp.net/t/1225951.aspx

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...