Disabling button after click - asp.net

Private Function StoreCouponCode() As String
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString)
Dim sql As New SqlCommand("", con)
Dim sqlGetSlNo As New SqlCommand("SELECT MAX(SlNo) FROM Coupons WHERE CustID=" & Convert.ToInt16(HFCustID.Value) & " AND BusiID=" & Convert.ToInt16(HFBusiID.Value) & " AND OfferID=" & Convert.ToInt16(HFOfferID.Value), con)
Dim sNo, UserID, couponCode, offerCheck As String
Dim slNo As Int16
Try
UserID = getCurrentUserID()
con.Open()
sNo = Convert.ToString(sqlGetSlNo.ExecuteScalar) 'fteches latest serial no for the coupon
If sNo = "" Then
slNo = 0
Else
slNo = Convert.ToInt16(sNo) + 1
End If
couponCode = MakeCouponCode(slNo)
offerCheck = couponCode.Substring(13, 3)
sql.CommandText = "INSERT INTO Coupons VALUES (" & _
HFCustID.Value & "," & HFBusiID.Value & "," & HFOfferID.Value & ",'" & _
Today.Date & "'," & Convert.ToString(slNo) & "," & offerCheck & ",'" & couponCode & "','" & _
UserID & "'," & LblPayInAdv.Text & "," & LblPayLater.Text & ",'" & Convert.ToString(Date.Now) & "')"
sql.ExecuteNonQuery()
con.Close()
Catch ex As Exception
couponCode = "N/A"
Finally
con.Dispose()
sql.Dispose()
End Try
Return couponCode
End Function
Protected Sub CmdGetCoupon_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles CmdGetCoupon.Click
If User.Identity.Name = "" Then
LblMessage.Text = "You need to login first!"
Exit Sub
End If
Dim couponCode As String = StoreCouponCode()
Response.Redirect("~/Coupon.aspx?CouponCode=" & couponCode, True)
End Sub
When the user clicks on the CmdGetCoupon it takes some time to redirect..so the user clicks on the CmdGetCoupon more than once,which results in multiple coupon generation from a single user account.
I want to display a message "Please Wait While Your Coupon Is Being Generated" and disable the CmdGetCoupon so that the user cannot click multiple times....Any Ideas??How to do this??

Do this in javascript - use the OnClientClick to call a function that disables the passed in form element.
// On button
... OnClientClick="DisableMe(this);" ...
// Javascript
function DisableMe(elem)
{
elem.disabled = true;
// more code to show message
}

In your html side you have to add it in the onClientClick property:
<asp:Button ID="CmdGetCoupon" runat="server" onClientClick="this.disabled=true;" />
Edit:
Since #Oded so accurately pointed out that my first answer does not address the display of a message, here are a couple of options.
<span id="PleaseWaitContainer"></span>
<asp:Button ID="CmdGetCoupon" runat="server" onClientClick="this.disabled=true;document.getElementById('PleaseWaitContainer').innerText='Please Wait While Your Coupon Is Being Generated';" />
Or
<asp:Button ID="CmdGetCoupon" runat="server" onClientClick="this.disabled=true;alert('Please wait while your coupon is being generated...';" />

You can disable the button in the click handler, because you're going to redirect to another page, so don't care about any other logic.
Otherwise, if you're performing any async operation, again, disable it as soon as you click it, and in the async callback handler depending on the logic either enable it back or handle it properly in other way.

Related

Dynamically add Script to a Dynamically Created Div at Runtime vb.net aspx

I have created a web form with a Parent div container that contains child divs based on an SQL query. The number of children is based on the number of rows in the query result. I am hitting a snag though, and I think it's because I am programmatically adding a script as the divs are created. I know the script works because I tested it. It just isn't firing for the dynamically created divs.
Here is what the code looks like in the child div. It works, but not on dynamically created divs.
Sub ThumbView()
lbl_Status.Text = "ThumbView"
ListPanel.Visible = False
Dim MyTable As String = "[Estimate_Info4]"
Dim Sql As String = "SELECT* FROM [Estimate_Info4]"
Dim dbConnection = New SqlConnection(connString)
Dim dbCommand = New SqlCommand(Sql, dbConnection)
Dim data As New SqlDataAdapter(dbCommand)
Dim table As New DataTable(MyTable)
Dim rowIndex As Integer = 0
'//////////Open Database Connection////////////
dbConnection.Open()
data.Fill(table)
'//////////Loop through Data & Create Div for each Record //////////////
For Each row As DataRow In table.Rows
For i As Integer = 0 To (table.Rows.Count - 1)
Try
rowIndex = i
'/////////////////Control Delcarations/////////////////////
Dim NumberName As String = CStr(table.Rows(rowIndex)("EstNumber")) & " " & CStr(table.Rows(rowIndex)("JobName"))
Dim CleanName As String = RemoveWhitespace(NumberName)
Dim LBL_EstId As Label = New Label
Dim LBL_EstNumber As Label = New Label
Dim LBL_EstName As Label = New Label
Dim LBL_EstAddress1 As Label = New Label
Dim LBL_EstAddress2 As Label = New Label
Dim LineBreak As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak1 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak2 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak3 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak4 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim LineBreak5 As HtmlGenericControl = New System.Web.UI.HtmlControls.HtmlGenericControl("br")
Dim div As HtmlGenericControl = New HtmlGenericControl("div")
Dim divleft As HtmlGenericControl = New HtmlGenericControl("div")
Dim divright As HtmlGenericControl = New HtmlGenericControl("div")
Dim MyScript As HtmlGenericControl = New HtmlGenericControl("Script")
Dim MyIMG As ImageButton = New ImageButton
Dim MyIMG2 As ImageButton = New ImageButton
Dim RecID As Integer = (table.Rows(rowIndex)("Id"))
Dim RecID2 As String = CStr(table.Rows(rowIndex)("Id"))
'/////////////////Add 1st Child Div//////////////////
div.Attributes.Add("runat", " = server")
div.Style.Add("Class", "test")
div.Style.Add("width:", "637px")
div.Style.Add("height:", "228px")
div.Style.Add("aria-multiline", "True")
div.Style.Add("font-family", "verdana")
div.Style.Add("aria-multiline", "True")
div.Style.Add("word-break", "break-all")
div.Style.Add("word-wrap", "break-word")
div.Style.Add("Padding", "100x")
div.Style.Add("Border", "thick solid #666666")
div.Style.Add("margin-bottom", "10px")
div.Style.Add("margin-top", "10px")
div.Style.Add("margin-right", "10px")
div.Style.Add("margin-left", "10px")
div.Style.Add("display", "inline-grid")
Panel1.Style.Add("display", "inherit")
Panel1.Controls.Add(div)
'/////////////////Add 1st Child to First Child Div Float Left to house Image//////////////////
Dim StartString As String = "<script language=" & Chr(34) & "vb" & Chr(34) & "runat=" & Chr(34) & "server" & Chr(34) & ">" & Chr(10)
Dim EndString As String = "Sub ImageBttn" & RecID & "_Click(sender As Object, e As ImageClickEventArgs) Handles ImageBttn" & RecID & ".Click" & Chr(10) &
"Dim JobName As String = ImageBttn" & RecID & ".DescriptionUrl" & Chr(10) & "Dim JobID As String = ImageBttn" & RecID2 & ".CommandName" & Chr(10) &
"Response.Redirect(String.Format(" & Chr(34) & "~/476.aspx?JobName={0}&JobID={1}" & Chr(34) & ", JobName, JobID))" & Chr(10) & "End Sub" '& Chr(10) & "</script>"
' Dim inputString As String = EndString.Replace((Char)34),"").ToString()
'MsgBox(StartString & EndString)
Dim Q As String = Chr(34).ToString
Dim aString As String = Q & "~/476.aspx?JobName={0}&JobID={1}" & Q & ", JobName, JobID))"
Dim mymsg As String = "You Clicked" & NumberName
Dim folderPath As String = Server.MapPath("~/Files/VBScripts/")
Dim Mypath As String = folderPath & CleanName & ".vbs"
Try
'Check whether Directory (Folder) exists.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists Create it.
Directory.CreateDirectory(folderPath)
End If
'Save the File to the Directory (Folder).
'Dim Path As String = Server.MapPath("~/Files/VBScripts/")
Dim fs As FileStream = File.Create(Mypath)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(EndString)
fs.Write(info, 0, info.Length)
fs.Close()
Catch ex As Exception
MsgBox("Something has gone wrong..." & vbNewLine & ex.Message)
End Try
MyIMG.Style.Add("ID", CleanName)
MyIMG.Style.Add("Runat", "server")
MyIMG.Style.Add("OnClick", "ImageBttn" & RecID & "_Click")
MyIMG.Style.Add("DiscriptionUrl", NumberName)
MyIMG.Style.Add("CommandName", RecID2)
MyIMG.Style.Add("Class", "inner")
' /////////////// Create VBScript File and Add to Div////////////////
MyScript.Attributes.Add("script language", "vb")
MyScript.Attributes.Add("runat", "server")
MyScript.Attributes.Add("src", MyPath)
' src="
divleft.Attributes.Add("runat", " = server")
divleft.Style.Add("Class", "inner")
divleft.Style.Add("width: ", "186px")
divleft.Style.Add("height:", "228px")
divleft.Style.Add("aria-multiline", "True")
divleft.Style.Add("font-family", "verdana")
divleft.Style.Add("aria-multiline", "True")
divleft.Style.Add("Padding", "100x")
divleft.Style.Add("Border", "1px Gray")
divleft.Style.Add("Float", "Right")
divleft.Style.Add("display", "inline-Block")
divleft.Controls.Add(MyScript)
div.Controls.Add(divleft)
'/////////////////Add 2nd Child to First Child Div Float Right to house Labels//////////////////
divright.Attributes.Add("runat", " = server")
divright.Style.Add("Class", "inner")
divright.Style.Add("width:", "351px")
divright.Style.Add("height:", "228px")
divright.Style.Add("aria-multiline", "True")
divright.Style.Add("font-family", "verdana")
divright.Style.Add("aria-multiline", "True")
divright.Style.Add("Padding", "100x")
divright.Style.Add("Border", "1px Gray")
divright.Style.Add("Float", "Left")
divright.Style.Add("display", "inline")
div.Controls.Add(divright)
'/////////////////Add Controls to all of the Children//////////////////
MyIMG.Style.Add("ID", CleanName)
MyIMG.Style.Add("Runat", "server")
MyIMG.Style.Add("DiscriptionUrl", NumberName)
MyIMG.Style.Add("CommandName", RecID2)
MyIMG.Style.Add("Class", "inner")
MyIMG.Style.Add("OnClick", "ImageBttn" & RecID & "_Click")
divleft.Controls.Add(MyIMG)
MyIMG.ImageUrl = "~/Images/BLDG1.jpg"
LBL_EstNumber.Style.Add("runat", "server")
LBL_EstNumber.Style.Add("Height", "21px")
LBL_EstNumber.Style.Add("Width", "266px")
LBL_EstNumber.Style.Add("Font-Names", "Verdana")
LBL_EstNumber.Style.Add("Font-Size", "medium")
LBL_EstNumber.Style.Add("Font-Bold", "True")
LBL_EstNumber.Style.Add("ForeColor", "#666666")
LBL_EstNumber.Text = Chr(10) & " " & CStr(table.Rows(rowIndex)("EstNumber")) & " "
divright.Controls.Add(LineBreak1)
divright.Controls.Add(LBL_EstNumber)
LBL_EstNumber.Font.Bold = True
LBL_EstName.Style.Add("runat", "server")
LBL_EstName.Style.Add("Height", "21px")
LBL_EstName.Style.Add("Width", "266px")
LBL_EstName.Style.Add("Font-Names", "Verdana")
LBL_EstName.Style.Add("Font-Size", "medium")
LBL_EstName.Style.Add("Font-Bold", "True")
LBL_EstName.Style.Add("ForeColor", "#666666")
LBL_EstName.Text = Chr(10) & " " & CStr(table.Rows(rowIndex)("JobName")) & " "
divright.Controls.Add(LineBreak2)
divright.Controls.Add(LBL_EstName)
LBL_EstName.Font.Bold = True
LBL_EstAddress1.Style.Add("runat", "server")
LBL_EstAddress1.Style.Add("Height", "21px")
LBL_EstAddress1.Style.Add("Width", "266px")
LBL_EstAddress1.Style.Add("Font-Names", "Verdana")
LBL_EstAddress1.Style.Add("Font-Size", "Small")
LBL_EstAddress1.Style.Add("ForeColor", "666666")
LBL_EstAddress1.Text = CStr(table.Rows(rowIndex)("JobAddress"))
divright.Controls.Add(LineBreak3)
divright.Controls.Add(LBL_EstAddress1)
LBL_EstAddress2.Style.Add("runat", "server")
LBL_EstAddress2.Style.Add("Height", "21px")
LBL_EstAddress2.Style.Add("Width", "266px")
LBL_EstAddress2.Style.Add("Font-Names", "Verdana")
LBL_EstAddress2.Style.Add("Font-Size", "Small")
LBL_EstAddress2.Style.Add("ForeColor", "666666")
LBL_EstAddress2.Text = CStr(table.Rows(rowIndex)("JobCity")) & ", " & CStr(table.Rows(rowIndex)("JobState")) & " " & CStr(table.Rows(rowIndex)("JobZipCode"))
divright.Controls.Add(LBL_EstAddress2)
divright.Controls.Add(LineBreak4)
MyIMG2.Style.Add("runat", "server")
divright.Controls.Add(MyIMG2)
Dim EstStatus As Integer = (table.Rows(rowIndex)("EstimateStatus"))
If EstStatus = 2 Then MyIMG2.ImageUrl = "~/Images/Loss.jpg"
If EstStatus = 3 Then MyIMG2.ImageUrl = "~/Images/Awarded.jpg"
If EstStatus = 1 Then MyIMG2.ImageUrl = "~/Images/Pending.jpg"
Catch Ex As Exception
MsgBox("We've encountered an error; " & Ex.Message)
End Try
Next
Next
'/////////////////unhide the parent//////////////
Panel1.Style.Add("Height", "800px")
Panel1.Style.Add("width", "1800px")
Panel1.Style.Add("overflow", "scroll")
Panel1.Style.Add("overflow-y", "Scroll")
Panel1.Style.Add("overflow-x", "scroll")
Panel1.Visible = True
End Sub
'end result
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/Images/BLDG1.jpg" OnClientClick="ImageButton4_Click" DescriptionUrl="EST 02 Concrete Superstructure Hotel" EnableTheming="True" />
<script language="vb" runat="server">
Sub ImageButton4_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton4.Click
Dim JobName As String = ImageButton4.DescriptionUrl
Dim JobID As String = ImageButton4.CommandName
Response.Redirect(String.Format("~/476.aspx?JobName={0}&JobID={1}", JobName, JobID))
End Sub
</script>
I would not write all that code to inject repeating data into a web page. It not only too much code, but then after you done that, then trying to pluck out, or have the user operate against a given row of data is too much work.
I suggest you create ONE thing, lay it out correct in the desinger, and then simply feed it data.
So, say we have this:
So create the "one thing", lay it out nice. style it - do whatever. The result is simple, no code, use markup - you are done.
Now, look how easy it now becomes to "repeat" the data over and over with this code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' load the Repeater
LoadData
End If
End Sub
Sub LoadData()
Using cmdSQL As SqlCommand = New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Repeater1.DataSource = cmdSQL.ExecuteReader
Repeater1.DataBind()
End Using
End Sub
Output:
Now, was that not oh so easy? And then we can add css, get fancy, and improve that grid, but NOT have to touch the code behind!!!
And now, it becomes SUPER easy to deal with one thing. For example, we have that button click in the div. Lets get the row clicked, get the database PK id, and lets shove that into a label FOR THE ONE repeater item.
The code is thus this:
Protected Sub cmdTest_Click(sender As Object, e As EventArgs)
' btn click
Dim btn As Button = sender
Dim rRow As RepeaterItem = btn.Parent
Dim str As String = "Row Clicked = " & rRow.ItemIndex & " (PK ID = " & btn.Attributes.Item("PKID") & ")<br/>"
Dim txtHotel As TextBox = rRow.FindControl("txtHotel")
str &= "Hotel name = " & txtHotel.Text
' now setup label
Dim lbl As Label = rRow.FindControl("Label1")
lbl.Text = str
End Sub
I mean, how easy was that? So if we click on the 3nd one, we see this:
So, put your repeating stuff into of al things a "repeater".
Note how easy, how clean, how little code was written, and yet we get amazing ability here.
So, I recommend that you move out your code from the vb side, put it into a single nice layout, and then just shove data into that repeater - and it will "repeat" the data for you over and over.
Don't hard code all that markup in VB - it too much work, too hard, and costs too much time to get things done.
Edit:
So we use this code to load:
Sub LoadData()
Using cmdSQL As SqlCommand = New SqlCommand("SELECT * FROM tblHotels ORDER BY HotelName",
New SqlConnection(My.Settings.TEST3))
cmdSQL.Connection.Open()
Dim rst As New DataTable
rst.Load(cmdSQL.ExecuteReader)
Repeater1.DataSource = rst
Repeater1.DataBind()
End Using
End Sub
We used a datatable - since we need it later.
Now our row data bind event to change the status button is this:
Protected Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Select Case e.Item.ItemType.ToString
Case "Item", "AlternatingItem"
Dim btnImage As ImageButton = e.Item.FindControl("cmdStatus")
Select Case e.Item.DataItem("Status")
Case 1
btnImage.ImageUrl = "Content/ok.png"
Case 2
btnImage.ImageUrl = "Content/ckdelete.png"
Case 3
End Select
Case "Footer"
End Select
End Sub
our markup is this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="float:left;width:auto;border:solid;border-width:2px;padding:15px;margin-right:20px;border-radius:25px;box-shadow: 5px 5px #888888">
<div style="text-align:center">
<img src="Content/Skyline.PNG" />
<br />
<asp:Label ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>'></asp:Label>
<br />
<asp:Label ID="txtAD" runat="server" Text='<%# Eval("Address") %>'></asp:Label>
<br />
Active :<asp:CheckBox ID="Active" runat="server" Checked ='<%# Eval("Active") %>'></asp:CheckBox>
<asp:Button ID="cmdTest" runat="server" Text="Row Click" OnClick="cmdTest_Click"
PKID = '<%# Eval("ID") %>'
/>
<br />
<div style="float:left">
<asp:ImageButton ID="cmdStatus" runat="server" ImageUrl="Content/ok.png" Height="20px" Width="20px"/>
</div>
</div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
Output:
The beauty of above? We can now click on that button, or even the lower left check box - and we now have a simple event button code behind to grab that row - we can now show or launch another page based on clicking on each item.
Note how it took me less then 5 minutes to change my layout - that's because I am NOT writing code to do that layout and the mark-up part. So it was super easy for me to change the layout - even adding the graphic image.
OK, I'm going another route and the code is not firing.
I know there are easier ways to do this- So I'm adding a photo of webapps thumb view-there is also a list view view with icons indicating status. All I need now is the code to fire-It shows up on the page when I inspect.
![webform view]: (https://1drv.ms/u/s!AmmK5IyEVLSlg9gQSd_eb5KzA8UVcg?e=8sSdvI)
` Try
Dim csName As [String] = "ClientScript" & RecID
Dim csType As Type = divleft.[GetType]()
Dim cs As ClientScriptManager = Page.ClientScript
If Not cs.IsClientScriptBlockRegistered(csType, csName) Then
Dim csText As New StringBuilder()
csText.Append("<script language=" & Chr(34) & "vb" & Chr(34) & "runat=" & Chr(34) & "server" & Chr(34) & ">")
csText.Append("Sub ImageBttn" & RecID & "_Click(sender As Object, e As ImageClickEventArgs) Handles ImageBttn" & RecID & ".Click" & Chr(10) &
"Dim JobName As String = ImageBttn" & RecID & ".DescriptionUrl" & Chr(10) & "Dim JobID As String = ImageBttn" & RecID2 & ".CommandName" & Chr(10) &
"Response.Redirect(String.Format(" & Chr(34) & "~/476.aspx?JobName={0}&JobID={1}" & Chr(34) & ", JobName, JobID))" & Chr(10) &
"msgbox(ImageBttn" & RecID & ".DescriptionUrl)" & Chr(10) & "End Sub" & Chr(10) & "</script>")
cs.RegisterClientScriptBlock(csType, csName, csText.ToString())
End If
Catch ex As Exception
MsgBox("Something has gone wrong..." & vbNewLine & ex.Message)
End Try``

GetCurrentUserName() is causing crash in MS Access 2010

I am running Windows 7 Professional. I have an MS Access frontend to an MS Access backend. The form that opens at the start of opening the frontend causes the app to crash.
Here is the code:
Private Sub Form_Open(Cancel As Integer)
Dim strMyDir As String
Dim intPos As Integer
Dim rst As dao.Recordset
Dim strSQL As String
Dim rstWhatsNew As dao.Recordset
DoCmd.ShowToolbar "Database", acToolbarNo
DoCmd.ShowToolbar "Toolbox", acToolbarNo
DoCmd.ShowToolbar "Form View", acToolbarNo
If Application.GetOption("ShowWindowsInTaskbar") = -1 Then
Application.SetOption "ShowWindowsInTaskbar", 0
End If
If DLookup("Locked", "luLockOut") <> 0 Then
MsgBox "Database is being worked on. Please try back in a couple minutes.", vbInformation, " "
DoCmd.Quit
Else
strSQL = "Select * From tblLastLogins Where UserName = '" & GetCurrentUserName() & "'"
This is where I have traced the error to: GetCurrentUserName()
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If Not .EOF Then
.Edit
strSQL = "Select WhatsNewID From tblWhatsNew Where DateAdded >= #" & !LastLoginDate & "#"
Set rstWhatsNew = CurrentDb.OpenRecordset(strSQL)
While Not rstWhatsNew.EOF
DoCmd.OpenForm "frmWhatsNew", , , , , acDialog, rstWhatsNew!WhatsNewID
rstWhatsNew.MoveNext
Wend
rstWhatsNew.Close
Set rstWhatsNew = Nothing
Else
.AddNew
!UserName = GetCurrentUserName()
End If
!LastLoginDate = Now()
!IsLoggedIn = -1
Me.txtLastLoginID = !LastLoginID
.Update
.Close
End With
Set rst = Nothing
DoCmd.OpenForm "frmPrivacyNote"
Debug.Print Me.txtLastLoginID
End If
I need to track the username, so if GetCurrentUserName() is outdated, what is the current syntax?
Further follow up. I could not find data on Bing for GetCurrentUserName(), for good reason. It is a function within a MOD, so I need to figure out why the MOD is not getting called, or is malfunctioning.
After further delving, I found a Referenced MDB that has another function created by one of our users that is the cause of this error.
This is currently not an issue of MS Access working incorrectly. It is an issue with user created code.
GetCurrentUserName() is not defined by Access, so you should have looked at (and posted) its code.
If you are looking for the Windows user name, use this function:
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Environ("USERNAME") is easily spoofed, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
Source
The link below would suggest that
CurrentUser()
is the function
CurrentUser()
Andre, thank you very much for the insight! I found this link:
http://www.codeproject.com/Articles/1422/Getting-User-Information-Using-WSH-and-VBScript
Dim objNet
On Error Resume Next
'In case we fail to create object then display our custom error
Set objNet = CreateObject("WScript.NetWork")
If Err.Number <> 0 Then 'If error occured then display notice
MsgBox "Don't be Shy." & vbCRLF &_
"Do not press ""No"" If your browser warns you."
Document.Location = "UserInfo.html"
'Place the Name of the document.
'It will display again
End If
Dim strInfo
strInfo = "User Name is " & objNet.UserName & vbCrLf & _
"Computer Name is " & objNet.ComputerName & vbCrLf & _
"Domain Name is " & objNet.UserDomain
MsgBox strInfo
Set objNet = Nothing 'Destroy the Object to free the Memory

How to Validate a textbox+dropdowns in vb for a asp.net form

Previous question which links onto this and has any addition code ref should I forget to link any, I have set it up to email me should someone submit this form and an error occur and right now should that occur for most integer or datetime fields if they fail to validate then it will show me which fields in the email failed and what was input into them.
Problem I'm having now is to validate the drop downs and the textboxs in a similar way to what I with integer and datetime fields so I can display those also in the email in case they error.
present integer and datetime validation
Catch ex As Exception
lblInformation.Text = ("<h4>Unable to save data in database</h4>" + vbNewLine + "The error was '" + ex.Message + "'" + vbNewLine + vbNewLine + vbNewLine + "The SQL Command which falied was:" + vbNewLine + "<strong>" + mySQL + "</strong>" + vbNewLine).Replace(vbNewLine, "<br />" + vbNewLine)
Dim dtb As DateTime
If Not DateTime.TryParse(DateOfBirth, dtb) Then
strEMessageBody.Append("<strong>Date Of Birth:</strong> " & DateOfBirthYear.SelectedItem.Value & "-" & DateOfBirthMonth.SelectedItem.Value & "-" & DateOfBirthDay.SelectedItem.Value & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
Dim iao As Integer
If Not Integer.TryParse(AnyOther, iao) Then
strEMessageBody.Append("<strong>Any Other:</strong> " & rblAnyOther.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
then below the final validation I have the Dim for the email setting but that I sorted out in the other question.
The problem is much earlier in the page I have
Sub Upload_Click(ByVal source As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
Dim Name As String
Which prevents me just using there names as shown above where I would instead call them something else but that doesn't work with strings so my main issue is having some bit of code to check if the strings are valid and for the dropdowns which would either work but always show the data in the email or would hiccup in the code,
Dim imd As Integer
If Not Integer.TryParse(dept, imd) Then
strEMessageBody.Append("<strong>Department:</strong> " & dept.Text & vbCrLf)
strEMessageBody.Append("<br/>" & vbTab & vbTab & vbTab & vbTab & vbTab & vbTab)
End If
below was how it had been setup to record the department
Department = dept.SelectedItem.Value
Department = Replace(Department, "'", "''")
Summary:- Need vb code to validate if strings and dropdowns are valid and the use of try/catch block is another possible solution but I wasn't able to figure out how to implement validation for that either.
Log your values into your database. Setup a logging table called "tblLog" or something else. Record the value of ex.Message or possibly even InnerException (if it exists).
Going hand in hand with Matt's answer, there is a tool that can help you with automatically logging errors to a DB.
It's called ELMAH.
EDIT
Here are 2 validations that you might want to use:
Dim s As String = "some user input in here"
If [String].IsNullOrEmpty(s) Then
' Watch out, string is null or it is an empty string
End If
Dim cb As New ComboBox()
If cb.SelectedItem Is Nothing Then
' Watch out, combo has no item selected
End If
NOTE ComboBox is a WinForm control in this example, but the idea is the same for the ASP.NET counterpart
Since everybodies given up trying to find a solution then I'm just gona close this topic with this post as the answer.

An example of advanced database search

im looking for an example script. I saw one yesterday but for the life of me I can't find it again today.
The task I have is to allow the user to search 1 database table via input controls on an aspx page where they can select and , or , equals to combine fields, generating the sql on the fly with concat/stringbuilder or similar. (it runs behind the corp firewall)
Please can someone point me in the right direction of an example or tutorial
I've been working on the page, but have run into problems. Here is the Page_load;
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = ("Select * From Table Where ")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty Then
sql += "Surname LIKE '%" & name & "%' "
End If
If EmailSearch.Text IsNot String.Empty Then
sql += andor1v & " Email LIKE '%" & email & "%' "
End If
If CitySearchBox.Text IsNot String.Empty Then
sql += andor2v & " City LIKE '%" & city & "%' "
End If
If QualificationsObtained.Text IsNot String.Empty Then
sql += andor3v & " (institutionquals1 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals2 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals3 LIKE '%" & qualifications & "%') OR " & _
"(institutionquals4 LIKE '%" & qualifications & "%') "
End If
Dim selectedrow As String = CompetenciesDD.SelectedValue.ToString
Dim selectedquals As String = NQFlevel.SelectedValue.ToString
If CompetenciesDD.SelectedValue.ToString IsNot "0" And selectedquals = 0 Then
sql += (selectedrow & " = 1 ")
ElseIf selectedrow = "assessortrue" And selectedquals IsNot "0" Then
sql += andor4v & (" assessortrue=1 and assessorlvl=" & selectedquals)
ElseIf selectedrow = "coordinatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("coordinatortrue=1 and coordinatorlvl=" & selectedquals)
ElseIf selectedrow = "facilitatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("facilitatortrue=1 and facilitatorlvl=" & selectedquals)
ElseIf selectedrow = "moderatortrue" And selectedquals IsNot "0" Then
sql += andor4v & ("moderatortrue=1 and moderatorlvl=" & selectedquals)
ElseIf selectedrow = "productdevelopertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("productdevelopertrue=1 and productdeveloperlvl=" & selectedquals)
ElseIf selectedrow = "projectmanagertrue" And selectedquals IsNot "0" Then
sql += andor4v & ("projectmanagertrue=1 and projectmanagerlvl=" & selectedquals)
End If
Response.Write(sql)
End Sub
After an hours tinkering the code is now looking as it does above ^
Now the problem im faced with is if a user does not enter a value for surname (the first field) but does enter a value for email (or any subsequent fields), the sql produced has an extra and like this;
Select * From Table Where And Email LIKE '%test%'
I'm also looking for a way to take the OR option into account. Do you think this should be done as Martin says where the whole query is either an and or an or and not a mix of the 2? Then I should be able to take out all the and/or drop downs?
Thanks.
NB: I'm not really looking for comments on how I should parameterise or about sql injection.
Regarding your issue with users not selecting an option you could just remove the "please select" and have it default to "and"
Also what is the desired behaviour if they select a mix of ANDs and ORs?
By default the ANDs will be evaluated first in the absence of any brackets
http://msdn.microsoft.com/en-us/library/ms186992.aspx
So if they enter
name="Fred" or email="blah" and
city="london" and province="xyz" or
qualifications="Degree"
I'm not really sure what the desired semantics would be?
Is it
(name="Fred" or email="blah") and
city="london" and (province="xyz" or
qualifications="Degree")
or
(name="Fred" or (email="blah" and
city="london") and province="xyz") or
qualifications="Degree"
Or something different? Maybe you should restrict them to AND or OR for the whole query or allow them to disambiguate either by typing in advanced search syntax with brackets or by providing a query builder UI.
To avoid sql injection and allow a dynamic search I would probably write a stored procedure something like this. If nothing is selected send DBNull.Value in the ado.net parameters collection as the parameter value. With this approach you can check any columns you want and if they are not selected by the user they will be ignored.
EDIT: I just saw that you are not allowed to use stored procedures. I changed my answer below to show a parameterized sql statement
SELECT * FROM TABLE
WHERE ([name] = #name OR #name IS NULL)
AND (email = #email OR #email IS NULL)
AND (city = #city OR #city IS NULL)
AND (province = #province OR #province IS NULL)
AND (qualifications = #qualifications OR #qualifications IS NULL)
AND (competencies = #competencies OR #competencies IS NULL)
AND (expertise = #expertise OR #expertise IS NULL)
Concat strings to build a query is never a good idea. You should use a stored procedure or parametrized queries
I have done this "dynamic" type query interface on classic asp.
The advice that I give to you is that you are trying to do the whole query in one page load so...
Look to "building" the query via a "wizard" type interface - either ajax for the newness or simple multiple pages for each part of the query building.
This is essence gives you "persitance" via what ever means you have (session, dbstore, cookie etc) for each part of the query and you have can sanity check each part of the query as you build.
Dim sql As String = ("Select * From Table Where **1=1**")
'variables to hold the and or values between fields
Dim andor1v As String = AndOr1.SelectedValue.ToString()
Dim andor2v As String = AndOr2.SelectedValue.ToString()
Dim andor3v As String = AndOr3.SelectedValue.ToString()
Dim andor4v As String = AndOr4.SelectedValue.ToString()
Dim andor5v As String = AndOr5.SelectedValue.ToString()
Dim andor6v As String = AndOr6.SelectedValue.ToString()
'variables to stop web control inputs going direct to sql
Dim name As String = NameSearch.Text.ToString()
Dim email As String = EmailSearch.Text.ToString()
Dim city As String = CitySearchBox.Text.ToString()
Dim province As String = ProvinceSelect.SelectedValue.ToString()
Dim qualifications As String = QualificationsObtained.Text.ToString()
Dim competencies As String = CompetenciesDD.SelectedValue.ToString()
Dim expertise As String = Expertiselist.SelectedValue.ToString()
If NameSearch.Text IsNot String.Empty And andor1v IsNot "0" Then
sql += "**and** Surname LIKE '%" & name & "%' "
ElseIf NameSearch.Text IsNot String.Empty And andor1v Is "0" Then
sql += "**or** Surname LIKE '%" & name & "%' "
End If
....additional logic here.....
Response.Write(sql)
End Sub
note the ** parts. 1=1 evaluates to true on most DBMS. This allows you to just start concatenating your or / ands on to it without worrying about ()'s

Login and syntax error

i try to do a login using asp.net 3.5 and sql server 2005 i create a dataset and do this code
but something is missing in the code here the code
Protected Sub btnlogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlogin.Click
Dim LoginTable As New ClassSet.UsersDataTable
Dim LoginAdapter As New ClassSetTableAdapters.UsersTableAdapter
LoginAdapter.FillBylogin(LoginTable, txtuser.Text, txtpass.Text)
Dim dr As DataRow() = LoginTable.Select("Name= ' " & txtuser.Text & " 'Password= ' " & txtpass.Text & " '")
If dr.Length > 0 Then
Response.Redirect("MyClassifieds.aspx")
Else
Label1.Text = "Invalid UserName or Password"
End If
End Sub
it say that there is something missed after the password=' " & txtpass.Text in line 5 but i cant get what missed can any one help please
You are missing the "AND" statement between Name and Password
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")
You're missing an AND
Dim dr As DataRow() = LoginTable.Select("Name= '" & txtuser.Text & "' AND Password= '" & txtpass.Text & "'")
And I doubt you want spaces in there either.
But you also have a problem here, SQL Injection. You seriously do not want to build up dynamic SQL like this, you MUST parameterise all your queries.
Why are you running a select to verify the username and password in the login table when its just been filled using the username and password through the data adaptor? Surely you can just check its length then. Also, if there is any security in your login system the password won't be stored in plain text so the adaptors fill method should do some kind of one way hashing to find the correct password to return the the data table.

Resources