• 0

[ASP.NET] Update SQL date/time field upon successful login?


Question

I'm trying to get my feet wet in ASP.net programming, as one of our companies applications is designed in it, and while I understand VB.net, ASP.net is a little strange to me. As a test, I've started working on a database driven web application that has a log in form. The log in form makes a call to an SQL database to see if the users name and PW exist in a table. If they do, it redirects them to the main form. SO far everything is working, but now I'd like to do a test by having the form write the current date/time back to the database to a field called "LastLogin" if their result was found.

What I have so far:

Partial Class Login
    Inherits System.Web.UI.Page


    Public Sub LogIn(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
        Dim connStr As String = "Data Source=WHITE-DWARF;Initial Catalog=UserDatabase;Integrated Security=True"
        Dim sqlconnet As Data.SqlClient.SqlConnection
        Dim MyComm As Data.SqlClient.SqlCommand

        sqlconnet = New Data.SqlClient.SqlConnection()
        sqlconnet.ConnectionString = connStr
        MyComm = New Data.SqlClient.SqlCommand("", sqlconnet)

        MyComm.CommandType = Data.CommandType.Text

        MyComm.CommandText = "SELECT * FROM Logins WHERE (UserName ='" & txtUserName.Text & "') AND (Password = '" & txtPassword.Text & "') "
        sqlconnet.Open()

        Dim result As Data.SqlClient.SqlDataReader = MyComm.ExecuteReader(Data.CommandBehavior.CloseConnection)


        If result.HasRows = False Then

            lblStatus.Text = "Username and/or Password does not exist!"

        Else

            Session("Username") = txtUserName.Text
            Response.Redirect("success.aspx")
           ------> MyComm.CommandText = "UPDATE Logins SET LastLogin=" & Now & " WHERE (UserName ='" & txtUserName.Text & "') AND (Password = '" & txtPassword.Text & "')"

        End If

        result.Close()

    End Sub
End Class

The text next to the "---->" is what I'm trying to have done back to the database, but not sure if I need to redeclare the whole SQL data connection again just to perform an UPDATE...is there an easier way than redeclaring everything?

3 answers to this question

Recommended Posts

  • 0

Try putting the following line:

MyComm.ExecuteNonQuery()

to get the Update command to fire.

It is similar to the ExecuteReader command for the Select statement

Dim result As Data.SqlClient.SqlDataReader = MyComm.ExecuteReader(Data.Commandbehavior.CloseConnection)

  • 0

Yeah, you need to execute the last query, also the Response.Redirect should come after the query execution.

Off-topic, but please never never do this:

        MyComm.CommandText = "SELECT * FROM Logins WHERE (UserName ='" & txtUserName.Text & "') AND (Password = '" & txtPassword.Text & "') "

Use parameters so you're not open to SQL injection.

  • 0

I agree.

- Create parameter driven stored procedures in your SQL database to use within your website

- Sanitise the user inputs with functions

- Put the 'Update' before the redirect ;)

Small Example Below:

Imports System.Web.Security
Imports System.Data.SqlClient
Imports System.Data

Partial Class Controls_LoginDialog
    Inherits System.Web.UI.UserControl

    Dim strTitle As String = String.Empty


    Private Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Login(fSanitise(Me.txtUsername.Text), fSanitise(Me.txtPassword.Text))
    End Sub

    Private Sub Login(ByVal userName As String, ByVal passWord As String)

        Dim cnnSecurity As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Item("connection_security       Dim cmdSelect As New SqlCommand("usp_mySite_Login", cnnSecurity)
        Dim Authd As Boolean
        Dim MySettings As UserSettings = Nothing

        With cmdSelect
            .CommandType = CommandType.StoredProcedure
            .Parameters.Add(New SqlParameter("@Username", SqlDbType.VarChar)).Value = userName
            .Parameters.Add(New SqlParameter("@Password", SqlDbType.VarChar)).Value = passWord

            Try
                .Connection.Open()

                Dim drUser As SqlDataReader = .ExecuteReader(CommandBehavior.CloseConnection)

                If drUser.Read Then

                    FormsAuthentication.SetAuthCookie(userName, False)

                    Session.Add("LastUnloadedthing) 'session variable for auto-logout
                    MySettings = New UserSettings(Convert.ToString(drUser.Item("Username_
                                                  Convert.ToString(drUser.Item("Surname_
                                                  Convert.ToString(drUser.Item("Firstname_
                                                  Convert.ToString(drUser.Item("Email
                    'Session.Add("usersettingsSettings)
                    UserSettings.storeSettings(MySettings)

                    Authd = True

                    Session.Timeout = MySettings.SessionTimeout

                    drUser.Close()
                Else
                    Me.vldCustPassword.IsValid = False
                    Me.vldCustPassword.ErrorMessage = "Incorrect User/Password Combination Provided"
                End If

            Catch ex As Exception
                Me.vldCustPassword.IsValid = False
                Me.vldCustPassword.ErrorMessage = "Serious Error Has Occured - Please Contact WebAdmin"
                Throw
            Finally
                If Not .Connection.State = ConnectionState.Closed Then .Connection.Close()
            End Try
        End With

        If Authd And (Not MySettings Is Nothing) Then

            If Request.QueryString.Item("ReturnUrl Nothing Then
                Response.Redirect(MySettings.DefaultUrl)
            Else
                Response.Redirect(Request.QueryString.Item("ReturnUrl           End If


        End If
    End Sub

End Class

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • PC gaming is stalling as well, recent analyst post I read is that it will stall for at least two years because of prices, tariffs and AI demand impacting GPU cost and availability. So far the only console to go up in price has been the Xbox. Which IMHO is just part of Microsoft’s plans to get out of the traditional insole market and move to a “Xbox” console that is just a PC made by an OEM with a Xbox sticker on it.
    • Jumping unicorns means people initiate Nintendo gaming
    • KB5060829: Microsoft makes Windows 11 File Explorer, Search faster with Build 26100.4482 by Sayan Sen Microsoft has released a new Release Preview build for Windows 11 Insiders. The new build, 26100.4482, under KB5060829, improves the performance of the File Explorer in case of extracting archives. The company says "has been enhanced when extracting archive files" and that the improvement will mainly be felt "in the case of copy pasting large numbers of files out of large 7z or .rar archives." Aside from File Explorer, Microsoft says that users can also expect a snappier Search. Microsoft notes that earlier the feature would respond "very slowly—the Search Box can take over 10 seconds to load before you can use it." Besides those, Taskbar has also received an improvement as it will better use the available real estate space more effectively with new ability to resize icons so more apps can fit. The build also brings new PC Migration tool. Start menu pins have also changed You can view the full changelog below: Gradual rollout [App defaults] New! We are rolling out some small changes in the EEA region for default browsers via the Set default button in Settings > Apps > Default apps: Additional file and link types will be set for the new default browser, if it registers them. The new default browser will be pinned to the Taskbar and Start menu unless you choose not to pin it by clearing the checkboxes. There is now a separate one-click button for browsers to change your .pdf default, if the browser registers for the .pdf file type. [Start menu] New! For Admins, the Configure Start Pins policy now includes an option to apply Start menu pins only once. This means users will receive the admin Start menu pins on their first sign-in (day 0), but afterward, they can personalize their pinned layout, and those changes will be retained. This policy can also be applied through group policy, in addition to the existing configuration service provider (CSP) method. [Taskbar & System Tray] New! The taskbar now resizes icons to fit more apps when space runs low, keeping everything visible and easy to access. You can adjust how icons appear in settings—reduce icon size only when the taskbar is full (default), keep icons at their original size at all times by selecting Never, or use smaller icons all the time by selecting Always. To change this setting, right-click an empty area on the taskbar, select Taskbar settings, expand the Taskbar behaviors section, and choose your preference under Show smaller taskbar buttons. New! In addition to the new grouping of the Accessibility menu in Quick settings, there are text descriptions for the assistive technologies like Narrator, Voice access, and more for easier identification and learning. New! Adjusted the indicator (pill) under taskbar apps to make it wider and more visible. Fixed: Clicking the top third of the buttons in the top row doesn’t work to enable or disable the button. Fixed: WIN + CTRL + Number doesn’t work anymore for switching windows of an open app in the taskbar Fixed: When using taskbar in Windows, the media controls that appear in the preview windows for apps might unexpectedly flicker. [Windows Share] New! When you share links or web content using the Windows share window, you will see a visual preview for that content. New! In the Windows share window, you can select a compression level—High, Medium, or Low Quality—when editing and sharing images, instead of selecting from a 0–100 scale. [PC Migration] We’re beginning the rollout of a new PC-to-PC migration experience in Windows. You’ll start to see the landing and the pairing page in the Windows Backup app, giving you a first look at what’s coming. In the full experience, you will be able to transfer your files and settings from your old PC to the new one during the PC setup process. Support during the PC setup will be available in a future update. We are releasing in phases for a smooth experience and will provide more details soon. [File Explorer] Improved: Performance has been enhanced when extracting archive files – this will particularly help in the case of copy pasting large numbers of files out of large 7z or .rar archives. Narrator New! The Screen Curtain feature in Narrator helps protect your privacy and improve focus by blacking out the screen while Narrator reads content aloud. This is especially helpful in public or shared spaces, where you can work with sensitive information without others seeing your screen. To turn on Narrator, press Ctrl + Windows + Enter. Then press Caps Lock + Ctrl + C to enable Screen Curtain. While it’s on, you can use Narrator as usual with the screen hidden. Press Caps Lock + Ctrl + C again to turn it off. New! Narrator makes it easier to discover and learn about its features directly within the experience. Whether you’re new or exploring advanced options, Narrator will guide you through the latest updates using a series of steps and prompts that explain each new feature and change. [Voice Access] New! You can now use voice access to navigate, dictate, and interact with Windows using voice commands in Simplified Chinese and Traditional Chinese. New! You can add custom words to the dictionary in voice access. The feature will be available in all the currently supported voice access languages. [Settings] New! The Settings homepage on PCs managed by IT administrators now includes cards tailored for enterprise use. These include familiar options like “Recommended settings” and “Bluetooth devices,” along with two cards for device info and accessibility preferences. If a user signs in with both a work or school account and a Microsoft account, an additional accounts card appears to show both account types. New! Added the country or region selected during device setup under Settings > Time & language > Language & region. Fixed: The storage card in Settings > System > About shows an incorrect or unreadable character instead of the proper disk size. [Windowing] Fixed: When you ALT + Tab out of a full screen game, other windows (like Windows Terminal might stop responding. Fixed: An underlying issue might lead to unexpected window size and position changes after sleep/resume for some devices. Fixed: Explorer.exe might stop working unexpectedly when dragging a window if window snapping is enabled. [Scripting] Fixed: Running a script on a remote SMB share might take an unexpectedly long time if the share was an older Windows Server version like Windows Server 2019. [Graphics] Improved: Made some underlying changes to help improve display related user experiences, including reducing screen flashing in some display configuration transitions and removing unnecessary display resets which was happening in some cases. Fixed: Certain displays might be unexpectedly green. Fixed: If User Account Control (UAC) is set to Always Notify and the button under Settings > System > Display for color calibration is selected for your display and canceled, Settings will stop responding. [Color Filters] Improved: Adjusted the location of the intensity and color boost sliders under Settings > Accessibility > Color Filters, so the color previews at the top of the page are visible while adjusting the sliders. [Input] Fixed: Typing Japanese with the touch keyboard may stop working after switching to typing with an English keyboard and back. [Printing] Fixed: Printed lines might be unexpectedly thicker than expected. [MSFTEdit.dll] Fixed: Some apps like Sticky Notes and dxdiag might stop working when the display language is set to Arabic or Hebrew. Normal rollout [Copilot] Fixed: Improved the Copilot key’s reliability and resolved an issue that prevented users from restarting Copilot after using the key. [Performance] Fixed: This update addresses an issue to maintain efficiency of Storage Spaces Direct (S2D). When running complex software defined data center (SDDC) related workflows, it’s possible the system might become unresponsive. [Storage optimization] Fixed: An issue that prevented unused language packs and Feature on Demand packages from being fully removed, which led to unnecessary storage use and longer Windows Update installation times. [Windows Search] Fixed: Windows Search responds very slowly—the Search Box can take over 10 seconds to load before you can use it. Fixed: This update enhances the reliability of Windows Search and resolves an issue that prevented users from typing in Windows Search in some cases. You can find the official blog post here on Microsoft's website.
    • Windows 11 Snipping Tool gets a useful new screen recording feature by Taras Buria Last month, news emerged about the Snipping Tool app, Windows 11's default screenshot and screen-recording tool, getting a much-needed feature—the ability to save screen recordings as GIFs. Today, Microsoft officially announced this capability, and it is rolling out to Windows 11 insiders in the Dev and Canary Channels. In case you missed it, the latter received a new build with context menu improvements, new accessibility features, and more. GIF export in Snipping Tool works simply: Start screen recording as usual, then click the GIF button in the upper-right corner of the editor once you've finished. After that, the app will ask you to specify GIF quality and display your GIF's size info: duration, resolution, and FPS. Now, all it takes is pressing Export (save as a file) or Copy (copy to clipboard). Note that as of right now, GIF export is limited to 30-second videos or less. When exporting longer videos, the app will save only the first 30 seconds of the recording. GIF export in the Snipping Tool app is rolling out in version 11.2505.21.0. If you do not have the feature after installing the update (your computer should be enrolled in the Canary or Dev Channel of the insider program), try force-enabling it with the ViVeTool app: Download ViveTool from GitHub and unpack the files in a convenient and easy-to-find folder. Run Command Prompt as Administrator and navigate to the folder containing the ViveTool files with the CD command. For example, if you have placed ViveTool in C:\Vive, type CD C:\Vive. Type vivetool /enable /id:47081492 and press Enter. Restart your computer. The announcement post can be found on the official Windows Blogs website. Other changes recently introduced for the Snipping Tool app include the so-called "Perfect Screenshot" feature, which snaps the screenshot area to shapes and objects like tables and charts. Credit for the ID goes to @phantomofearth on X
    • Sure, I'm with you, but then again I don't run these companies and don't know all the details. As far as sales go, lots of MS software/services is sold through 3rd parties. I've always seen them for the longest time, they'll sell you the MS stuff and then also charge you a fee to act as direct support and so on.
  • Recent Achievements

    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
    • Week One Done
      Karan Khanna earned a badge
      Week One Done
    • First Post
      MikeK13 earned a badge
      First Post
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      690
    2. 2
      ATLien_0
      263
    3. 3
      Michael Scrip
      201
    4. 4
      +FloatingFatMan
      167
    5. 5
      Steven P.
      137
  • Tell a friend

    Love Neowin? Tell a friend!