While I'm helping the Folks on asp.net forums, I noticed that there is a lot of develoeprs trying to access the Http Session in Page Constructor !
Most of them used this to Implement a kind of Secured Base Page that checks the session value ,and if its missing , it will redirect to login or whatever page,
some of them write this Class :
public class AdminSecuredPage : System.Web.UI.Page
{
public AdminSecuredPage()
{
if (Session["AdminUser"] == null) {
Response.Redirect("~/login.aspx");
}
}
}
Note that the above class will throws HttpException ,
which tells :
"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration> ..."
well the above exception will be thrown because the session is not ready when the Page constructor was called .
The Solution :
One solution is to Move the Code from Page Constructor to Page_init , Note that the page_init for this class will be called before the the Page_init of its Sub Page Class,
so you can check the Session value as follows:
public class AdminSecuredPage : System.Web.UI.Page
{
public AdminSecuredPage()
{}
protected override void OnInit(EventArgs e)
{
// if the user is not Admin , redirect to Login Page
if (Session["AdminUser"] == null)
Response.Redirect("~/login.aspx");
// this needed to initialize its base page class
base.OnInit(e);
}
}
Edit 1:
Note that using the session for that purpose is not a good practice , because there is al ready a built in FormsAuthentication services for asp.net,
however , i will not discuss the security approches here...
Hope It Helps,
Best Regards,
Anas Ghanem
while working with Forms Authentication and Membership services , if the user selects " remember me " check box in the login dialog ,the runtime will create a persistent authentication cookie for him, the persisted cookie is responsible to keep the user logged in for a specified period(even he closed his browser) ,and the default period is 30 minutes in .Net 2.0 or later , and you can change it to some value lets say 50 minutes as follows :
in web.config file :
<authentication mode="Forms">
<forms timeout="50"></forms>
</authentication>
Now the problem comes if the administrator deleted the user from the Membership users , the user still authenticated and can access your site !
to override this behavior , you need to check the user existence upon request , and redirect the user to login page if he is not exists ,
to accomplish this , you can use HttpModule that intercept the user request .
the following are the HttpModule :
Public Class checkUser
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.AuthenticateRequest, AddressOf OnAuthenticateRequest
End Sub
Sub OnAuthenticateRequest(ByVal sener As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
Dim response As HttpResponse = HttpContext.Current.Response
If context.User.Identity.AuthenticationType = "Forms" AndAlso Membership.GetUser(context.User.Identity.Name) Is Nothing Then
FormsAuthentication.SignOut()
context.RewritePath("~/login.aspx")
End If
End Sub
End Class
and you need to register it in web.config file as follows:
<httpModules>
<add name="checkUserStatus" type="checkUser"/>
</httpModules>
Of course this solution will slow your website , because it will add one extra database call for every request ...
Regards,
Anas Ghanem
The profile services is a very helpful and easy way to add custom properties for your users which is not contained in the Standard MembershipUser Properties...
for example , you may need to add the Marital status , Date of Birth, Address.... all of these are custom properties that you may need them while developing your projects ...
If you are familiar with Profile .. you will know that the first thing that must done when working with profiles is to set the Profile properties in web.config File ,
for example ,you can add the Date of Birth, address, Marital status for the user profile as follows,
<profile>
<properties >
<add name="DateOfBirth" type="DateTime"/>
<add name="Address" type="String"/>
<add name="MaritalStatus" type="String"/>
</properties>
</profile>
after saving the file , and working under a website project ,
you will notice that if you typed profile in the page code behind , you will see the properties generated for you as in the picture below:

this happened because the Visual studio created a new class called ProfileCommon Thats inherits ProfileBase , and adds the new properties to it ..
Note that visual studio will always update that class when you change the Profile properties in web.config ...
Now , if you are working with web application projects , you will notice that adding the Profile properties to web.config will not add any properties to Profile object in the code behind of the page.... this is because Visual studio doesn't generate a profileCommon class ...
instead you need to access the properties using ProfielBase.GetPropertyValue(PropertyName)
for example , to access the DateOfBirth property , you need to use this code
Dim DOB As DateTime = CDate(HttpContext.Current.Profile.GetPropertyValue("DateOfBirth"))
In this post , I talked about the Differences in Profile between the normal website and WAP projects , Note that there is a lot of other differences between them, for example ,
when working with resource files , the website will provide a strong typing for resources properties which is also handled by Visual studio ...
Regards,
Anas Ghanem
while working with login control , you can redirect the users to a different pages base on there roles , to do this , you need to handle theLoggedIn event for login control which is fired after the user logged in successfully ,
Assume we have 2 roles , Admins and Editors ..
and assume that every role has its own directory ,
you can check the user role and redirect the user in the loggedIn event handler of the Login control as follows:
protected void Login1_LoggedIn(object sender, EventArgs e) {
if(Roles.IsUserInRole("Admins"))
Response.Redirect("~/Admins/Default.aspx");
else if(Roles.IsUserInRole("Editors"))
Response.Redirect("~/Editors/Default.aspx");
}
Regards,
Anas Ghanem
In this blog i will talk about how to redirect the website visitors to a page that display a " web site under maintenance" ,
you can implement this functionality in your Global application file ( Global.asax file) ,
you can use Application_BeginRequest event handler which will be called when your website receives a new request ,
this example will put your website in a maintenance mode if the current day is Saturday and for a one hour (from 10 -11)
add the following function to Global.asax file ,
(if you don't have this file in your website , in visual studio , right click on the website , select add new Item , select global Application Class)
Private Sub Application_BeginRequest(ByVal source As Object, ByVal e As EventArgs)
Dim application As HttpApplication = CType(source, _
HttpApplication)
Dim context As HttpContext = application.Context
If Now.DayOfWeek = DayOfWeek.Saturday AndAlso Now.Hour = 10 Then
context.RewritePath("~/UnderMaintanace.aspx")
End If
End Sub
adding the above code will redirect your website users to UnderMaintanace.aspx page if the day is Saturday and if the time between 10 -11 .
- Note that i used RewritePath and not Response.redirect because the second one will make a new request to the website and so we will have infinite loop (until we redirect to an HTML page which will not handled by asp net runtime and the function will not get executed )
- the above solution use the date and time of the week to put the website in a maintenance mode , but you can extend this to more practical scenarios ,
for example , you can use a settings file for your website, so that the administrator can set some flag and put the website in maintenance mode !
- Another thing you may want to do is to use http module instead of using the Global application file , so that you can have a reusable module that can be plugged to any new website you design.
Further resources:
Regards,
Anas Ghanem
did your windows XP take a long time to loggoff ? My windows was taking more that a minute to logoff the user ,it just show me logging off , but the computer is Idle...
this happened because there maybe a handle to a registry key that prevent the windows from saving and clearing handle.
I was solving this problem by creating a new user account...
of course this is not a practical solution , so i searched the interenet andfound that tool,
And i just want to share it with you ...
you can download it here
Regards,
There is many reasons to prevent that , like preventing mutiple Database Calls , Or Even Preventing them from submitting the form twice and so save the bandwidth and server resources .
this is a one solution for that Issue ,
Use a hiddenField control to remeber the Click counts ,and when the Linkbutton clicked you check to see if the click counts >0 ,
if yes then you will cancel the click event ,
To Accomplish this , Add a hiddenField Server control to your page as follows :
<asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
Now Register Onclick Attribute for the Linkbutton , in page load add this code :
If Not IsPostBack Then
LinkButton1.Attributes("onclick") = String.Format("javascript:var Count = document.getElementById('{0}'); if (Count.value>0) return false ;Count.value =Count.value+1; ", HiddenField1.ClientID)
End If
How To Test that :
Add the hidden field and register the Onclick attribute as mentioned ,
Now click the LinkButton for the first time , the form must be submitted (postback must occured)
Try to click the LinkButton for the second time, you will notice that there is no postback happened .
Regards,
Anas ghanem
By default .net runtime uses the cookies to remember the session Id between the requests ,
but when using Cookie less sessions ,the runtime inserts the Session Id to the requested url ,
this way the runtime can remember the session id and prevent the session loss .
The problem is , when using the Menu and TreeView Controls , these controls doesn't handle this issue ,
so when those controls display there data from the Site maps, they didn't append the session id to the Navigation Urls of there Items ,
and so when the User Navigate to a page using those controls , he will redirected to a Url that didn't contains the session Id,
and so the runtime can't extract the session id , Hence the session will be lost .
The Solution:
the solution is to Manually Append the Session Id to NavigateUrl of the Items for those Navigation controls,
we can use HttpContext.Current.Response.ApplyAppPathModifier to modify the Item Urls as Follows:
For the Menu Control , we can use MenuItemDataBound Event Handler to accomplish this ,
protected void Menu1_MenuItemDataBound(object sender, MenuEventArgs e)
{
// appened the SessionId to Menu Item URL to Avoid sessin loss
e.Item.NavigateUrl = HttpContext.Current.Response.ApplyAppPathModifier(e.Item.NavigateUrl);
}
For the TreeView Control, we can use TreeNodeDataBound to accomplish this
protected void TreeView1_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
e.Node.NavigateUrl = HttpContext.Current.Response.ApplyAppPathModifier(e.Node.NavigateUrl);
}
Regards,
Some times you may have a page with output cache enabled , and for some reason you don't want to use its output cache ,
Take this seanrio:
you have a page that displays a Dynamic data , and you have 2 users
- Viewers: they just View your page.
- Editors: they need to Edit the data in the page , and they must see the latest changes they did .
and you decided to Enable output Caching on the page to enhance the Performance ,
Now the problem is : the Editors can't Edit and See the Latest chages they did , because the page output is cached ,
you need to enforce the page to show and render the latest data without using its current cached output,and without affecting the current cached output.
The solution :
you need to use HttpCachePolicy.AddValidationCallback Method , so that you can register an output Cache validation Callback ,
Set the Output Caching for your page By setting the output cache in ASPX code as follows:
<%@ OutputCache VaryByParam="none" Duration="600" %>
and in Code behind :
Page_Load:
Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If HttpContext.Current.User.Identity.IsAuthenticated Then
Response.Cache.AddValidationCallback(New HttpCacheValidateHandler(AddressOf ValidateCache), Nothing)
End If
End Sub
And the ValidateCache method:
'' this method will invoked every time the page requested
Public Shared Sub ValidateCache(ByVal Currentcontext As HttpContext, ByVal data As Object, ByRef status As HttpValidationStatus)
If Currentcontext.User.IsInRole("Editors") Then
' Dont use the output cache for the Editors
' and force the page to Excute ( handled as a cache miss)
status = HttpValidationStatus.IgnoreThisRequest
Else
' nothing needed , just use the Output cache
' also if you want to Invalidate the page Output cache ,
' you need to set the status value to HttpValidationStatus.Invalid
End If
End Sub
How to Test :
Add a break point on the Page_laod event Handler, Page_Load will not called for Non Editors Users (Unless the output Cache Expired )
Hope it Helps.
Anas Ghanem
the following are a list of some basic ASP.NET interview questions :
1. Explain the life cycle of an ASP .NET page.
2. Explain the .NET architecture.
3. What are object-oriented concepts?
4. How do you create multiple inheritance in c# and .NET?
5. When is web.config called?
6. Differences between DLL and EXE?
7. Can an assembly have EXE?
8. Can a DLL be changed to an EXE?
9. Compare & contrast rich client (smart clients or Windows-based) & browser-based Web application
10. Compare Client server application with n-Tier application
11. Can a try block have more than one catch block?
12. Can a try block have nested try blocks?
13. How do you load an assembly at runtime?
14. If I am writing in a language like VB or C++, what are the procedures to be followed to support .NET?
15. How do you view the methods and members of a DLL?
16. What is shadowing?
17. What are the collections you’ve used?
18. What is a static class?
19. What is static member?
20. What is static function?
21. What is static constructor?
22. How can we inherit a static variable?
23. How can we inherit a static member?
24. Can we use a static function with a non-static variable?
25. How can we access static variable?
26. Why main function is static?
27. What is garbage collection?
28. Can we force garbage collector to run?
29. What is reflection?
30. What are different type of JIT?
31. What are Value types and Reference types?
32. What is concept of Boxing and Unboxing?
33. What’s difference between VB.NET and C#?
34. What’s difference between System exceptions and Application exceptions?
35. What is CODE Access security?
36. What is a satellite assembly?
37. How to prevent my .NET DLL to be decompiled?
38. What’s the difference between Convert.toString and .toString() method ?
39. What is Native Image Generator (Ngen.exe)?
We have two version of the same assembly in GAC? I want my client to make choice which assembly to choose?
40. What is CodeDom?
The questions above are some of the many questions
the employer may pose on you during an interview. Sometimes questions
will be divided into sections. So, for example, there may be a section
on Threading and you would have to answer a series of questions under
that. Some other popular sections would be Remoting and Webservices,
caching concepts, OOPS, ASP.NET, .NET Architecture, ADO.NET, SQL
Server, UML, XML.
Hope this helps you prepare! Good luck!
More Posts
Next page »