Anas Ghanem

<ItemTemplate ".Net Tips" runat="Weblogs.asp.net" Country="WestBank" />
you may get "System.MethodAccessException" after installing .net 3.5 and vs 2008 sp1 Beta

After i installed the sp1 beta for  Visual studio 2008 and .net 3.5  i get that exception , I'm working on windows xp sp3 .

I solved that by reseting All the Code Access security policies , and then  restarted the IIS.

 

Posted: Jul 08 2008, 12:49 PM by anas | with no comments
Filed under:
Building a color selector control

This article will show you how to create a color selector control that will looks like the image in the right side.  Colors Selector Image

Read the full article on ASP.Net Wiki
 
 
 
Posted: Jun 22 2008, 11:32 AM by anas | with no comments
Filed under:
Differences when Registering Httpmodules and HttpHandlers for Web application Projects and webSite project

In this blog I will mention the Difference between Web Application Project(WAP) and website Prject when registering Custom HttpModules and HttpHandlers,

If you are not familiar with Http Modules and Http Handlers , please read this

And if you are not familiar with the Differences between WAP and website project , Please read this and this 

Now , i will talk about some different cases when working with them ,

For WebSite project :

when you write a custom Http Module ( or Http Handler) in App_Code folder which is inside your website,Then you can register the Custom module in web.config in this format :


 

so for example if you write this module in App_Code


Then you can register that modue in web.config as follows:


 For Wep application Projects(WAP) :

Now,when you are working with web application Project ( or VS 2003 web application ),

Then you need to PrePrend the WebApplication Name(Actually the Root NameSpace of the Project)   before the Class Name as follows:



When The module Or Handler Written in a separate Class Library:

when you need to register a custom HttpModule Or Handler that is written in a separate class library or DLL, then you need to use the following format :


 

In this Blog post i mentioned the correct ways to register the custom HttpModules and HttpHandlers when you are working with Web application Project, Website project, Or with a Custom class library project , Note that if you failed to register the module or handler correctly ,you will get errors like "Could not load file or assembly  or one of its dependencies "...

 

Hope that Helps

Anas Ghanem
 

Posted: May 25 2008, 07:18 PM by anas | with 2 comment(s)
Filed under:
Don't forget to check "Static content service" in IIS7 installation

before a couple of days ,I started to work on Vista and IIS 7, and since the default installation for Vista doesn't includes IIS7 ,

I started by trying to  install IIS 7, I went to control panel, Programs and features, then to " turns windows features on or off",

After the dialog displayed , I navigate to application development features and checked asp.net and IIS management console,

then I selects to install them , after the installation finishes , I prompted to restart the computer and i did ,

after i logged in a gain , and after i added an existing website to in IIS, i requested the website from the browser,then the problems started ,

the browser displayed an empty page with no images , no scripts ... I tried to restart, reinstall with no , after many  hours I find it , 

I didn't check the "Static Content service" , look at the red Box in the Image below :

Note that the "static content" service is responsible for serving the Static contents like images, scripts , style sheets file, ....

In my opinion , if the user doesn't checked this option( which will be checked by default if you checked the " internet information service " root node  ) windows vista must displays an alert or something , so that the user  doesn't waste the time to know the problem ...

So I posted this problem  and hoping to help some one in the future ,

 

Best Regards,

Anas Ghanem 

Posted: May 23 2008, 08:31 PM by anas | with no comments
Filed under: ,
Avoid using the Session in The Page Constructor OR in Page Local Variables

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...

 

Edit 2:

I want to mention that you should also avoid accessing the Session in the Page Local Variables , like this example ( look at the Bold word)

Partial Class Page1

Inherits System.Web.UI.Page

 Private LocalVar as string=Session("MyVar")


that will also throw the HttpException !

 

Hope It Helps,

Anas Ghanem

Posted: May 07 2008, 10:50 PM by anas | with 5 comment(s)
Filed under: ,
Preventing the Deleted Users from logging to your site

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

Posted: Apr 18 2008, 11:30 PM by anas | with 2 comment(s)
Filed under: ,
The Differences in Profile between Web Application Projects (WAP) and website

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

Posted: Apr 12 2008, 09:46 PM by anas | with 2 comment(s)
Filed under: ,
Redirecting the Users to different pages based on there roles

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

Posted: Apr 12 2008, 09:19 PM by anas | with 5 comment(s) |
Filed under: ,
Putting your website in a maintanance mode based on a weekly schedule

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 

 

User Profile Hive Cleanup, A service to help with slow log off and unreconciled profile problems.

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,

Posted: Mar 25 2008, 03:59 PM by anas | with no comments
Filed under:
More Posts Next page »