desde un frame o iframe se pierder los valores de session o cookies

Upload: luis-espino

Post on 02-Apr-2018

257 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    1/126

    DESDE UN FRAME O IFRAME SE PIERDER LOS VALORES DESESSION O COOKIESEs posible que al estar dentro de un iframe o frame, al cambiar de pgina, sepierdan los valores de las sessiones o de las cookies con algunos navegadores,por ejemplo, con internet explorer. Para solucionar esto, hay que aadir una lnea,

    justo antes de hacer el cambio de pgina, un ejemplo:

    Session("NUM") = TABLA.Tables("ACCESO").Rows(0)("NUM")

    HttpContext.Current.Response.AddHeader("p3p", "CP=\""IDC DSP COR ADMDEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""")

    Response.Redirect("Datos.aspx")

    Numero de Usuarios en Linea en ASP

    Utilizaremos el Global Asa para contabilizar las personas que tenemos online en la

    web.

    Utilizaremos una variable de session para almacenar los usuarios online.

    Cdigo Fuente:

    sub application_onStart()

    'sentencias que se ejecutan al entrar el primer usuarioapplication("numero_usuarios")=0

    end sub

    sub session_onStart()

    application.lock

    application("numero_usuarios") = application("numero_usuarios") + 1

    application.unlock

    end sub

    sub session_onEnd()

    'sentencias que se ejecutan cada vez que entra un usuarioapplication.lock

    application("numero_usuarios") = application("numero_usuarios") - 1

    application.unlock

    end sub

    Ya tenemos la variable de sesion "numero_usuarios" preparada.

    En la pgina que queramos mostrar el nmero de usuarios online:

    response.write application("numero_usuarios")

    http://trucos-masm2000.blogspot.com/2011/02/desde-un-frame-o-iframe-se-pierder-los.htmlhttp://trucos-masm2000.blogspot.com/2011/02/desde-un-frame-o-iframe-se-pierder-los.htmlhttp://trucos-masm2000.blogspot.com/2011/02/desde-un-frame-o-iframe-se-pierder-los.htmlhttp://trucos-masm2000.blogspot.com/2011/02/desde-un-frame-o-iframe-se-pierder-los.htmlhttp://trucos-masm2000.blogspot.com/2011/02/desde-un-frame-o-iframe-se-pierder-los.html
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    2/126

    How to show number of online users / visitors for ASP.NET website?

    Posted: 24-Mar-2008

    Updated: 8-Apr-2008

    Views: 64166

    There are many ways to count number of active visitors on your ASP.NET website.

    They differ in technique and accuracy.

    here is the simplest approach that delivers acceptable accuracy when configured optimally:

    Step 1:

    - first we need to add these lines to ourglobal.asax file

    (if your website do not have it, create it by right-clicking on website in solution explorer,

    and choosing Add New Item > Global Application Class option)

    void Application_Start(object sender, EventArgs e){

    // Code that runs on application startupApplication["OnlineUsers"] = 0;

    }

    void Session_Start(object sender, EventArgs e){

    // Code that runs when a new session is startedApplication.Lock();Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;Application.UnLock();

    }

    void Session_End(object sender, EventArgs e){

    // Code that runs when a session ends.

    // Note: The Session_End event is raised only when the sessionstatemode

    // is set to InProc in the Web.config file. If session mode is set toStateServer

    // or SQLServer, the event is not raised.Application.Lock();Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;Application.UnLock();

    }

    This will allow us that whenever some distant web visitor opens our website in his browser,and new session is created for him, our "OnlineUsers" variable in the global HttpApplicationState class instanceis increased.

    Also when user closes his browser or does not click on any links in our website, session expires,

    and our "OnlineUsers" global variable is decreased.

    To know more about ApplicationState and HttpApplicationState class visit this MSDN link:

    msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx

    NOTE: we are using Application.Lock and Application.Unlock methods to prevent multiple threadsfrom changing this variable at the same time.

    By calling Application.Lock we are receiving exclusive right to change the values in Application state.But we must not forget to call Application.Unlock() afterwards.

    Step 2:In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our

    web.config file):

    http://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspxhttp://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspxhttp://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    3/126

    In-process mode stores session state values and variables in memory on the local Web server.It is the only mode that supports the Session_OnEnd event that we used previously.

    Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other wordshere we set how long our users can be inactive before considered Offline.

    In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least oncein a 20 minutes, they are considered online.

    If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their sessionis destroyed, so our online visitor counter is decreased by 1.(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

    Ok, so now we are done with configuration steps, let us see how to use this:

    To show number of online visitors/users on your ASPX page you can use this code:

    Visitors online:

    Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and

    use Timer to refresh it in regular intervals without refreshing the whole page, but that is another story

    Found errors in this FAQ? Have a suggestion? Clickhere

    Printer Friendly version of this page

    (Current rating: 4.42 out of 5 for 86 votes)

    Show Comments (17)

    NUMERO DE USUARIOS ONLINE CON ASP.NET 2.0

    Publicado porericghel abril 13, 2009 1 comentario

    A continuacin describiremos como hacer para mostrar el nmero de usuarios que se encuentran

    navegando en nuestro sitio Web (Usuarios Online).

    1.-Agregamos un nuevo elemento a nuestro sitio Web de tipo Clase de aplicacin global que deber de

    tener una extensin .asax

    http://www.aspdotnetfaq.com/SubmitFaq.aspxhttp://www.aspdotnetfaq.com/SubmitFaq.aspxhttp://www.aspdotnetfaq.com/SubmitFaq.aspxhttp://www.aspdotnetfaq.com/PrinterFriendlyFaq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspxhttp://www.aspdotnetfaq.com/PrinterFriendlyFaq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspxhttp://__dopostback%28%27ctl00%24content%24showfaq1%24faqcomments%24lbtogglecomments%27%2C%27%27%29/http://__dopostback%28%27ctl00%24content%24showfaq1%24faqcomments%24lbtogglecomments%27%2C%27%27%29/http://tecnobreros.wordpress.com/author/ericgh/http://tecnobreros.wordpress.com/author/ericgh/http://tecnobreros.wordpress.com/author/ericgh/http://tecnobreros.wordpress.com/2009/04/13/numero-de-usuarios-online-con-aspnet-20/#commentshttp://tecnobreros.wordpress.com/2009/04/13/numero-de-usuarios-online-con-aspnet-20/#commentshttp://tecnobreros.wordpress.com/2009/04/13/numero-de-usuarios-online-con-aspnet-20/#commentshttp://www.addthis.com/bookmark.phphttp://tecnobreros.wordpress.com/2009/04/13/numero-de-usuarios-online-con-aspnet-20/#commentshttp://tecnobreros.wordpress.com/author/ericgh/http://__dopostback%28%27ctl00%24content%24showfaq1%24faqcomments%24lbtogglecomments%27%2C%27%27%29/http://www.aspdotnetfaq.com/Faq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspxhttp://www.aspdotnetfaq.com/PrinterFriendlyFaq/How-to-show-number-of-online-users-visitors-for-ASP-NET-website.aspxhttp://www.aspdotnetfaq.com/SubmitFaq.aspx
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    4/126

    Elemento de tipo Clase global de ASP.NET

    2.- Una vez agregado nos muestra el contenido del archivo con algunos eventos por default.

    3.- Comenzamos a agregar cdigo en el evento Application_Start y quedaria algo como lo siguiente:

    void Application_Start(object sender, EventArgs e)

    {

    // Cdigo que se ejecuta al iniciarse la aplicacin

    Application["activos"] = 0;

    Application["fecha"] = DateTime.Now;

    }

    4.-Agregamos codigo a los eventos Session_Start y Session_End.

    void Session_Start(object sender, EventArgs e)

    {

    // Cdigo que se ejecuta cuando se inicia una nueva sesin

    Application.Lock();

    Application["activos"] = (int)Application["activos"] + 1;

    Application.UnLock();

    }

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    5/126

    void Session_End(object sender, EventArgs e)

    {

    // Cdigo que se ejecuta cuando finaliza una sesin.

    // Nota: El evento Session_End se desencadena slo con el modo sessionstate

    // se establece como InProc en el archivo Web.config. Si el modo de sesin se establece como StateServer

    // o SQLServer, el evento no se genera.

    Application.Lock();

    Application["activos"] = (int)Application["activos"] 1;

    Application.UnLock();

    }

    5.- Por ultimo mostrarmos el numero de usuarios en la pagina aspx que deseemos de la siguente forma:

    lblNumerousuariosOnLine.Text = Application["activos"].ToString();

    Listo !!!, ya tenemos nuestro propio contador de usuarios online.

    asp .net mostrando cuantos usuarios hay online

    bueno lo primero tenemos que crear un archivo global.asax y agregar el siguiente

    codigo

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)

    ' Code that runs when a new session is started

    TryIf IsNumeric(Application.Item("contador")) = False Then

    Application.Item("contador") = 1

    End If

    Dim x1 As Single

    x1 = Val(Application.Item("contador").ToString)

    x1 = x1 + 1

    Application.Item("contador") = x1

    Application.Item("urlref") = Me.Request.UrlReferrer.ToString

    Catch ex As Exception

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    6/126

    End Try

    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)

    ' Code that runs when a session ends.

    ' Note: The Session_End event is raised only when the sessionstate mode

    ' is set to InProc in the Web.config file. If session mode is set to StateServer

    ' or SQLServer, the event is not raised.

    Try

    If IsNumeric(Application.Item("contador")) = False Then

    Application.Item("contador") = 0

    End If

    Dim x1 As Single

    x1 = Val(Application.Item("contador").ToString)

    x1 = x1 - 1Application.Item("contador") = x1

    Catch ex As Exception

    End Try

    End Sub

    que hace cuando se inicia una sesion se sumara a la variable contador +1 cuando el

    servidor genere el timeout hara el -1

    bueno para mostrar los usuarios online es facil basta en el master page o la pagina

    principal

    poner un control label o y asignarle el valor

    Application.Item("contador"))

    Try

    label1.text=Application.Item("contador")) .tostring

    Catch ex As Exception

    label1.text="no anda naiden xD"

    End Try

    apliquen un try por si las moscas

    saludos............

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    7/126

    There are many ways to count number of active visitors on your ASP.NET website.They differ in technique and accuracy.

    here is the simplest approach that delivers acceptable accuracy when configured optimally:

    Step 1:

    - first we need to add these lines to our global.asax file(if your website do not have it, create it by right-clicking on website in solution explorer,and choosing Add New Item > Global Application Class option)

    void Application_Start(object sender, EventArgs e)

    {

    // Code that runs on application startup

    Application["OnlineUsers"] = 0;

    }

    void Session_Start(object sender, EventArgs e)

    {

    // Code that runs when a new session is started

    Application.Lock();

    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;

    Application.UnLock();

    }

    void Session_End(object sender, EventArgs e)

    {

    // Code that runs when a session ends.

    // Note: The Session_End event is raised only when the sessionstatemode

    // is set to InProc in the Web.config file. If session mode is set to

    StateServer

    // or SQLServer, the event is not raised.

    Application.Lock();

    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;

    Application.UnLock();

    }

    This will allow us that whenever some distant web visitor opens our website in his browser,and new session is created for him, our "OnlineUsers" variable in the

    global HttpApplicationState class instanceis increased.

    Also when user closes his browser or does not click on any links in our website, sessionexpires,and our "OnlineUsers" global variable is decreased.

    To know more about ApplicationState and HttpApplicationState class visit this MSDN link:msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx

    NOTE: we are using Application.Lock and Application.Unlock methods to prevent multiplethreadsfrom changing this variable at the same time.

    By calling Application.Lock we are receiving exclusive right to change the values inApplication state.But we must not forget to call Application.Unlock() afterwards.

    http://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspxhttp://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspxhttp://msdn2.microsoft.com/en-us/library/system.web.httpapplicationstate(VS.80).aspx
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    8/126

    Step 2:

    In order for this to work correctly we need to enable sessionstate and configure its modeto InProc value (in our web.config file):

    In-process mode stores session state values and variables in memory on the local Webserver.It is the only mode that supports the Session_OnEnd event that we used previously.

    Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' -in other wordshere we set how long our users can be inactive before considered Offline.

    In this example timeout is set to 20 minutes, so while our visitors click on some links in ourwebsite at least once

    in a 20 minutes, they are considered online.If they do not open any pages on our website longer than 20 minutes, they are consideredOffline, and their sessionis destroyed, so our online visitor counter is decreased by 1.(You can experiment with lower or higher values of Timeout settings to see what is the bestfor your website).

    Ok, so now we are done with configuration steps, let us see how to use this:

    To show number of online visitors/users on your ASPX page you can use this code:

    Visitors online:

    Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel

    control, and

    use Timer to refresh it in regular intervals without refreshing the whole page, but that is

    another story

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    9/126

    Howto Create a Hit Counter Using the Global.asax File in

    ASP.NET 1.x

    If you have a live Web site on the World Wide Web, you may be interested in how many people

    are visiting your site. You can of course analyze the log files of your Web server but that

    information is usually difficult to read. The log files contain information for each and every request

    a visitor has made to your site, including resources like images, Flash movies and so on. This

    makes it near impossible to extract information about individual users. It would be a lot easier if

    you could count the number of individual users that have visited you since you started your site. It

    would also be useful if you could see the number of users that are currently browsing your site.

    This article will show you how to accomplish these two tasks by storing the hit counters in static

    variables using code in the Global.asax file. The disadvantage of this method is that this

    information is lost when you restart the Web server. Two other articles on this site demonstrate

    how to store this information in atext fileand in adatabase, so the value for the counter will be

    preserved when you restart your Web server.

    There is also aClassic ASP versionof this article available

    Prerequisites

    The code in this article uses Sessions in ASP.NET, so you'll need to have them enabled on your

    server, by configuring the element in the Web.config file. Refer to the References

    section at the end of this article for more details.

    You'll also need to have access to a file called Global.asax in the root of your site. If you run your

    own Web server, this is not a problem; you can simply create the file yourself. If you are using an

    ISP, you'll need to check with them if they support the use of the Global.asax file as,

    unfortunately, not all ISPs allow this.

    This article also assumes you're using Visual Studio .NET 2002 or 2003, as it shows code and

    ASPX pages using the Code Behind model. Don't worry if you don't have Visual Studio .NET; it

    should be relatively easy to use the code in your own Code Editor like Macromedia Dreamweaver

    MX or Notepad.

    Counting Users

    One of the easiest ways to count individual users is in the Session_Start event that you can define in

    theGlobal.asax file. This event is fired whenever a user requests the first page in your Web site.

    This way, you have the ability to count each unique visitor only once during their visit. As long as

    the Session remains active on the server, the user won't be counted again. After the Session has

    timed out (it will automatically time out after a certain interval when no new pages have been

    requested) or has been explicitly ended, a request to a page will create a new Session, and the

    user will be counted again.

    To keep track of the total number of users that have visited your site since you started the Web

    server, you can increase a counter for each request a user makes. Let's call this

    counter TotalNumberOfUsers. You can store that counter in a static variable in the Global class.

    This Global class is defined in the file Global.asax.cs, the Code Behind file for Global.asax. By

    creating static variables, you can be sure there is always just one instance of your hit counter

    variable present. Because the class defined in the Global.asax file is accessible throughout the

    entire application, you can retrieve and display the value for the counter on other pages in your

    site.

    You can also create a second counter, called CurrentNumberOfUsers for example, that counts the

    number of active Sessions on your server. Just as with TotalNumberOfUsers, you increase the value of

    this counter whenever a new Session is started. However, you should decrease its value again

    when the Session ends. so you can keep track of the number of users that are currently visiting

    your site.

    http://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/161/howto-create-a-hit-counter-using-the-globalasa-filehttp://imar.spaanjaars.com/161/howto-create-a-hit-counter-using-the-globalasa-filehttp://imar.spaanjaars.com/161/howto-create-a-hit-counter-using-the-globalasa-filehttp://imar.spaanjaars.com/161/howto-create-a-hit-counter-using-the-globalasa-filehttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1x
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    10/126

    Let's take a look at how you can accomplish this:

    You should start by making sure you have a file called Global.asax (note that the extension is

    different from ordinary aspx pages) in the root of your Web site. Usually, when you create a new

    Visual Studio ASP.NET Web Application, the Global.asax file is already there, and the skeleton for

    important events like Session_Startand Session_End are already present.

    If you don't have the file, open the Visual Studio .NET Solution Explorer (Ctrl+Alt+L), right-clickyour Web project and choose Add | Add New Item... from the context menu. Scroll down the list with

    Web Project Items until you see Global Application Class. Alternatively, expand Web Project Items

    and then click Utility to limit the list of Web items. Select the Global Application Class and

    click Open to add the Global.asax file to your Web site project.

    The page will open in Design View so you'll need to click the link "click here to switch to code view" to

    view the Code Behind file for the Global.asax file. You'll see some default using statements,

    followed by the definition for theGlobal class. You'll expand this class by adding a few private

    variables for the two hit counters. These private variables will then be made accessible

    throughpublic properties. Using properties instead of public fields helps keeping your code cleaner

    and more stable. Calling code is not allowed to just arbitrarily change the field's value; it has to

    change the value through a public Set method. In this example, you'll make the code even a bitmore safe by removing the Set method altogether. This makes it impossible for calling code to

    change the value of the counter; all it can do is read its value.

    Modifying Global.asax

    1. Locate the code that starts with public class Global : System.Web.HttpApplication and add the followingshaded lines of code:

    namespace HitCounters

    {

    ///

    /// Summary description for Global./// public class Global : System.Web.HttpApplication{

    private static int totalNumberOfUsers = 0;

    private static int currentNumberOfUsers = 0;

    ///

    /// Required designer variable.

    Whenever the Web application starts, the Global class is constructed and the two hit counters will

    be initialized to 0.

    2. The next step is to add code to the Session_Start event. This event will fire once for each userwhen they request the first page in your Web application, so this place is perfect for your hitcounter. Inside this event, the values of the two hit counters are increased; one for the totalnumber of users and one for the current number of users.Locate the skeleton for the Session_Start event and add the following code:

    protected void Session_Start(Object sender, EventArgs e)

    {

    totalNumberOfUsers += 1;

    currentNumberOfUsers += 1;

    }

    3. Just as with the Session_Start event, you'll need to write some code for the Session_End event.However, instead of increasing the counters, you should decrease the counter for the currentnumber of users only. This means that whenever a user Session times out (usually 20 minutes

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    11/126

    after they requested their last page), the counter will be decreased, so it accurately holds thenumber ofcurrentusers on your site. You should leave the counter for the total number ofusers untouched.Locate the Session_End event, and add this code:

    protected void Session_End(Object sender, EventArgs e){

    currentNumberOfUsers -= 1;

    }

    Making Your Counters Accessible by Other Pages

    Since the hit counters are stored in the Global class, you need some way to get them out of there,

    so you can display them on a management page for example. The easiest way to do this, is to

    create two public properties. Because the Global class is in many respects just an ordinary class, it

    is easy to add public properties to it.

    To add the properties, locate the skeleton for the Application_End event, and add the following code

    right below it:

    protected void Application_End(Object sender, EventArgs e){

    }

    public static int TotalNumberOfUsers

    {get{return totalNumberOfUsers;

    }}

    public static int CurrentNumberOfUsers{

    get

    {

    return currentNumberOfUsers;

    }

    }

    With these two read-only properties in place, your calling code is now able to access the values of

    your hit counters. For example, to retrieve the number of users browsing your site right now, you

    can use this code:HitCounters.Global.CurrentNumberOfUsers where HitCounters is the default namespace

    for your Web application as defined on the Property Pages for the Web project in Visual Studio

    .NET.

    Testing it OutTo test out your hit counters, create a new Web form and call it HitCounter.aspx. You can save

    the form anywhere in your site. In Design View, add two labels to the page and call

    them lblTotalNumberOfUsers andlblCurrentNumberOfUsers respectively. Add some descriptive text before

    the labels, so it's easy to see what value each label will display. You should end up with something

    similar to this in Code View:

    Total number of users since the Web server started:


    Current number of users browsing the site:

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    12/126

    Press F7to view the Code Behind for the hit counter page, and add the following code to

    the Page_Load event:

    private void Page_Load(object sender, System.EventArgs e)

    {

    int currentNumberOfUsers = HitCounters.Global.CurrentNumberOfUsers;

    int totalNumberOfUsers = HitCounters.Global.TotalNumberOfUsers;

    lblCurrentNumberOfUsers.Text = currentNumberOfUsers.ToString();

    lblTotalNumberOfUsers.Text = totalNumberOfUsers.ToString();

    }

    The first two lines of code retrieve the total number of visitors and the current number of visitors

    from theGlobal class. The next two lines simply display the values for the counters on the

    appropriate labels on the page.

    To test it out, save the page and view it in your browser. You'll see there is one current user. Also,

    note that the total number of users is 1. Open another browser (don't use Ctrl+N, but start a freshinstance or use an entirely different brand of browser) and open the counter page. You'll see there

    are two current users, and two users in total. Wait until both the Sessions have timed out (the

    default timeout defined in Web.config is 20 minutes) and open the hit counter page again. You'll

    see there is one current user, but the total number of users has been maintained and should be 3.

    Summary

    This article demonstrated how to create a hit counter that keeps track of the current and total

    number of users to your site. It stores these counters in static variables in the Global class so they

    are available in each page in your Web site. A big disadvantage of storing these variables in static

    variables is that their values get lost when the Web server is restarted.

    Two other articles on this site will demonstrate how you can save the counter value for the totalnumber of users in a text file or in a database. By saving the counter to a text file or database, its

    value can be maintained, even when you restart or reboot the Web server.

    Howto Create a Hit Counter Using a Text File inASP.NET(http://Imar.Spaanjaars.Com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1x)

    Howto Create a Hit Counter Using a Database inASP.NET (http://Imar.Spaanjaars.Com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharp)

    Related Articles

    Howto Create a Hit Counter Using a Text File in ASP.NET 1.x

    If you have a live Web site on the World Wide Web, you may be interested in how many people

    are visiting your site. You can of course analyze the log files of your Web server but that

    information is usually difficult to read. The log files contain information for each and every request

    a visitor has made to your site, including resources like images, Flash movies and so on. This

    makes it near impossible to extract information about individual users. It would be a lot easier if

    you could count the number of individual users that have visited you since you started your site. It

    would also be useful if you could see the number of users that are currently browsing your site.

    This article will show you how to accomplish these two tasks by storing the hit counters in static

    variables in theGlobal class and in a text file using code in the Global.asax file. This article

    extends the ideas from aprevious articlewhere the values of the counters were just stored in static

    http://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-c-sharphttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1x
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    13/126

    variables. By writing the counters to a file you can maintain their values, even when you restart

    the Web server.

    There is also aClassic ASP versionof this article available.

    Prerequisites

    The code in this article uses Sessions in ASP.NET, so you'll need to have them enabled on your

    server, by configuring the element in the Web.config file. Refer to the

    References section at the end of this article for more details.

    You'll also need to have access to a file called Global.asax in the root of your site. If you run your

    own Web server, this is not a problem; you can simply create the file yourself. If you are using an

    ISP, you'll need to check with them if they support the use of the Global.asax file as,

    unfortunately, not all ISPs allow this.

    You'll also need to be able to write to a text file from within the Global.asax file. This means that

    the account your Web site is running under (usually, the ASPNET account) needs sufficient

    permissions to write to the file.

    Finally, this article assumes you're using Visual Studio .NET 2002 or 2003, as it shows code andASPX pages using the Code Behind model. Don't worry if you don't have Visual Studio .NET; it

    should be relatively easy to use the code in your own Code Editor like Macromedia Dreamweaver

    MX or Notepad.

    Counting Users

    Just as in the article where the counters were stored in the Global class, you can make use of

    theSession_Start event, defined in the Global.asax file to keep track of your users. This event

    is fired for every user whenever they request the first page in your Web site. This way, you have

    the ability to count each unique visitor only once during their visit. As long as the Session remains

    active on the server, the user won't be counted again. After the Session has timed out (it will

    automatically time out after a certain interval when no new pages have been requested) or has

    been explicitly ended, a request to a page will create a new Session,Session_Start will fire and

    the user will be counted again.

    To keep track of the total number of users that have visited your site since you started the Web

    server, you can increase a counter for each request a user makes. Let's call this

    counter totalNumberOfUsers. You can store that counter in a static variable in the Global class,

    so you can retrieve and display it on other pages in your site. You can also create a second

    counter, called currentNumberOfUsers for example, that counts the number of active Sessions on

    your server. Just as with totalNumberOfUsers, you increase the value of this counter whenever a

    new Session is started. However, you should decrease its value again when the Session ends. so

    you can keep track of the number of users that are currently visiting your site.

    Besides storing these values in the Global class, you can also write the valueoftotalNumberOfUsers to a text file, so its values will survive server restarts. When your server

    is restarted, code in the Global.asax file will read in the old value from the text file, so your

    counter will continue with the value it had before the restart. Don't underestimate the problem of

    restarting your Web server. Even if you have your stable Windows 2003 box running for months

    without a reboot, the newIIS Process Recyclingfeature may restart your Web application every day

    or even every few hours.

    You should start by making sure you have a file called Global.asax (note that the extension is

    different from ordinary aspx pages) in the root of your Web site. Usually, when you create a new

    Visual Studio ASP.NET Web Application, the Global.asax file is already there, and the skeleton for

    important events like Session_Startand Session_End are already present in its Code Behind file.

    If you don't have the file, open the Visual Studio .NET Solution Explorer (Ctrl+Alt+L), right-click

    your Web project and choose Add | Add New Item... from the context menu. Scroll down the list with

    http://imar.spaanjaars.com/164/howto-create-a-hit-counter-using-a-text-filehttp://imar.spaanjaars.com/164/howto-create-a-hit-counter-using-a-text-filehttp://imar.spaanjaars.com/164/howto-create-a-hit-counter-using-a-text-filehttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://imar.spaanjaars.com/164/howto-create-a-hit-counter-using-a-text-file
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    14/126

    Web Project Items until you see Global Application Class. Alternatively, expand Web Project Items

    and then click Utility to limit the list of Web items. Select the Global Application Class and

    click Open to add the Global.asax file to your Web site project.

    The page will open in Design View so you'll need to click the link "click here to switch to code view" to

    view the Code Behind file for the Global.asax file. You'll see some default using statements,

    followed by the definition for theGlobal class. I'll show you how to expand this class in theremainder of this article by adding a few private variables for the two hit counters. These private

    variables will then be made accessible throughpublic properties. Using properties instead of public

    fields helps keeping your code cleaner and more stable. Calling code is not allowed to just

    arbitrarily change the field's value; it has to change the value through a public Setmethod. In this

    example, you'll make the code even a bit more safe by removing the Set method altogether. This

    makes it impossible for calling code to change the value of the counter; all it can do is read its

    value.

    Modifying Global.asax

    1. Locate the code that starts with public class Global : System.Web.HttpApplication andadd the following shaded lines of code:

    namespace HitCounters

    {

    ///

    /// Summary description for Global.

    /// public class Global : System.Web.HttpApplication{

    private static int totalNumberOfUsers = 0;

    private static int currentNumberOfUsers = 0;

    ///

    /// Required designer variable.

    2. The code that writes the counters to a file, makes use of theStreamWriterclass. This class islocated in theSystem.IOnamespace, so you'll need to add a reference to this namespace byadding a usingstatement, at the top of the page somewhere below theother using statements:

    using System.ComponentModel;using System.Web;using System.Web.SessionState;

    using System.IO;

    3. The next step is to add code to the Session_Start event. This event will fire once when a userrequests the first page in your Web application, so this place is perfect for your hit counter.Inside this event, the values of the two hit counters are increased; one for the total number ofusers and one for the current number of users. Once the values are increased, the valueoftotalNumberOfUsers is written to a text file.

    Locate the skeleton for the Session_Start event and add the following code:

    protected void Session_Start(Object sender, EventArgs e){

    totalNumberOfUsers += 1;

    currentNumberOfUsers += 1;

    string counterFile = Server.MapPath("/Counter.txt");

    if (File.Exists(counterFile)){

    File.Delete(counterFile);

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamWriterClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamWriterClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamWriterClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemio.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemio.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemio.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemio.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamWriterClassTopic.asp
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    15/126

    }StreamWriter sw = File.CreateText(counterFile);

    sw.WriteLine ("Total\t" + totalNumberOfUsers);

    sw.Close();

    }

    4. Just as with the Session_Start event, you'll need to write some code for

    the Session_End event. However, instead of increasing the counters, you should decrease thecounter for the current number of users only. This means that whenever a user Session timesout (usually 20 minutes after they requested their last page), the counter will be decreased, soit accurately holds the number ofcurrentusers on your site. You should leave the counter forthe total number of users untouched.Locate the Session_End event, and add this line of code:

    protected void Session_End(Object sender, EventArgs e){

    currentNumberOfUsers -= 1;

    }

    How It WorksThe code that runs in the Session_Start event performs a few important steps; first of all, the

    values for the two hit counters are increased. Next, the code checks whether the counter file is

    already present. If it is, it gets deleted by calling the static Deletemethod of theFileclass. Then a

    new text file is created and the value of thetotalNumberOfUsers is written to this new file,

    preceded by the word Total and a Tab character.

    The code that runs in the Session_End event simply decreases the value of the current number of

    users. There is no need to touch the counter for the total number of users.

    Making Your Counters Accessible by Other Pages

    Since the hit counters are stored in the Global class, you need some way to get them out ofthere, so you can display them on a management page for example. The easiest way to do this, is

    to create two public properties. Because the Global class is in many respects just an ordinary

    class, it is easy to add public properties to it.

    To add the properties, locate the skeleton for the Application_End event, and add the following

    code just below it:

    protected void Application_End(Object sender, EventArgs e){

    }

    public static int TotalNumberOfUsers{

    get

    {

    return totalNumberOfUsers;}

    }

    public static int CurrentNumberOfUsers{get{

    return currentNumberOfUsers;

    }

    }

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclassdeletetopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclassdeletetopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclassdeletetopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemiofileclassdeletetopic.asp
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    16/126

    With these two read-only properties in place, your calling code is now able to access the values of

    your hit counters. For example, to retrieve the number of users browsing your site right now, you

    can use this code:HitCounters.Global.CurrentNumberOfUserswhere HitCounters is the default

    namespace for your Web application as defined on the Property Pages for the Web project in

    Visual Studio .NET.

    Reading the Counter When the Web Server StartsAs long as the Web server keeps running, this code will run fine. For each new Session that is

    created, the counters are increased by one and the value oftotalNumberOfUsers is written to the

    file. If, however, the Web server stops unexpectedly, or your restart or reboot the Web server

    yourself, the values fortotalNumberOfUsers and currentNumberOfUsers are lost. But because the

    value for totalNumberOfUsershas also been stored in a text file, it's easy to retrieve the counter

    again from that file when the Web server starts. To read in the value from the Counter.txt file,

    you'll need to add some code to the Application_Startevent that is also defined in

    the Global.asax file:

    protected void Application_Start(Object sender, EventArgs e){

    int counterValue = 0;string counterFile = Server.MapPath("/Counter.txt");

    if (File.Exists(counterFile)){

    using (StreamReader sr = new StreamReader(counterFile))

    {string result = sr.ReadLine();if (result != null){string delimStr = "\t";char [] delimiter = delimStr.ToCharArray();

    string [] arrResult = null;

    arrResult = result.Split(delimiter);

    if (arrResult.Length == 2)

    {counterValue = Convert.ToInt32(arrResult[1]);

    }

    }

    }

    }

    totalNumberOfUsers = counterValue;

    }

    This code may look a bit complicated, but it's actually rather simple. AStreamReaderobject (sr)

    is used to read in a file. The StreamReader class defines a methodReadLineto read in a file line

    by line. Since all you're interested in is the first line, this method is called just once. If the file is

    empty, this method returns null, so you'll need to check for that. If line equals null, the code in

    the if block will not run, and the counter will get its default value of 0 (from the local

    variable counterValue). IfReadLine does return a string, the code in the if block willrun.

    The string result is then split into two elements by splitting on a Tab character (\t). If you look

    at the code that writes to the file in the beginning of this article, you can see that the word Total,

    then a Tab and then the value of the counter are written to the file. Since all you're interested in is

    the value for the counter, you'll need to split the line in two elements; both sides of the Tab

    character. Because theSplitmethod of the String class requires a char array that defines the

    character to split on, you'll need the additional step of converting delimStr to the

    array delimiter which can then be passed to the Split method of the string result.

    If the Length of the array equals 2 you can be sure you read in a valid line. The second

    element,arrResult[1], is then used as the value for the local variable counterValue, by

    converting it to an int usingConvert.ToInt32.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassReadLineTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassReadLineTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassReadLineTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclasssplittopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclasssplittopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclasssplittopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclasssplittopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassReadLineTopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemIOStreamReaderClassTopic.asp
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    17/126

    At the end of the code block, the static variable totalNumberOfUsers gets the value of

    counterValue, which holds either 0 or the value retrieved from the Counter file.

    It would have been easier to leave out the TOTAL in the text file, so there is no need to split the

    line of text you retrieved from the file. I did include it in this example though, because it can be

    useful if you want to store multiple counters in the same text file. This way, you can saveindividual counters as TOTALUSERS, TOTALDOWNLOADS and so on all in the same file, while you

    can still see which value means what.

    Testing it Out

    To test out your hit counters, create a new Web form and call it HitCounter.aspx. You can save

    the form anywhere in your site. In Design View, add two labels to the page and call

    them lblTotalNumberOfUsers andlblCurrentNumberOfUsers respectively. Add some descriptive

    text before the labels, so it's easy to see what value each label will display. You should end up

    with something similar to this in Code View:

    Total number of users since the Web server started:


    Current number of users browsing the site:


    Press F7to view the Code Behind for the hit counter page, and add the following code to

    the Page_Load event:

    private void Page_Load(object sender, System.EventArgs e){

    int currentNumberOfUsers = HitCounters.Global.CurrentNumberOfUsers;int totalNumberOfUsers = HitCounters.Global.TotalNumberOfUsers;lblCurrentNumberOfUsers.Text = currentNumberOfUsers.ToString();

    lblTotalNumberOfUsers.Text = totalNumberOfUsers.ToString();

    }

    The first two lines of code retrieve the total number of visitors and the current number of visitors

    from theGlobal class. The next two lines simply display the values for the counters on the

    appropriate labels on the page.

    To test it out, save the page and open it in your browser. You'll see there is one current user. Also,note that the total number of users is 1. Open another browser (don't use Ctrl+N, but start a fresh

    instance or use an entirely different brand of browser) and open the counter page. You'll see there

    are two current users, and two users in total. Wait until both the Sessions have timed out (the

    default timeout defined in Web.config is 20 minutes) and open the hit counter page again. You'll

    see there is one current user, but the total number of users has been maintained and should be 3.

    Summary

    This article demonstrated how to create a hit counter that keeps track of the current and total

    number of users to your site. It stores these counters in static variables in the Global class so

    they are available in each page in your Web site. It also stores the value for the total number of

    users in a text file so its value won't be lost when the Web server restarts.

    A disadvantage of using text files is that it's difficult to scale out your Web site to lots of users.

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    18/126

    Only one user has access to the file at any given moment, so if you have a real busy site, you'll

    soon run into problems.

    Take a look at the following article to see how you can improve the counter page even further by

    using a database instead of a text file.

    Howto Create a Hit Counter Using a Database in ASP.NET 1.x

    with C#If you have a live Web site on the World Wide Web, you may be interested in how many people

    are visiting your site. You can of course analyze the log files of your Web server but that

    information is usually difficult to read. The log files contain information for each and every request

    a visitor has made to your site, including resources like images, Flash movies and so on. This

    makes it near impossible to extract information about individual users. It would be a lot easier if

    you could count the number of individual users that have visited you since you started your site. It

    would also be useful if you could see the number of users that are currently browsing your site.

    This article will show you how to accomplish these two tasks by storing the hit counters in sharedvariables in theGlobal class and in a database using code in the Global.asax file. The counters in

    the shared variables are used to display them on a page in your Web site; either as a counter so

    your visitors can see it as well, or somewhere on a page in your Admin section, so only you have

    access to them. By writing the counters to a database you can maintain their value even when you

    restart the Web server, while you still have a fast and scalable solution.

    This article extends the ideas from two previous articles where the values of the counters were

    just stored instatic variables in the Global classand in atext file.

    There are alsoClassic ASP andVB.NETversions of this article available.

    PrerequisitesThe code in this article uses Sessions in ASP.NET, so you'll need to have them enabled on your server,by configuring the element in the Web.config file. Refer to the References section atthe end of this article for more details.You'll also need to have access to a file called Global.asax in the root of your site. If you run your ownWeb server, this is not a problem; you can simply create the file yourself. If you are using an ISP, you'llneed to check with them if they support the use of the Global.asax file as, unfortunately, not all ISPs

    allow this.

    You'll also need to be able to write to and read from a database from within the Global.asax file. Thismeans that the account your Web site is running under (usually, this is the ASPNET account) needssufficient permissions to write to the database file and the folder it resides in.

    Finally, this article assumes you're using Visual Studio .NET 2002 or 2003, as it shows code and ASPXpages using the Code Behind model. Don't worry if you don't have Visual Studio .NET; it should be

    relatively easy to use the code in your own Code Editor like Macromedia Dreamweaver MX or Notepad.

    Counting Users

    Just as in the article where the counters were stored in the Global class, you can make use of

    theSession_Start event, defined in the Global.asax file to keep track of your users. This event is fired

    whenever a user requests the first page in your Web site. This way, you have the ability to count eachunique visitor only once during their visit. As long as the Session remains active on the server, the userwon't be counted again. After the Session has timed out (it will automatically time out after a certaininterval when no new pages have been requested) or has been explicitly ended, a request to a page willcreate a new Session, Session_Start will fire and the user will be counted again.

    To keep track of the total number of users that have visited your site since you started the Web server,

    you can increase a counter for each request a user makes. Let's call this counter totalNumberOfUsers.You can store that counter in a static variable in the Global class, so you can retrieve and display it on

    other pages in your site. You can also create a second counter, called currentNumberOfUsers for

    http://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/261/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-vbnethttp://imar.spaanjaars.com/261/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-vbnethttp://imar.spaanjaars.com/261/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-vbnethttp://imar.spaanjaars.com/261/howto-create-a-hit-counter-using-a-database-in-aspnet-1x-with-vbnethttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1x
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    19/126

    example, that counts the number of active Sessions on your server. Just as with totalNumberOfUsers,you increase the value of this counter whenever a new Session is started. However, you should decreaseits value again when the Session ends. so you can keep track of the number of users that are currentlyvisiting your site.

    Besides storing these values in the Global class, I'll show you how to save them in a database, so the

    value for the counter is preserved, even when the Web server is stopped and restarted. When your

    server is restarted, code in the Global.asax file will read in the old value from the database, so yourcounter will continue with the value it had before the restart. Don't underestimate the problem ofrestarting your Web server. Even if you have your stable Windows 2003 box running for months withouta reboot, the newIIS Process Recyclingfeature may restart your Web application every day or evenevery few hours.

    This example uses a Microsoft Access database that is called Website.mdb. The database has just one

    single table called Counters. This table has two columns called CounterType and NumberOfHits.

    The CounterTypecolumn defines the type of counter you want to store in the database. The table looksas follows:

    Figure 1 - The Counters Table

    In this example, the type of counter will be UserCounter, to indicate you are counting users. You can

    expand on this example and count individual pages, for example. In that case, you could store the pagename in theCounterType column to indicate which page you are tracking.

    The NumberOfHits column will hold the number of hits for the counter. In this example, it stores thenumber of visitors to your site.

    The code assumes that you have saved this database (which is available in the code download for thisarticle) in a folder called C:\Databases. If you decide to store your database at a different location,

    make sure you adjust the path in the code that references the database. You'll also need to make surethat the ASPNET account has sufficient permissions to both the database and the folder Databases.

    Once you have set up the database, you should make sure you have a file called Global.asax (note that

    the extension is different from ordinary aspx pages) in the root of your Web site. Usually, when you

    create a new Visual Studio ASP.NET Web Application, the Global.asax file is already there, and the

    skeleton for important events like Session_Start and Session_End are already present in its CodeBehind file.

    If you don't have the file yet, open the Visual Studio .NET Solution Explorer (Ctrl+Alt+L), right-click yourWeb project and choose Add | Add New Item... from the context menu. Scroll down the list with WebProject Items until you see Global Application Class. Alternatively, expand Web Project Items and thenclick Utility to limit the list of Web items. Select the Global Application Class and click Open to addthe Global.asax file to your Web site project.

    The page will open in Design View so you'll need to click the link "click here to switch to code view" to viewthe Code Behind file for the Global.asax file. You'll see some default using statements, followed by the

    definition for theGlobal class. I'll show you how to expand this class in the remainder of this article by

    adding a few private variables for the two hit counters. These private variables will then be madeaccessible throughpublic properties. Using properties instead of public fields helps keeping your codecleaner and more stable. Calling code is not allowed to just arbitrarily change the field's value; it has tochange the value through a public Setmethod. In this example, you'll make the code even a bit more

    safe by removing the Set method altogether. This makes it impossible for calling code to change thevalue of the counter; all it can do is read its value.

    Modifying Global.asax

    http://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspxhttp://msdn2.microsoft.com/en-us/library/ms525803.aspx
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    20/126

    1. Locate the code that starts with public class Global : System.Web.HttpApplication andadd the following shaded lines of code:

    namespace HitCounters

    {

    ///

    /// Summary description for Global.

    /// public class Global : System.Web.HttpApplication{

    private static int totalNumberOfUsers = 0;

    private static int currentNumberOfUsers = 0;

    ///

    /// Required designer variable.

    2. The code that writes the counters to the database, makes use of objects liketheOleDbConnection, located inSystem.Data.OleDbnamespace, so you'll need to add areference to this namespace by adding a using statement, at the top of the page somewhere

    below the other using statements:

    using System.ComponentModel;using System.Web;using System.Web.SessionState;

    using System.Data.OleDb;

    3. The next step is to add code to the Session_Start event. This event will fire once for each userwhen they request the first page in your Web application, so this place is perfect for your hitcounters. Inside this event, the values of the two hit counters are increased; one for the totalnumber of users and one for the current number of users. Once the values are increased, thevalue of

    totalNumberOfUserswill be written to the database as well.

    Locate the skeleton for the Session_Start event and add the following code:

    protected void Session_Start(Object sender, EventArgs e)

    {

    // Increase the two counters.totalNumberOfUsers += 1;currentNumberOfUsers += 1;

    // Save the Total Number of Users to the database.

    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;

    Data Source=C:\Databases\Website.mdb;

    User ID=Admin;Password=";

    string sql = @"UPDATE Counters SET NumberOfHits = "

    + totalNumberOfUsers + " WHERE CounterType = 'UserCounter'";

    OleDbConnection conn = new OleDbConnection(connectionString);

    OleDbCommand cmd = new OleDbCommand(sql, conn);

    // Open the connection, and execute the SQL statement.

    cmd.Connection.Open(); cmd.ExecuteNonQuery();

    cmd.Connection.Close();

    }

    http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdataoledboledbconnectionclasstopic.asphttp://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdataoledboledbconnectionclasstopic.asphttp://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdataoledboledbconnectionclasstopic.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledb.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledb.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledb.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoledb.asphttp://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdataoledboledbconnectionclasstopic.asp
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    21/126

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    22/126

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    23/126

    value from theNumberOfHits column is stored in the private variable called totalNumberOfUsers.

    The GetInt32 method makes sure the value is retrieved as an int. If the counter is not found, the

    private variable is reset to 0. (Note that it is unlikely that the record is not found, as it is defined in thedatabase. If you ever delete this record, theUPDATE statement that sets the counter in

    the Session_Start will not run correctly, because it expects the record to be present).

    At the end, the OleDbDataReader and the Connection are closed. This is good practice, as leaving

    DataReaders and Connections open can severely limit the number of concurrent users your site canserve.

    Testing it Out

    To test out your hit counters, create a new Web form and call it HitCounter.aspx. You can save theform anywhere in your site. In Design View, add two labels to the page and callthem lblTotalNumberOfUsers andlblCurrentNumberOfUsers respectively. Add some descriptive textbefore the labels, so it's easy to see what value each label will display. You should end up withsomething similar to this in Code View:

    Total number of users since the Web server started:

    Current number of users browsing the site:


    Press F7to view the Code Behind for the hit counter page, and add the following code tothe Page_Load event:

    private void Page_Load(object sender, System.EventArgs e){

    int currentNumberOfUsers = HitCounters.Global.CurrentNumberOfUsers;int totalNumberOfUsers = HitCounters.Global.TotalNumberOfUsers;lblCurrentNumberOfUsers.Text = currentNumberOfUsers.ToString();lblTotalNumberOfUsers.Text = totalNumberOfUsers.ToString();

    }

    The first two lines of code retrieve the total number of visitors and the current number of visitors fromtheGlobal class. The next two lines simply display the values for the counters on the appropriate labelson the page.

    To test it out, save the page and view it in your browser. You'll see there is one current user. Also, notethat the total number of users is 1. Open another browser (don't use Ctrl+N, but start a fresh instanceor use an entirely different brand of browser) and open the counter page. You'll see there are twocurrent users, and two users in total.

    Next, restart your Web server. If you are using IIS, you can choose Restart IIS... from the AllTasks context menu for your Web server in the IIS Management Console. Alternatively, you canrecompile your application in Visual Studio .NET. Whenever you do a recompile, the Web application willrestart automatically.Open HitCounter.aspx again. You'll see that currently you're the only user browsing the site, but thetotal number of users has maintained its value.

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    24/126

    Summary

    This article demonstrated how to create a hit counter that keeps track of the current and total number ofusers to your site. It stores these counters in static variables in the Global class so they are available ineach page in your Web site. It also stores the value for the total number of users in a database so itsvalue won't be lost when the Web server restarts, either unexpectedly, or on purpose.

    By using a database, you have created a solution that can easily be scaled to lots of users. If you have areal busy Web site, you can change the code from this article so it uses a real Database ManagementSystem, like Microsoft SQL Server or Oracle. These kind of work beasts can easily serve thousands andthousands of users a day allowing for lots of concurrent users.

    Related Articles

    When Sessions End - Once And For All!atwww.asp101.com(http://www.asp101.com/articles/john/sessionsend/default.asp)

    Howto Create a Hit Counter Using a Text File inASP.NET(http://Imar.Spaanjaars.Com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1x)

    Howto Create a Hit Counter Using the Global.asax file in

    ASP.NET(http://Imar.Spaanjaars.Com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1x)

    Howto Create a Hit Counter Using a Database ("Classic ASP"version)(http://Imar.Spaanjaars.Com/165/howto-create-a-hit-counter-using-a-database

    References

    Configuring ASP.NET Applications to Use the Appropriate SessionState(http://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspx)

    Element(http://msdn.microsoft.com/library/en-us/cpgenref/html/gngrfsessionstatesection.asp)

    Download Files

    Source Code for thisArticle(http://Imar.Spaanjaars.Com/Downloads/Articles/HitCounterInDatabaseASPNET.zip)

    Source Code for this Article for Visual Studio2008(http://Imar.Spaanjaars.Com/Downloads/Articles/HitCounterInDatabaseASPNET2008.zip)

    http://www.asp101.com/articles/john/sessionsend/default.asphttp://www.asp101.com/articles/john/sessionsend/default.asphttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://msdn.microsoft.com/library/en-us/cpgenref/html/gngrfsessionstatesection.asphttp://msdn.microsoft.com/library/en-us/cpgenref/html/gngrfsessionstatesection.asphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET2008.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://imar.spaanjaars.com/Downloads/Articles/HitCounterInDatabaseASPNET.ziphttp://msdn.microsoft.com/library/en-us/cpgenref/html/gngrfsessionstatesection.asphttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://technet2.microsoft.com/WindowsServer/en/Library/51aa77d2-4485-4cb9-a75f-9186dc5d775f1033.mspxhttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/165/howto-create-a-hit-counter-using-a-databasehttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/227/howto-create-a-hit-counter-using-a-text-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://imar.spaanjaars.com/223/howto-create-a-hit-counter-using-the-globalasax-file-in-aspnet-1xhttp://www.asp101.com/articles/john/sessionsend/default.asp
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    25/126

    Requiring Users to Confirm their E-mail Address after they

    Create an AccountOver the past couple of weeks I received a number of e-mails from readers with more or less the samequestion: how do you require users to confirm their e-mail addresses before they are allowed to log inwith an account they just created. Rather than answer them individually by e-mail, I decided to write

    this article to explain the principles.

    Introduction

    In this article Ill show you how you can let users sign up for an account that they need to confirm firstbefore they can sign in with it. By using the standard ASP.NET features for account management(Membership, theCreateUserWizard control, built-in e-mail sending capabilities), it turns out this ispretty easy to do. Heres a short rundown of all the required steps:

    1. Configure Membership, create a page using the standard CreateUserWizard control that sendsout a standard e-mail with the user name and password.

    2. Disable the account when it is is created so users can't log in until they confirm their e-amailaddress.

    3. When the account is created, generate a unique ID for the user, save it the users profile, and

    then customize the e-mail message by including a link to a confirmation page that includes thisunique ID.4. When the user clicks the confirmation link in the e-mail, retrieve the unique ID from the query

    string and use it to validate the account and approve the user.

    Ill dig a little deeper into each step in the following sections. Youll find the fu ll source code for the demoapplication at the end of the article. This article was written using Visual Studio 12 and SQL ServerLocalDB. However, if you follow the instructions and create a new site from scratch, it would equallywork in Visual Studio 2008 and 2010.

    1. Setting the Stage

    The first thing you need to do is modify your site so users can sign up for an account. This part is prettysimple and is identical to what you would normally do. I wont describe this part in detail but instead

    describe the steps I followed to set up the demo site.

    1. Create a new web site or web application in Visual Studio (the source you can download is for aweb site project).

    2. Set up Membership by executing the following NuGet command:

    Install-Package Microsoft.AspNet.Providers

    3. Create a page that contains a CreateUserWizard control so users can sign up for an account.

    This page is called SignUp.aspx in the sample application.

    4. Create an e-mail message body in the App_Data folder that contains text to welcome the user.

    You can use the standard and placeholders to inject the username and password. For example:

    Dear

    Your account has been created. Please find your account details below:

    Username: Password:

    This file is saved as ~/App_Data/YourNewAccount.txt in the sample application.

    5. Set up the MailSettings element on the CreateUserWizard control so it uses this mailtemplate like this:

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    26/126

    6. Configure the system.net element in Web.config so it can successfully send out e-mail. In thesample application I am using alocal pickup folder.

    (seehttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryfor moredetails).7. Create a page with a Login control so users can sign in to your site. In the sample application,

    this page is called Login.aspx.8. Test the application. For each account you create you should receive an e-mail. You should be

    able to log in using the user name and password you supplied.

    2. Disabling Created Users

    This step is really easy because the CreateUserWizard has built-in support for this. All you need to do issetDisableCreatedUser to True, like this:

    With this setting on, you should no longer be able to log om with new new accounts you create on the

    site.

    3. Inserting a Confirmation Link in the E-mail Message

    This action consists of a few steps:

    1. Generate a unique ID for the user and store it in the users profile. A good location to dothis is in the CreateUserWizardsCreatedUser event, like this:

    2. protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e){ProfileCommon userProfile =

    ProfileCommon.Create(CreateUserWizard1.UserName) as ProfileCommon;accountConfirmationKey = Guid.NewGuid().ToString();userProfile.AccountConfirmationKey = accountConfirmationKey;userProfile.Save();

    }

    For this code to work, I added the following profile property to Web.config:

    Notice how the code explicitly creates a profile using ProfileCommon.Create. Since the user

    account has just been created, Profile is not active for the current page yet so you need to

    get it explicitly. This also means you need to call Save. The random ID (created

    using Guid.NewGuid()) is stored in the users profile and in a field in the class so you can use it

    when sending the e-mail, discussed next.

    3. Modify the outgoing message. The CreateUserWizard has a handy SendingMail event you

    can hook into to customize the e-mail. You access the MailMessage instance on

    the e.Messageproperty. Heres the code from the sample application that builds up a link to the

    current web site, embeds the unique user ID, and then adds the link to the MailMessagesbody:

    4. protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgse)

    http://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-deliveryhttp://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-delivery
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    27/126

    5. {string confirmLink =

    6. string.Format("{0}://{1}/Confirm.aspx?ConfirmationKey={2}&UserName={3}",7. Request.Url.Scheme, Request.Url.Authority, accountConfirmationKey,8. CreateUserWizard1.UserName);

    e.Message.Body = e.Message.Body.Replace("##ConfirmLink##", confirmLink);}

    Note: I could have combined the code in the CreatedUser and SendingMail events into a

    single block called from SendingMail. However, separating it like this feels a bit cleaner.

    9. Modify the e-mail body to include a placeholder for the link. Heres the full text for thatmessage from the sample application:

    10.Dear ,11.12.Your account has been created. However, before you can use it you need to confirm13.your e-mail address first by clicking the following link:14.15.#ConfirmLink##16.17.Please find your account details below:18.19.Username:

    Password:

    20. Change the CompleteSuccessText property of the CreateUserWizardcontrol to inform

    the user the account is not activated immediately, but needs manual confirmation first.Heres the full code for theCreateUserWizard:

    21.

    When users now sign up for a new account, they receive something like the following in their

    Inbox:

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    28/126

    4. Activating the User Account

    When the user clicks the confirmation link in the e-mail message, he's being sent tothe Confirm.aspx page, along with the confirmation ID and UserName in the query string. A typical linkcould look like this:

    http://localhost:6864/Confirm.aspx?ConfirmationKey=ef05127f-a050-41b9-9132-be8a8aeea925&UserName=Imar

    The localhost:6864 part varies depending on where you run this code, and would include your fulldomain name when used on a production site.

    In the code behind ofContfirm.aspx, you then get the user name from the query string and use it to

    create aProfile instance. This profile instance should have a value for

    the AccountConfirmationKey property that matches the confirmation key sent in the query string. If

    the two match, you can create a MembershipUser for the requested user name and activate the account

    by setting IsApproved to true. Heres the code from the sample application that shows a way you canimplement this:

    protected void Page_Load(object sender, EventArgs e){string userName = Request.QueryString.Get("UserName");string accountKey = Request.QueryString.Get("ConfirmationKey");

    var profile = ProfileCommon.Create(userName) as ProfileCommon;if (accountKey == profile.AccountConfirmationKey){var user = Membership.GetUser(userName);user.IsApproved = true;Membership.UpdateUser(user);Status.Text = "Account confirmed successfully.";

    }else{Status.Text = "Something went wrong while confirming your account.";

    }}

  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    29/126

    As you can see, implementing this functionality is pretty straightforward, as most of what you need issupported out of the box. Hooking into some events to customize behavior is a great way to makemodifications to existing functionality without building your own security system from scratch.

    Extending the Sample

    The sample application that comes with this article is pretty simple so its easy to focus on the concept

    without getting confused by too many details. For a real-world website, you may want to implement thefollowing features:

    Key expiration. Along with the unique ID you could save the date and time the key wasgenerated in the profile as well. Then when the key is validated in Confirm.aspx you couldcheck this date and decide not to activate the user when the key has expired.

    If you dont like sending the user name and password over e-mail and the query string, youcould leave them out of the mail message. Then in Confirm.aspx you could add a TextBox and

    a Button so the user can manually enter their user name and click a confirm button. In the

    Code Behind you would replace the code that gets the user name from the query string withcode that gets it from the text box.

    Downloads

    The full source code for this application (C# only)

    Where to Next?

    Wonder where to go next? You can read existing comments below or you can post acommentyourselfon this article .

    http://imar.spaanjaars.com/Downloads/Articles/ConfirmAccountAfterSignup.ziphttp://imar.spaanjaars.com/Downloads/Articles/ConfirmAccountAfterSignup.ziphttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account#Feedbackhttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account#Feedbackhttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account#Feedbackhttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account#Feedbackhttp://imar.spaanjaars.com/Downloads/Articles/ConfirmAccountAfterSignup.zip
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    30/126

    Approving Users and Assigning them to Roles After They Sign

    Up for an Account

    Back in July I wrotean article that showed how you can require your users to confirm their e-mail

    addressesbefore they can access your site after signing up for a new account. In this article I

    describe a similar but slightly different technique where an administrator of the site can approve

    the account before the user gains access to the site.

    Approving Users

    If you haven't read the original article yet, you're encouraged to do it now as it explains the coreprinciple of approving user accounts. In this article, I'll only describe the variations needed to let anadministrator approve the account.

    From a high-level perspective, here's what you need to do to let an administrator of your site approvethe account of a newly signed up user:

    1. Let the user sign up for an account2. Intercept the sending of the e-mail and either change the existing e-mail so it's send to the

    administrator of the site, or create an additional e-mail message instead. Add a link to the mailmessage body that lets an administrator approve the account.3. Create a page that lets an administrator approve the account, and optionally assign it to one or

    more roles.

    You'll see how to accomplish these steps next.

    1. Let the user sign up for an accountThis is similar to the implementation in the original article: add a CreateUserWizard to a page(calledSignUp.aspx in the demo site), and set DisableCreatedUserto True so the user account isn't activatedautomatically when it gets created. Then write code for the SendingMail event and redirect the e-mail toan administrator instead of to the user that signed up for the account. Here's the code forthe CreateUserWizard(note: you find a fully working example in the download for this article):

    2. Intercept the sending of the e-mailIn the code behind ofSignUp.aspx, you can modify the e-mail message that is normally send to the user,and send it to an administrator instead, like this:

    protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e){// Remove the original recipiente.Message.To.Clear();// Add the Administrator account as the new recipiente.Message.To.Add("[email protected]");string confirmLink =

    string.Format("{0}://{1}/Confirm.aspx?ConfirmationKey={2}&UserName={3}",Request.Url.Scheme, Request.Url.Authority, _accountConfirmationKey,CreateUserWizard1.UserName);

    e.Message.Body = e.Message.Body.Replace("##ConfirmLink##", confirmLink);}

    First, this code clears the To collection by calling Clear. This removes the original recipient so the userthat signed up for an account doesn't receive a copy of the message. Then the e-mail address of theAdministrator is added by calling Add on the To collection and passing in the administrator's e-mail

    http://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-accounthttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-accounthttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-accounthttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-accounthttp://imar.spaanjaars.com/569/requiring-users-to-confirm-their-e-mail-address-after-they-create-an-account
  • 7/27/2019 Desde Un Frame o Iframe Se Pierder Los Valores de Session o Cookies

    31/126

    address. The remainder of the code is ide