Update statement in asp.net encountered with logic error? - asp.net

I'm developing a project where user can can edit/update their profile, but somehow I found myself in trouble when try to update the data into Access Database. The only funniest thing is, ONLY profile picture is updated/change in database, but none for password, firstname, lastname, etc. The rest still the same. I hope someone can help me in this case, thanks in advance!
The Page Load:
If Not IsPostBack Then
DropDownList1.DataBind()
End If
LinkButtonCancel.Visible = False
FileuploadProfPic.Visible = False
TextBoxCfrmPassword.Visible = False
ButtonUpdateProf.Visible = False
TextBoxImage.Visible = False
LabelUpload.Visible = False
LabelCfnPss.Visible = False
TextBoxUsername.Enabled = False
TextBoxPassword.Enabled = False
TextBoxFirstName.Enabled = False
TextBoxLastName.Enabled = False
TextBoxEmail.Enabled = False
TextBoxHPN.Enabled = False
TextBoxUsername.ReadOnly = True
TextBoxPassword.ReadOnly = True
TextBoxFirstName.ReadOnly = True
TextBoxLastName.ReadOnly = True
TextBoxEmail.ReadOnly = True
TextBoxHPN.ReadOnly = True
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
The Data Function to call the data from database:
Dim dvLogin As DataView = CType(AccessDataSourceProfile.Select(DataSourceSelectArguments.Empty), DataView)
dvLogin.RowFilter = "Username = '" & DropDownList1.SelectedValue & "'"
Dim Dt As New UserLogin
Dt.Username = dvLogin(0)("Username").ToString
Dt.Password = dvLogin(0)("Password").ToString
Dt.FirstName = dvLogin(0)("FirstName").ToString
Dt.LastName = dvLogin(0)("LastName").ToString
Dt.MobileNumber = dvLogin(0)("MobileNumber").ToString
Dt.Email = dvLogin(0)("Email").ToString
Dt.ProfilePic = dvLogin(0)("ProfilePic").ToString
Return Dt
The Update Button:
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("Product.mdb") & ";Jet OLEDB:Database Password=;"
objConn.ConnectionString = strConnString
objConn.Open()
Dim savePath As String = "C:\Users\AdananLong\Documents\Visual Studio 2010\Projects\E-Commerce\E-Commerce\"
If (FileuploadProfPic.HasFile) Then
Dim files As String = FileuploadProfPic.FileName
savePath += files
FileuploadProfPic.SaveAs(savePath)
TextBoxImage.Text = files
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
Else
Try
objCmd = New OleDbCommand("UPDATE Member SET [Password] = #password, FirstName = #firstname, LastName = #lastname, MobileNumber = #mobilenumber, Email = #email, ProfilePic = #profilepic WHERE Username = #username", objConn)
objCmd.Parameters.AddWithValue("#password", TextBoxPassword.Text)
objCmd.Parameters.AddWithValue("#firstname", TextBoxFirstName.Text)
objCmd.Parameters.AddWithValue("#lastname", TextBoxLastName.Text)
objCmd.Parameters.AddWithValue("#mobilenumber", TextBoxHPN.Text)
objCmd.Parameters.AddWithValue("#email", TextBoxEmail.Text)
objCmd.Parameters.AddWithValue("#profilepic", TextBoxImage.Text)
objCmd.Parameters.AddWithValue("#username", TextBoxUsername.Text)
objCmd.ExecuteNonQuery()
DropDownList1.DataBind()
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Update Sucessful."
Catch ex As Exception
Me.LabelWarning.Visible = True
Me.LabelWarning.Text = "Cannot Update : Error (" & ex.Message & ")"
End Try
End If
objConn.Close()
objConn = Nothing

This seems to be a well know effect of forgetting to test for postbacks in the Page_Load code.
Every time your user triggers an event to be handled on the server (runat="server" and/or AutoPostBack="true" ) then the Page.Load event of your page is called BEFORE calling the event handler activated by the user action. See ASP.NET Life Cycle
This means that in your Page.Load code you should be careful to not reload the page controls with values from the database otherwise, when the event handler is started, you have the controls filled with the original values extracted in the Page.Load event.
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
.....
' code to load the controls with values from database
UserData = Me.Data()
TextBoxUsername.Text = UserData.Username
TextBoxFirstName.Text = UserData.FirstName
TextBoxLastName.Text = UserData.LastName
TextBoxHPN.Text = UserData.MobileNumber
TextBoxEmail.Text = UserData.Email
ProfilePic.ImageUrl = UserData.ProfilePic
TextBoxImage.Text = UserData.ProfilePic
TextBoxPassword.Text = UserData.Password
End If
End Sub

Related

error after publishing app: The specified string is not in the form required for an e-mail address.

I am trying to create a program to send an email. my program works fine when I run it on local, but display an error after I publish it to the server.
this program trying to send an email inside gridview.
here is the gridview :
checkbox || email1 || email2
checkbox || bla2.smptserver.com || bla3.smptserver.com
checkbox || || bla3.smptserver.com
if email if email in column email1 is not null then the email will be send directly.
if email in column email1 is null then the email will be send to the recipient in column email2.
here is my code so far :
Private Sub sendEmail()
Dim Username2 As String = System.Configuration.ConfigurationManager.AppSettings("username")
Dim Password2 As String = System.Configuration.ConfigurationManager.AppSettings("1234")
Dim Server2 As String = System.Configuration.ConfigurationManager.AppSettings("namesmtp.server.com")
Dim X As Integer
For X = 0 To GridView1.Rows.Count - 1
Dim chkBox As CheckBox = CType(GridView1.Rows(X).Cells(18).Controls(1), CheckBox)
If chkBox.Checked = True Then
Dim email2 As String = ""
Dim no As Integer = CInt(GridView1.Rows(X).Cells(0).Text)
Dim id As String = Trim(GridView1.Rows(X).Cells(1).Text)
Dim name As String = Trim(GridView1.Rows(X).Cells(2).Text)
Dim item As String = Trim(GridView1.Rows(X).Cells(3).Text)
Dim size As String = Trim(GridView1.Rows(X).Cells(4).Text)
Dim qty As String = Trim(GridView1.Rows(X).Cells(5).Text)
Dim clr As String = Trim(GridView1.Rows(X).Cells(6).Text)
Dim type As String = Trim(GridView1.Rows(X).Cells(7).Text)
Dim area As String = Trim(GridView1.Rows(X).Cells(8).Text)
Dim ab As String = Trim(GridView1.Rows(X).Cells(9).Text)
Dim reason As String = Trim(GridView1.Rows(X).Cells(10).Text)
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim chkRow As CheckBox = TryCast(row.Cells(18).FindControl("chkCtrl"), CheckBox)
If chkRow.Checked Then
Dim spv As String = Trim(row.Cells(16).Text)
Dim mgr As String = Trim(row.Cells(17).Text)
sql = "update tbl_name set [Attire App] = 'Approved', [Attire Date] = #ADate, [SPV App] = (case when [SPV id] = '' then 'Approved' else [SPV App] end) where No = '" & Convert.ToUInt32(no) & "' and [Badge ID]= '" + Convert.ToString(id) + "' and Uniform = '" + item + "' and [Attire App] is null"
Dim sqlcomm As New SqlCommand(sql, con)
sqlcomm.Parameters.AddWithValue("#ADate", Now.Date)
sqlcomm.ExecuteNonQuery()
End If
End If
Next
If email2 <> "" Then
email2 = Trim(GridView1.Rows(X).Cells(16).Text)
Else
email2 = Trim(GridView1.Rows(X).Cells(17).Text)
End If
Try
Dim EmailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage
EmailMessage.From = New MailAddress("mail.address#something.com")
EmailMessage.To.Add(email2)
EmailMessage.Subject = "Attire Request"
EmailMessage.IsBodyHtml = True
Dim link As String = "Some link"
EmailMessage.Body = "There is a request for attire from employee. Please approve the request by using the following link Click here "
Dim smtp As New SmtpClient(Server2)
Dim basicAuthenticationInfo As New System.Net.NetworkCredential(Username2, Password2)
smtp.Credentials = basicAuthenticationInfo
smtp.Send(EmailMessage)
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End If
Next
End Sub
column email1 reside on gridview cell 16.
column email2 reside on gridview cell 17.
it's work fine but after I publish it, it's throws an errror.
the error display is 'The specified string is not in the form required for an e-mail address. '
Thanks in advance...

Handler change Session Variable?

I have this handler:
Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim request As HttpRequest = context.Request
Dim response As HttpResponse = context.Response
If (request.QueryString(GestioneConstants.PASSWORD_PARAM) Is Nothing) Then
Dim erroreParamName = GestioneConstants.ERRORE_PASSWORD_PARAM
Dim erroreMessage = GestioneConstants.MESSAGE_PWD_MANCANTE
Dim urlHome = "~/Default.aspx?" & erroreParamName & "=" & erroreMessage
response.Redirect(urlHome, False)
Else
Dim passToFind= request.QueryString(GestioneConstants.PASSWORD_PARAM)
Dim myConn As OdbcConnection
myConn = New OdbcConnection("Driver={Microsoft ODBC for Oracle};Server=SERVER;uid=uid;pwd=password")
myConn.Open
Dim passwordQuery As String = "SELECT PASSWORD as PASSWORD FROM INFOPWD WHERE INFOPWD.PASSWORD = '" & passToFind & "'"
Dim queryCommand As OdbcCommand = New OdbcCommand(passwordQuery,myConn)
Dim reader As OdbcDataReader = queryCommand.ExecuteReader()
Dim risultato = ""
While reader.Read()
risultato = reader("PASSWORD").ToString
End While
reader.Close
myConn.Close
If (risultato Is "") Then
Dim erroreParamName = GestioneConstants.ERRORE_PASSWORD_PARAM
Dim erroreMessage = GestioneConstants.MESSAGE_PWD_ERRATA
Dim urlHome = "~/Default.aspx?" & erroreParamName & "=" & erroreMessage
response.Redirect(urlHome, False)
Else
context.Session("Logged") = True
Dim strURL = "~/Home.aspx"
response.Redirect(strURL, False)
End If
End If
End Sub
Pratically my problem its on:
context.Session("Logged") = True
I just want to set this session variable to true where from the ASP page the user insert the correct password.
But I get the error:
An object reference not set to an instance of an object.
I don't understand why this happens.
Can someone help?
You need to use the Current property:
context.Current.Session("Logged") = True should work.

unhandles exception error when login page idle

I have developed a site in vb.net (with some help from my brother in law) and it's almost ready to roll out except I am getting an unhandled exception error on the login
screen when the page is idle for a few minutes. I am reasonably new to vb.net and not a programmer :( Any help would be really appreciated. Sorry if anything in my post is not to the site standard as this is my first post. :)
I'm not sure why this is happening. The code that is executed on login_buttonClick is:
Protected Sub LoginWizard_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles LoginWizard.FinishButtonClick
Dim oUsername As String = txtUsername.Text
Dim oPassword As String = txtPassword.Text
Dim oPath As String = Server.MapPath("App_Data/IOFR.mdb")
Dim oValid As Boolean = False
Dim oReader As System.Data.OleDb.OleDbDataReader = Nothing
Dim oConnection As System.Data.OleDb.OleDbConnection = Nothing
Dim oName As String = ""
Dim oOrg As String = ""
Dim oUserId As Integer = 0
Dim oActiveAcc As String = ""
Dim oSessionExpire As Integer = 0
Try
oConnection = New System.Data.OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Jet OLEDB:Database Password=EdmundColin13", oPath))
oConnection.Open()
Dim ipAddress As String = Request.ServerVariables("REMOTE_ADDR")
Dim cmd As New SqlCommand
Dim oParams As New List(Of System.Data.OleDb.OleDbParameter)
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmUsername", oUsername))
oParams.Add(New System.Data.OleDb.OleDbParameter("#pmPassowrd", oPassword))
Dim oCommand As New System.Data.OleDb.OleDbCommand("SELECT ID, [Name], Organisation, ActiveAccount, [Password] FROM Users WHERE [Username] = #pmUsername AND [Password] = #pmPassword", oConnection)
oCommand.Parameters.AddRange(oParams.ToArray)
oReader = oCommand.ExecuteReader()
If oReader.Read() Then
oValid = True
oName = oReader.GetString(oReader.GetOrdinal("Name"))
oActiveAcc = oReader.GetString(oReader.GetOrdinal("ActiveAccount"))
oOrg = oReader.GetString(oReader.GetOrdinal("Organisation"))
oPassword = oReader.GetString(oReader.GetOrdinal("Password"))
oUserId = oReader.GetInt32(oReader.GetOrdinal("ID"))
oSessionExpire = oReader.GetInt32(oReader.GetOrdinal("SessionExpire"))
End If
Catch ex As Exception
Finally
If Not oReader Is Nothing Then
If Not oReader.IsClosed Then
oReader.Close()
End If
oReader = Nothing
End If
End Try
If oValid And Not String.Equals(txtPassword.Text, oPassword) Then
oValid = False
End If
If oValid Then
If oActiveAcc = "No" Then
Response.Redirect("~/DisabledAccount.aspx")
Return
End If
Session("username") = txtUsername.Text
Session("name") = oName
Session("org") = oOrg
'Generate session id and store it in session
Dim uniquesessionid As String = Guid.NewGuid().ToString()
Session("uid") = uniquesessionid
Dim oCommandSession As New System.Data.OleDb.OleDbCommand("UPDATE Users SET SessionId = #pmid, SessionExpire = '" & DateTime.Now.AddHours(2).ToString() & "' WHERE [ID] = #pmUserid", oConnection)
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmid", uniquesessionid))
oCommandSession.Parameters.Add(New System.Data.OleDb.OleDbParameter("#pmUserid", oUserId))
oCommandSession.ExecuteNonQuery()
Response.Redirect("~/Home.aspx?login=true")
Else
txtUsername.BorderColor = Drawing.Color.Red
txtUsername.BackColor = Drawing.Color.Red
txtPassword.BorderColor = Drawing.Color.Red
FailedLogin.Visible = True
End If
If Not oConnection Is Nothing Then
If oConnection.State = Data.ConnectionState.Open Then
oConnection.Close()
End If
End If
End Sub
Thanks All. This seams to have resolved the issue.
EnableViewStateMAC="False"

Session disappears unexpectedly

The site is a buy/sell site and the page the code comes from is the "add product" page.
The problem is that the session("change") becomes nothing by some reason, I can't find any errors. The payment.aspx have a button that sends me back to the page with a session("change").
The reason I see the problem is that when I try to edit something the category gets restetted to the first in the list. and when I debug I see that the session is nothing, though it should be something
Heres the code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
If Not stats > 0 Then
If Session("change") IsNot Nothing Then
Dim dc As New DataClassesDataContext
Dim getP = From prod In dc.Products _
Where prod.ProductID = CInt(Session("change")) _
Select prod
If getP.Any Then
If rdbSell.Checked = True Then
getP.FirstOrDefault.BuySell = True
Else
getP.FirstOrDefault.BuySell = False
End If
If ddlSubSubcat.SelectedValue IsNot String.Empty Then
getP.FirstOrDefault.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
getP.FirstOrDefault.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
getP.FirstOrDefault.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
getP.FirstOrDefault.CountyID = CInt(ddlCounty.SelectedValue)
getP.FirstOrDefault.E_mail = txtEmail.Text
getP.FirstOrDefault.Date = DateTime.Now
getP.FirstOrDefault.Active = 0
getP.FirstOrDefault.Alias = txtAlias.Text.Replace("'", "''")
getP.FirstOrDefault.ShowEmail = 0
Dim PreID As Integer = getP.FirstOrDefault.ProductID
If chkShowEmail.Checked = True Then
getP.FirstOrDefault.ShowEmail = 1
Else
getP.FirstOrDefault.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
getP.FirstOrDefault.ShowPhone = 1
Else
getP.FirstOrDefault.ShowPhone = 0
End If
getP.FirstOrDefault.Headline = txtHeadline.Text
getP.FirstOrDefault.Password = txtPassword.Text
getP.FirstOrDefault.Phone = txtPhone.Text
getP.FirstOrDefault.Price = txtPrice.Text
If chkUnknown.Checked = True Then
getP.FirstOrDefault.YearModel = String.Empty
Else
getP.FirstOrDefault.YearModel = ddlYear.SelectedValue
End If
For Each item In libPictures.Items
Dim i As String = item.ToString
Dim imagecheck = From img In dc.Pictures _
Where img.Name = i And img.ProductID = CInt(Session("change")) _
Select img
If imagecheck.Any Then
Else
Dim img As New Picture
img.Name = item.ToString
img.ProductID = CInt(Session("change"))
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
End If
Next
dc.SubmitChanges()
Session.Remove("change")
Response.Redirect("~/precheck.aspx?id=" + PreID.ToString)
End If
Else
Dim dc As New DataClassesDataContext
Dim prod As New Product
If rdbSell.Checked = True Then
prod.BuySell = True
Else
prod.BuySell = False
End If
If ddlSubSubcat.DataValueField IsNot String.Empty Then
prod.CategoryID = CInt(ddlSubSubcat.SelectedValue)
Else
prod.CategoryID = CInt(ddlSubCat.SelectedValue)
End If
prod.Content = txtContent.Text.Replace(Environment.NewLine, "<br />")
prod.CountyID = CInt(ddlCounty.SelectedValue)
prod.E_mail = txtEmail.Text
prod.Date = DateTime.Now
prod.Active = 0
prod.Alias = txtAlias.Text.Replace("'", "''")
prod.ShowEmail = 0
If chkShowEmail.Checked = True Then
prod.ShowEmail = 1
Else
prod.ShowEmail = 0
End If
If chkShowPhone.Checked = True Then
prod.ShowPhone = 1
Else
prod.ShowPhone = 0
End If
prod.Headline = txtHeadline.Text
prod.Password = txtPassword.Text
prod.Phone = txtPhone.Text
prod.Price = txtPrice.Text
If chkUnknown.Checked = True Then
prod.YearModel = String.Empty
Else
prod.YearModel = ddlYear.SelectedValue
End If
dc.Products.InsertOnSubmit(prod)
dc.SubmitChanges()
Dim PreID As Integer = prod.ProductID
For Each item In libPictures.Items
Dim img As New Picture
img.Name = item.ToString
img.ProductID = prod.ProductID
dc.Pictures.InsertOnSubmit(img)
dc.SubmitChanges()
Next
Session.Remove("change")
Response.Redirect("./precheck.aspx?id=" + PreID.ToString, False)
End If
End If
stats = 0
'Catch ex As Exception
'End Try
End Sub
It depends upon how the application is managing session state. If your session state is managed InProc then if the application pool is recycled then all your session information will be lost. If that is happening then it could be a good option to store session state in SQL Server which will persist between app pool recycling.
More info:
ASP.NET Session State Overview
ASP.NET State Management Recommendations

asp.net vb.net gridview - can't sort!

I try to make this gridview sortable, but it simply doesn't work, anyone know why?
Dim sql As String = "SELECT Product_ID, Code, Trade_Name "
sql = sql & "FROM Product "
sql = sql & "WHERE Category = ? "
Dim conn As String = WebConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim dad As New OleDbDataAdapter(sql, conn)
dad.SelectCommand.Parameters.AddWithValue("?", CatID)
Dim dtblProduct As New DataTable()
dad.Fill(dtblProduct)
Dim grdProducts As New GridView
grdProducts.ID = "grdProducts"
grdProducts.CellPadding = 5
grdProducts.CellSpacing = 5
grdProducts.GridLines = GridLines.None
grdProducts.AutoGenerateColumns = False
grdProducts.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
grdProducts.EmptyDataText = "No Products Available."
grdProducts.DataSource = dtblProduct
Dim dataNavigateUrlFields() As String = {"Product_ID"}
Dim blnfirstCol As Boolean = True
Dim strPageResolveURL As String = String.Empty
Dim strLnkSelectText As String = String.Empty
For Each col As Data.DataColumn In dtblProduct.Columns
If blnfirstCol Then
Dim lnkSelect As New HyperLinkField
With lnkSelect
.Text = _strAction
.DataNavigateUrlFields = dataNavigateUrlFields
.DataNavigateUrlFormatString = Page.ResolveUrl(_strDirectPage & ".aspx?ProductID={0}&Cat=" & CatID)
End With
grdProducts.Columns.Add(lnkSelect)
blnfirstCol = False
Else
Dim myBoundField As New BoundField()
With myBoundField
Select Case col.ColumnName
Case "CODE"
.HeaderText = "Code"
.ItemStyle.Width = 100
.HtmlEncode = False
Case "TRADE_NAME"
.HeaderText = "Trade Name"
.ItemStyle.Width = 200
End Select
.DataField = col.ColumnName
.Visible = True
End With
grdProducts.Columns.Add(myBoundField)
End If
Next
grdProducts.AllowSorting = True ' Should already be true, but this doesnt help
grdProducts.DataBind()
It's frustrating!
I think you are not assigning SortExpression property in Columns.
Please check this example for more detail.
In your example, just add
.SortExpression= col.ColumnName
below
.DataField = col.ColumnName
Since you are adding columns manually, you have to set the SortExpression property for each of them. See last note here.

Resources