how to delete cookies?

Last post 07-03-2009 7:19 AM by sandy060583. 6 replies.

Sort Posts:

  • how to delete cookies?

    03-01-2008, 7:08 AM
    • Member
      16 point Member
    • satender88
    • Member since 02-04-2008, 7:22 AM
    • Posts 46

     Hi,
    I am creating a cookie using the following code:
                    Dim iharyanacookie As HttpCookie
                    iharyanacookie = New HttpCookie("username", uid.Text)
                    Response.Cookies.Add(iharyanacookie)

     But how can I delete or destroy a cookies. I using the following code about cookies is still there and working.
            Response.Cookies("iharyanacookie").Expires = DateTime.Now.AddYears(-30)
            Response.Cookies.Remove("iharyanacookie")
            Response.Redirect("http://www.iharyana.com")

     

    Basically the whole page code is:

    Imports System.Data.SqlClient

    Partial Class WebUserControl
        Inherits System.Web.UI.UserControl

     Login Button:

      Protected Sub login_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles login.Click
            login_error.Text = ""
            Dim conn1 As SqlConnection
            Dim comm1 As SqlCommand
            Dim reader1 As SqlDataReader
            Dim connstring1 As String

            connstring1 = ConfigurationManager.ConnectionStrings("iharyana").ConnectionString

            conn1 = New SqlConnection(connstring1)

            Dim users As String
            users = "select password from usermain where username = @username"

            comm1 = New SqlCommand(users, conn1)

            comm1.Parameters.Add("@username", Data.SqlDbType.VarChar, 20)
            comm1.Parameters("@username").Value = uid.Text

            conn1.Open()

            reader1 = comm1.ExecuteReader

            If reader1.Read Then
                Dim pass As String
                pass = reader1.Item("password")
                If (pass = password.Text) Then
                    'create cookies
                    Dim iharyanacookie As HttpCookie
                    iharyanacookie = New HttpCookie("username", uid.Text)
                    Response.Cookies.Add(iharyanacookie)
                    Response.Redirect("http://www.iharyana.com")


                Else
                    login_error.Text = "Invalid Login ID or Password! Try Again"
                End If

            End If

            reader1.Close()
            conn1.Close()

        End Sub

     

    Page Load:

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim iharyanacookie As HttpCookie
            iharyanacookie = Request.Cookies("username")
            If iharyanacookie Is Nothing Then

            Else
                user.Text = "Welcome back <b>" & iharyanacookie.Value & "</b>"
                uid.Visible = False
                pass.Visible = False
                password.Visible = False
                login.Visible = False
                forgot.Visible = False
                sep.Visible = False
                reg.Visible = False
                my.Visible = True
                logout.Visible = True

            End If
        End Sub

     

    Logout Button:

        Protected Sub logout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles logout.Click
            Response.Cookies("iharyanacookie").Expires = DateTime.Now.AddYears(-30)
            Response.Cookies.Remove("iharyanacookie")
            Response.Redirect("http://www.iharyana.com")

        End Sub
    End Class

     

     

     

     Pls pls help.

     

  • Re: how to delete cookies?

    03-01-2008, 8:06 AM
    • Participant
      1,790 point Participant
    • ivanatanasov
    • Member since 05-09-2007, 12:49 PM
    • Bulgaria
    • Posts 333

    hi boy,

    Logout Button:

        Protected Sub logout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles logout.Click
            Response.Cookies("iharyanacookie").Expires = DateTime.Now.AddYears(-30)
            Response.Cookies.Remove("iharyanacookie")

             Request.Cookies("iharyanacookie").Expires = DateTime.Now.AddYears(-30)
           
    Request.Cookies.Remove("iharyanacookie")
            Response.Redirect("http://www.iharyana.com")

        End Sub
    End Class

     

     


    My blog is here.


    Please remember to 'Mark as Answer' if this post answered your question!
  • Re: how to delete cookies?

    03-01-2008, 1:25 PM
    Answer
    • Contributor
      3,802 point Contributor
    • gopalanmani
    • Member since 07-28-2006, 2:45 PM
    • Posts 640

    hi,

    Deleting Cookies

    Deleting a cookie—physically removing it from the user's hard disk—is a variation on modifying it. You cannot directly remove a cookie because the cookie is on the user's computer. However, you can have the browser delete the cookie for you. The technique is to create a new cookie with the same name as the cookie to be deleted, but to set the cookie's expiration to a date earlier than today. When the browser checks the cookie's expiration, the browser will discard the now-outdated cookie. The following code example shows one way to delete all the cookies available to the application:

    Dim aCookie As HttpCookie
    Dim i As Integer
    Dim cookieName As String
    Dim limit As Integer = Request.Cookies.Count - 1
    For i = 0 To limit
        cookieName = Request.Cookies(i).Name
        aCookie = New HttpCookie(cookieName)
        aCookie.Expires = DateTime.Now.AddDays(-1)
        Response.Cookies.Add(aCookie)
    Next
    
    check this url regarding cookies,
    http://msdn2.microsoft.com/en-us/library/ms178194.aspx 
     
  • Re: how to delete cookies?

    03-02-2008, 10:19 AM
    • Member
      16 point Member
    • satender88
    • Member since 02-04-2008, 7:22 AM
    • Posts 46

    Hi ivanatanasov,

     It is showing following error:

    Server Error in '/' Application.

    Object reference not set to an instance of an object.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:

    Line 72:         Response.Cookies.Remove("iharyanacookie")
    Line 73:
    Line 74: Request.Cookies("iharyanacookie").Expires = DateTime.Now.AddYears(-30)
    Line 75: Request.Cookies.Remove("iharyanacookie")
    Line 76: Response.Redirect("http://www.iharyana.com")

    Source File: d:\hosting\satender88\login.ascx.vb    Line: 74

    Stack Trace:

    [NullReferenceException: Object reference not set to an instance of an object.]
    WebUserControl.logout_Click(Object sender, EventArgs e) in d:\hosting\satender88\login.ascx.vb:74
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
    System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
    System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
    System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102


    Version Information: Microsoft .NET Framework Version:2.0.50727.832; ASP.NET Version:2.0.50727.832

     

  • Re: how to delete cookies?

    03-02-2008, 10:40 AM
    • Member
      16 point Member
    • satender88
    • Member since 02-04-2008, 7:22 AM
    • Posts 46

    Hi.

    This works:

     

            Dim iharyanacookie As HttpCookie
            iharyanacookie = New HttpCookie("username", "abc")
            iharyanacookie.Expires = DateTime.Now.AddYears(-30)
            Response.Cookies.Add(iharyanacookie)
            Response.Redirect("http://www.iharyana.com")

     

    Thanks gopalanmani, thanks a ton

  • Re: how to delete cookies?

    06-03-2009, 1:04 AM
    • Participant
      1,074 point Participant
    • klpatil
    • Member since 09-02-2008, 9:24 AM
    • Vadodara
    • Posts 206

     Hi,

    Thanks for all your help i just have one suggestion that without creating a new cookie with same name we can also take instance of already existing cookie[As we are going to delete a cookie so it must  exist :)] and then set its expires date and set it back in response...for PoC i have created one static function which you can use by just passing the cookie name to delete. Here it is :  

            /// &lt;summary&gt;
            /// This function will be used to remove
            /// cookies value
            /// </summary>
            /// <param name="key"></param>
            /// <returns>Cookies value</returns>
            public static void RemoveCookie(string key)
            {
                //get cookies value
                HttpCookie cookie = null;
                if (HttpContext.Current.Request.Cookies[key] != null)
                {
                    cookie = HttpContext.Current.Request.Cookies[key];
                    //You can't directly delte cookie you should
                    //set its expiry date to earlier date
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    HttpContext.Current.Response.Cookies.Add(cookie);
                }
                
            }
     
    Let me know if you need further assistance. I will be happy to help you.

    HTH

    -Kiran
    For more solution like this my blog is here
  • Re: how to delete cookies?

    07-03-2009, 7:19 AM
    • Participant
      1,294 point Participant
    • sandy060583
    • Member since 05-23-2007, 12:49 AM
    • Ahmedabad
    • Posts 327

    here is the code to create the cookie & delete it...


                            //Create Cookie
                            HttpCookie aCookie = new HttpCookie("AdminInfo");
                            aCookie.Values["userName"] = txtUsername.Text;
                            aCookie.Values["Password"] = txtPassword.Text;
                            aCookie.Values["lastVisit"] = DateTime.Now.ToString();
                            aCookie.Expires = DateTime.Now.AddDays(10);
                            Response.Cookies.Add(aCookie);
                     
                            //Delete Cookie
                            HttpCookie aCookie = new HttpCookie("AdminInfo");                        
                            aCookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(aCookie);
                      

    Hope this will help u..

    Please mark the answer if it helps you

    Ramani Sandeep

    http://ramanisandeep.wordpress.com


Page 1 of 1 (7 items)