I have a web application in vb in which I am using this approach to prevent a user from having concurrent logins due to a simple licensing agreement.
It works great, if a user logs in with an account that is already in use, the first user gets logged out. I am trying to add a messagebox or some kind of js confirmation box in the loggingin event that states:
This user account has been active in the last 20 minutes.
If someone else is using it, then logging in may possibly
compromise any report generation or activity.
Continue login?
Here is the code:
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Dashboard/Default.aspx" >
<LayoutTemplate>
<table border="0" cellpadding="0">
<tr>
<td align="right"><p><asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label></p></td>
<td align="right">
<p><asp:TextBox ID="UserName" runat="server" Width="220" autocomplete="on" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" Text="*"
ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login1" /></p>
</td>
</tr>
<tr>
<td align="right"><p><asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></p></td>
<td align="right">
<p><asp:TextBox ID="Password" runat="server" TextMode="Password" Width="220"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" Text="*"
ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login1" /></p>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color: red"><asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal></td>
</tr>
<tr>
<td align="right" colspan="2"><asp:LinkButton CssClass="prettyButton" ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" /></td>
</tr>
</table>
</LayoutTemplate>
</asp:Login>
Private Sub Login1_LoggingIn(sender As Object, e As LoginCancelEventArgs) Handles Login1.LoggingIn
Dim messagetext As String = "This user account has been active in the last 20 minutes." + Environment.NewLine + Environment.NewLine
messagetext += "If someone else is using it, then logging in may possibly" + Environment.NewLine
messagetext += "compromise any report generation or activity." + Environment.NewLine + Environment.NewLine
messagetext += "Continue login?"
Dim userNameTextBox As System.Web.UI.WebControls.TextBox = DirectCast(Login1.FindControl("UserName"), System.Web.UI.WebControls.TextBox)
Dim currentUser As MembershipUser = Membership.GetUser(userNameTextBox.Text)
If currentUser IsNot Nothing Then
If currentUser.IsOnline Then
'*****CONFIRMATION MESSAGE BOX TO GO HERE*****/
Dim result = MessageBox.Show(messagetext , "Login Warning", MessageBoxButtons.YesNo)
'* IF USER DECIDES NOT TO LOGIN:*/
If result = DialogResult.No Then
e.Cancel = True
End If
'* ELSE LOGIN CONTINUES AND ORIGINAL USER IS LOGGED OUT*/
End If
End If
End Sub
Private Sub Login1_LoggedIn(sender As Object, e As EventArgs) Handles Login1.LoggedIn
Dim userNameTextBox As System.Web.UI.WebControls.TextBox = DirectCast(Login1.FindControl("UserName"), System.Web.UI.WebControls.TextBox)
SingleSessionPreparation.CreateAndStoreSessionToken(userNameTextBox.Text)
End Sub
Now, I can use a windows form msgbox() locally, and everything works great, but once I put it on a server, the message box obviously doesn't work. I've tried ClientScript and ScriptManager, but the client side check doesn't seem to get triggered.
Any help is greatly appreciated.
Do not use the VB MessageBox in a web site. It will ONLY show up on the server - and will more than likely kill your page every time. The end user will never see it on his browser.
There are a bunch of ways you could handle what you're trying to achieve, though one that will work well is to show the user a javascript confirm box; which is more or less the same as a message box but has an OK and Cancel button instead.
You can show this to the user by injecting a little javascript to your page as it renders. So, remove your Dim result.... line and replace it with something like this: - this will inject some javascript to your pages HTML.
Dim cs As ClientScriptManager = Page.ClientScript
cs.RegisterStartupScript(Me.GetType(), "userChecker", "UserCheck(Confirm('yourMessage'));", True)
NOTE - you will also remove the code that checks your dialog, I.E If result = ....
When the page loads the confirm dialog will appear. The captured response, in this case, will be passed to a javascript function called UserCheck - so have a javascript function in your HTML to accept it. Something like this:
function UserCheck(t){
if (t){
// do something for OK
}else{
// do something for CANCEL
}
Within the UserCheck you can easily handle the users response. Perhaps by redirecting, or causing a postback by calling the __doPostBack function of .Net.
Related
I am creating a password text field that shows/hides password requirements as the user types their password into a TextBox with TextMode="Password". I added a TextChanged event so I could check the TextBox text against the requirements each time a new character is typed/removed.
The problem I am having is that the TextChanged event is seemingly not being triggered ever. Here is the relevant code:
<tr>
<td style="text-align: right">
<asp:Label ID="Label1" runat="server" CssClass="BoldLabel14px" Font-Bold="True"
Text="New Password"></asp:Label>
</td>
<td>
<asp:TextBox ID="NewPassword" runat="server" Font-Names="calibri"
Font-Size="14px" TextMode="Password"></asp:TextBox>
</td>
</tr>
Protected Sub NewPassword_TextChanged(sender As Object, e As EventArgs) Handles NewPassword.TextChanged
System.Diagnostics.Debug.WriteLine("NewPassword Text = " & Me.NewPassword.Text)
CheckPasswordRequirements(Me.NewPassword.Text)
Me.PasswordRequirementsCapital.Visible = False
End Sub
From this code, the output never shows the debug statement as the TextBox is modified. Is different way to grab the text as it is written? I am using Visual Studio, vb.net, and asp.net.
The main reason the event isn't fired is because you don't have an event tied up to even be fired.
It should be something like:
<asp:TextBox ID="NewPassword" runat="server" Font-Names="calibri" Font-Size="14px" TextMode="Password" ontextchanged="NewPassword_TextChanged" AutoPostBack="True"></asp:TextBox>
The event itself will not fire until you leave though, it's a server side process and only happens between posts to the server. If you want to handle this as the text is changing look into JavaScript and or JQuery.
I have a simple FileUpload box that is alble to accept files and save them to a location on a server on one web page, but the page I'm working on now has a form view inside of a radPageView, inside of a RadMultiPageView. When I attempt to see if there is a file in the FileUpload control, I am met with null values every time, eventhough I'm loading in a file. Here are some snippets of my code, trimmed down a little. Part of the problem is that in all of the tutorials I've found online, users are entering some of this information in the vb for the button click event, where I'm entering it in the xyz Handles .Updating section.
The prolem I run into is that when I get to the FileUpload1.HasFile it shows that there is no file, even if I have uploaded one. In fact, it shows Null, as if I haven't properly connected to the FileUpload control. I messed around with different ways to connect to the FileUpload control, but none of them really worked.
<telerik:RadMultiPage ID="RadMultiPage1" runat="server" SelectedIndex="0" CssClass="multiPage"
BorderColor="Black" BorderStyle="Solid">
<telerik:RadPageView ID="pvMemoDoc" runat="server">
<asp:FormView ID="fvMemoDoc" runat="server" DefaultMode="Edit" DataSourceID="dsMemos"
DataKeyNames="coreDocID">
<EditItemTemplate>
<table class="tblNoSpace">
[...Other Code...]
<%--Begin file upload section--%>
<tr>
<td class="fieldLabel">File to upload:<br />
</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" Width="600" ToolTip="Browse for file" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<asp:Label ID="lblFU1" runat="server" Enabled="false" Visible="false"
Text="(only select new file if you wish to replace existing file)"></asp:Label>
</td>
</tr>
<tr>
<td>
<br />
<br />
<asp:Button ID="btnUpdateMemo" CommandName="Update" runat="server" Text="Update Memo"
CausesValidation="true" ValidationGroup="MemoInformation"
ToolTip="Save updates" />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:FormView>
</telerik:RadPageView>
[...Other Code...]
</telerik:RadMultiPage>
VB Code:
Private Sub DsMemo_Updating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsMemos.Updating
Dim FileUpload1 As FileUpload = CType(fvMemoDoc.FindControl("FileUpload1"), FileUpload)
'Dim FileUpload1 As FileUpload = CType(fvMemoDoc.Controls(0).Controls(0).FindControl("FileUpload1"), FileUpload)
'Dim FileUpload1 As FileUpload = CType(fvMemoDoc.Controls(0).FindControl("FileUpload1"), FileUpload)
'Dim FileUpload1 As FileUpload = TryCast(updateButton.Parent.Parent.FindControl("FileUpload1"), FileUpload)
If FileUpload1.HasFile Then
[...Other Code Here..]
[...Never gets past FileUpload1.HasFile...]
End If
End Sub
It appears after some tinkering that there was an issue with modify versus read/write permissions.
The way that control was working is that it would store a temporary file and then delete it off of the server, so that is why no file was showing.
Giving the web app modify access to the folder where the temporary files are stored solved my issue.
I am using an asp TextBox control with its TextChanged event and my goal is to capture text as a user enters it. If there are one or more characters entered, I would like a button control to be enabled without the user having to leave the TextBox control.
My source code for the TextBox on the aspx page is
<asp:TextBox ID="NewSpendingCategoryTextBox" MaxLength="12" runat="server"
AutoPostBack="True"
OnTextChanged="NewSpendingCategoryTextBox_TextChanged"
ViewStateMode="Enabled" >
</asp:TextBox>
and my source code on the code behind page is
Protected Sub NewSpendingCategoryTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NewSpendingCategoryTextBox.TextChanged
Dim strSpendingCategoryTextBox As String = Nothing
strSpendingCategoryTextBox = NewSpendingCategoryTextBox.Text
If strSpendingCategoryTextBox.Length <= 0 Then
Me.NewSpendingCategoryInsertButton.Enabled = False
Else 'strSpendingCategoryTextBox.Length > 0
Me.NewSpendingCategoryInsertButton.Enabled = True
End If 'strSpendingCategoryTextBox.Length <= 0
End Sub
So it appears I have to use javascript to enable or disable the insert button. Can someone guide me on how to get an element within a table? The table sits in a Panel as well.
below is the aspx code...
<asp:Panel ID="AddSpendingCategoryPanel" Visible="false" runat="server">
<table class="AddNewTable">
<tbody>
<tr>
<td>
<asp:Label ID="lblSpend" runat="server"
Text="Spending Category:">
</asp:Label>
</td>
<td>
<asp:TextBox ID="txtSpend" MaxLength="12"
runat="server"
AutoPostBack="True"
OnTextChanged="txtSpend_TextChanged"
OnKeyDown="return CheckSpendTextBoxValue()"
ViewStateMode="Enabled" >
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="frmbtn" ID="btnInsertSpend"
runat="server" Text="Insert" />
</td>
<td>
<asp:Button CssClass="frmbtn" ID="btnCancelSpend"
runat="server" Text="Cancel"
CausesValidation="False" />
</td>
</tr>
</tbody>
</table>
</asp:Panel>
Run this code in the OnKeyPress event or consider JavaScript. The textbox does not fire the Text_Changed event til Tab or Enter are used.
Simplify the boolean check.
Me.NewSpendingCategoryInsertButton.Enabled = (NewSpendingCategoryTextBox.Text.Length <> 0)
I'm not sure exactly how you would do it. But the ASP.NET code is executed on the server that is hosting the web page.
I'd highly recommended doing it on JavaScript which can be run client side. Hopefully this article is of use to you.
How to check if a textbox is empty using javascript
I have been working on a file upload section within my ASP.NET site.
With the below code, I am able to get a user to upload documents based based on the Regular Expressions set within the RegularExpressionValidator. I am happy that this works accordingly.
What I would like to complete now is a message to indicate that the file has been uploaded successfully. I am unsure how to complete this, but would like to add it to a Label named "fileuploaded".
Here is my code for the .aspx page:
<table width = "60%">
<tr>
<td>Modes of Operation:</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:Button ID="buttonUpload" runat="server" Text="Upload" ValidationGroup="FileUpload" />
</td>
</tr>
<tr>
<td colspan="3">
<asp:RequiredFieldValidator ID="FilenameRFValidator" runat="server"
ControlToValidate="FileUpload1" Display="Dynamic"
ErrorMessage="RequiredFieldValidator" ValidationGroup="FileUpload">
* Please select a file to upload...
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td colspan="3">
<asp:RegularExpressionValidator ID="FilenameRegExValidator" runat="server"
ControlToValidate="FileUpload1" Display="Dynamic"
ErrorMessage="RegularExpressionValidator"
ValidationExpression="(?i)^[\w\s0-9.-]+\.(txt|pdf|doc|docx|xls|xlsx)$"
ValidationGroup="FileUpload">
* Please upload file in format .pdf / .docx / .xlsx.
</asp:RegularExpressionValidator>
</td>
</tr>
</table>
<asp:Label ID="lblfileuploaded" runat="server" Text=""></asp:Label>
And here is my code so far for the VB page:
Protected Function GetUploadList() As String()
Dim folder As String = Server.MapPath("~/Uploads")
Dim files() As String = Directory.GetFiles(folder)
Dim fileNames(files.Length - 1) As String
Array.Sort(files)
For i As Integer = 0 To files.Length - 1
fileNames(i) = "" & Path.GetFileName(files(i)) & ""
Next
Return fileNames
End Function
Protected Sub UploadThisFile(ByVal upload As FileUpload)
If upload.HasFile Then
Dim theFileName As String = Path.Combine(Server.MapPath("~/Uploads"), upload.FileName)
If File.Exists(theFileName) Then
File.Delete(theFileName)
End If
upload.SaveAs(theFileName)
End If
End Sub
Protected Sub buttonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonUpload.Click
UploadThisFile(FileUpload1)
UploadedFiles.DataBind()
End Sub
Any help in advance is much appreciated.
As Tim Schmelter says in the comments, you should just set the text of the label after SaveAs has been successfully called.
You can use a Try -> Catch to make sure the there were no exceptions (according to the MSDN article linked above, the SaveAs method could throw an HttpException). Something like this:
Try
upload.SaveAs(theFileName)
fileuploaded.Text="File uploaded successfully"
Catch ex As Exception
fileuploaded.Text="Upload failed. Reason: " + ex.Message
What I would like to achieve:
I would like a user to be able in insert a row into the listview. BUT not into a database.
What I am stuck on:
Currently I am stuck on the OnItemCommand, i dont seem to be entering the method. Any help would be great Code below.
<LayoutTemplate>
<table>
<th>
</th>
<th class="grayHeader">
<asp:Label ID="lblHeader" runat="server" />
</th>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Button runat="server" ID="btnDeletePerson" Text="-" CommandName="deletePerson"/>
</td>
<td>
<asp:Label ID="lblPerson" runat="server" Text='<% #Eval("Person") %>'></asp:Label>
</td>
</tr>
</ItemTemplate>
<InsertItemTemplate>
<tr>
<td>
<asp:Button ID="btnAddUser" runat="server" CommandName="Insert" ext="+" />
</td>
<td>
<asp:TextBox runat="server" ID="txtInsert"></asp:TextBox>
</td>
</tr>
</InsertItemTemplate>
Protected Sub ListGrantee_OnItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs)
Select Case e.CommandName
Case "Insert"
Dim test As ListViewItem
test = New ListViewItem("test")
listGrantee.Items.Add(test)
Case ""
Case Else
End Select
End Sub
I would save you temporarily created Users in the ListView's Datasource flagged as temporary(add a new DataColumn). Afterwards you have to DataBind the Listview. Store the flag in an invisible control(label) so that it is saved in the ViewState on Postbacks.
Further to my comment - as I understand your problem, your OnItemCommand event handler is not getting triggered. Here's how I set up event handlers (using VS2008).
In the design view for the aspx file, I highlight the control that I am interested in. Then, in the "Properties" window, I click on the Event's button (the little lightning flash), and scroll down the list of events until I find the one I am interested in.
Double click in the column next to the event name - this will bring up the code behind page, with the shell of the event handler in place - including the all important "handles ...." clause.
Now enter your event handling code....
I had viewstate turned off. Which disabled the event mechanism, flipped view state back on problem solved.