Require logging in to view page - asp.net

I have 2 pages:
login.aspx <Public
user.aspx <Should be locked behind a login
I have been trying to get this to work but I have not idea where to go from where I am now. Google mainly shows C# instead of vb.net.
I created a login page which works and continues to the next page.
However..
I can also type in the next page URL and I would not need to login.
How can I make it so the 2nd page tells me you need to be logged in to view this page.
What I have so far is:
login.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="login.aspx.vb" Inherits="web.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
height: 172px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="auto-style1">
Loginpage<br />
<br />
user:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
password:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
Code behind:
Imports System.Data.SqlClient
Public Class WebForm1
Inherits UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "myconstring"
Dim objcon As SqlConnection = Nothing
Dim objcmd As SqlCommand = Nothing
objcon = New SqlConnection("myconstring")
objcon.Open()
Dim stmt As String = "select * from login where Username = '" & TextBox1.Text & "' AND Password = '" & TextBox2.Text & "'"
objcmd = New SqlCommand(stmt, objcon)
Dim reader As SqlDataReader = objcmd.ExecuteReader
If reader.Read Then
Response.Redirect("user\user.aspx")
Else
Label1.Visible = True
Label1.Text = "Login onjuist"
End If
End Sub
End Class

In the code behind of your users page you can check if the user is authenticated. If they are not authenticated, you can redirect them to a page that informs them they must be logged in to access the page they were trying to visit. The code below just redirects to the login page.
If HttpContext.Current.User.Identity.IsAuthenticated = False Then
Response.Redirect("~/Login.aspx")
End If
Another option is you can define a location section in your web.config. The following code denies access to users.aspx, for users that are not authenticated.
<location path="users.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

Related

Binary Image Not Visible From Live Sql Table ASP.NET

On my page I have to upload image and immediate after saving it's displaying on ImageButton control and Image control. It's working local but not on Stagging Server.
I have tried by Image Datatype and VARBINARY(MAX). In both cases image is not displaying on stagging server.
Local Screenshot
Stagging Server Screenshot
Below is my code:
Html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Submit" /><br /><br />
<asp:Image ID="Image1" runat="server" Width="150px" />
<asp:ImageButton ID="ImageButton1" runat="server" Width="150px"/>
</form>
</body>
</html>
vb Code:
Imports System.IO
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Partial Class testingImage
Inherits System.Web.UI.Page
Dim imageurl As String = ""
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
bindrepeater()
End Sub
Sub bindrepeater()
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dsejConnectionString").ConnectionString)
Using cmdda As New SqlDataAdapter("select imagefile from testingPhototable where id=1", conn)
Using ds As New DataSet()
cmdda.Fill(ds, "t")
If (ds.Tables(0).Rows.Count > 0) Then
If ds.Tables(0).Rows(0)("imagefile").ToString() <> "" Then
imageurl = "data:image/jpg;base64," & Convert.ToBase64String(CType(ds.Tables(0).Rows(0)("imagefile"), Byte()))
ImageButton1.ImageUrl = imageurl
Image1.ImageUrl = imageurl
End If
End If
End Using
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim bytes As Byte()
Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)
bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength)
End Using
Dim constr As String = ConfigurationManager.ConnectionStrings("dsejConnectionString").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "UPDATE testingPhototable set imagefile=#imagefile where id=1"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#imagefile", bytes)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
bindrepeater()
End Sub
End Class
As the property name ImageUrl is maked from a word like “Url” presumes there needs an URL. So, it’s not like the “src” attribute on Client Side where you can set a source as Base64 String as well.
ImageUrl needs a relative url like “root/images/image1.jpg” or absolute “//somewhere_in_the_net_or_server/anotherpath/specificpath/yourfile.jpg”. Anyway, to achieve what you want, you can set the attribute “src” of your ImageButton1 as the follow line of code shows:
ImageButton1.Attributes("src") = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAMAAADDpiTIAAAAA3NCSVQICAjb4U....................."
You can do the same for Image1 as well
In my web.config
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="DENY"/>
<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" />
<add name="X-XSS-Protection" value="1; mode=block" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="content-security-policy: frame-ancestors 'none';img-src 'self';object-src 'self';frame-src 'self';child-src 'self';base-uri 'self';"/>
<add name="Referrer-Policy" value="strict-origin" />
</customHeaders>
</httpProtocol>
As listed above under content-security-policy there is a property img-src 'self'; this would stopping binary image to get render on control. I have removed this and now it's working fine.

ASP VB Add to textbox

I have a asp vb page that holds store hours. I'm supposed to add a textbox that has a list of people's emails in it. The emails come from a database, someone else wrote the code for that. But I need to be able to fill a textbox with these emails and have the textbox editable so someone can change or add new emails. So how do you get it so the textbox automatically fills up with the emails? I have a textbox on the asp page. And I have some code on the vb page to try to fill it but nothing shows up in textbox. Please help, I'm very new at this!
Asp:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="label1" Text="List Of Emails" runat="server" /> <br />
<asp:TextBox ID="emailBox" TextMode="MultiLine" runat="server" />
<br/><br/>
<asp:Button Text="Save" runat="server" />
<asp:Button Text="Cancel" runat="server" />
</div>
</form>
</body>
</html>
VB:
Partial Class KioskEmailUpdate
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim tempstoreID As Integer = 101
Dim ds As DataSet
Dim emailList As String = ""
ds = DBUtility.GetKisokAlertEmails(tempstoreID)
If Not ds Is Nothing AndAlso ds.Tables.Count > 0 And ds.Tables(0).Rows.Count > 0 Then
For Each dr In ds.Tables(0).Rows
emailList = dr("EmailList")
Next
End If
Dim seperatedEmailList() As String = Split(emailList, ";")
Dim counter As Integer = 0
For Each email In seperatedEmailList
emailBox.Text = emailBox.Text + email
counter = counter + 1
Next
Catch ex As Exception
Dim tempstoreID As Integer = 101
LogUtility.LogMessage("Error in getting and parsing email list from database. " & ex.ToString, "I", tempstoreID)
End Try
End Sub
End Class
You keep overwriting the variable emailList. Therefore, when you attempt to split it, you will only get one email address.
Change:
emailList = dr("EmailList")
To:
emailList &= dr("EmailList").ToString & ";"

Avoid postback on TreeView SelectedNodeChanged (inside jquery dialog)

What I am attempting to achieve is basically this:
user clicks on save as button
dialog "pop-up" shows that has report categories and name entry
user enters a name, or selects category which loads old reports
backend will get the values from dialog and use those to update reports in database
My issue is that when I fire the MyTreeView.SelectedNodeChanged event, I am redirected to the aspx page that I'm showing in my dialog pop-up. Is there anything I can do to prevent this, or contain the postback? I included my code, but I'm guessing this will be something I will have to account for in aspx?
Here's some code:
ReportSave.aspx -- in dialog window
<%# Page Language="VB" AutoEventWireup="false" CodeFile="ReportSave.aspx.vb" Inherits="ReportSave" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save Report As</title>
<link href="ReportSaveStyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form id="formReportSave" runat="server">
<div class="container">
<asp:Label class="report-list-title" ID="lblReportList" runat="server" Text="Report List"></asp:Label>
<asp:TreeView class="report-list-items" ID="trvReportList" runat="server"></asp:TreeView>
<asp:Label class="category-tree-title" ID="lblReportCategory" runat="server" Text="Report Category"></asp:Label>
<asp:TreeView class="category-tree-items" ID="trvCategoryView" runat="server"></asp:TreeView>
<asp:Label class="save-input-title" ID="lblReportName" runat="server" Text="Report Name"></asp:Label>
<asp:TextBox class="save-input-textbox" ID="tbReportName" runat="server"></asp:TextBox>
<asp:Button class="save-button1" ID="btnOK" runat="server" Text="OK" />
<asp:Button class="save-button2" ID="btnCancel" runat="server" Text="Cancel" />
</div>
</form>
</body>
</html>
Backend code - ReportSave.aspx.vb
Private Sub trvCategoryView_SelectedNodeChanged(sender As Object, e As EventArgs) Handles trvCategoryView.SelectedNodeChanged
Try
'Dim li As ListItem
'li = cblCategoryView.SelectedItem
Dim node As TreeNode
node = trvCategoryView.SelectedNode
' handle all categories
If node.Value.ToString.ToUpper = "NEW CATEGORY" Then
Dim strNC As String = InputBox("Enter Name for New Category", "Create Category")
If strNC = "" Then
Exit Sub
End If
If strNC.ToUpper = "NEW CATEGORY" Then
ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "window.alert('You can't have a Category Called New Category. Sorry!');", True)
Exit Sub
End If
Dim conn As New SqlClient.SqlConnection(_ConnectionString)
conn.Open()
Dim cmd As New SqlClient.SqlCommand("Select recordno from Reports where ReportType = '" & strNC & "'", conn)
Dim strresult As String = cmd.ExecuteScalar
If IsNothing(strresult) Then
Dim temp As TreeNode = New TreeNode(strNC, strNC, "Images/file.png")
' Dim temp As ListItem = New ListItem(strNC, strNC)
'lvCategoryView.Items.Add(temp)
'SetSelectedListItem(lvCategoryView.Items(lvCategoryView.Items.Count - 1))
'cblCategoryView.Items.Add(temp)
trvCategoryView.Nodes.Add(temp)
FillReports()
lblReportList.Text = "Report List for Group " & trvCategoryView.SelectedValue.ToString
' cblCategoryView.SelectedValue
ClientScript.RegisterStartupScript(Me.GetType(), "myalert", "window.alert('That Report Group Already Exists');", True)
End If
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
conn = Nothing
Exit Sub
Else
'SetSelectedListItem(li)
FillReports()
lblReportList.Text = "Report List for Group " & trvCategoryView.SelectedValue.ToString
'cblCategoryView.SelectedValue.ToString
End If
Catch ex As Exception
End Try
End Sub
Thanks for any help in advance! I am new to Web Development as well as ASP.NET. :)
I am making the assumption that you are loading this form into an iframe, and would guess that the problem lies in the implementation of the MyTreeView.SelectedNodeChanged event or the parent page itself.
Thinking outside the box, Web Forms may have alternate solutions to accomplish your objectives. The implementation of an iframe would be my least favorite. Depending on your specific requirements, these options may work better for you.
Nested Masterpages
Re-usable User Control (ascx) in overlay (popup) DIV element
Update Panel in overlay (popup) DIV element
AJAX post to Handler (ashx)

SQL connection will not display on gridview

I have a website and when a user logs in they can see their own information (username and a grid containing information about their medicines). This did load but now since I have moved it only loads the logged in user's username and does not display the grid that held their medicine information.I moved my project file from my laptop on to my college computer and ensured to change the location of where I was loading the data from :
Previously
"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Laura\Final_proj\App_Data\surgerydb.mdf;Integrated Security=True;Connect Timeout=30"
Now:
"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30"
This should work as the login uses the same data directory source and logs the user in. They are then redirected to the user.aspx page but now the grid does not display
user.aspx page (the query doesnt seem to be even running on this:
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_user
Inherits System.Web.UI.Page
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmdstring As String = "SELECT md.MedicineId, md.Name, md.Purpose, md.Instrcutions, DoctorId " +
"FROM Patient pt INNER JOIN prescription pr ON pt.PatientId = pr.PatientId " +
"INNER JOIN medicine md ON md.MedicineId = pr.MedicineId Where pt.PatientId = #PatientId"
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmdstring, conn)
da.SelectCommand.Parameters.Add("#PatientId", System.Data.SqlDbType.Int).Value = CInt(Session("PatientId").ToString())
conn.Open()
da.Fill(dt)
conn.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "UpdateMedicine" Then
Dim medecineID As Integer = Integer.Parse(e.CommandArgument.ToString())
End If
End Sub
The grid:
<asp:Content ID="Content3" ContentPlaceHolderID="contentbody" runat="Server">
<p>
Please Select Your Medication
</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Select" CommandName="UpdateMedicine" CommandArgument='<%# Eval("MedicineId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Purpose" HeaderText="Purpose" />
<asp:BoundField DataField="Instrcutions" HeaderText="Instructions" />
</Columns>
</asp:GridView>
</asp:Content>
What it looked like previously:
Hopefully someone can help
kind regards
After discussion, it turns out that Page_Load was not called, since AutoEventWireup was turned off and the event handler was not specified in code-behind. Either one of these two changes should work:
The event to handle can be specified in code-behind:
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
or AutoEventWireup can be turned on in the markup file:
<%# Page AutoEventWireup="true" ... %>

Dynamically Add Text Files to DDL in ASP & VB

I am looking to update one of my DDL's functionality by making it dynamically update so if the user adds more files, the drop down will pick this up.
At present my drop down list is pulling from VB code behind, as shown below:
Public Sub DDL_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddl As DropDownList = CType(sender, DropDownList) 'item is already dropdownlist
Dim ctl As TextBox = DirectCast(ddl.NamingContainer.FindControl("eTemplate"), TextBox)
If ddl.SelectedValue = 1 Then
ctl.Text = File.ReadAllText("e:Documents\Visual Studio 2013\Projects\Web\Templates\Down.txt")
ElseIf ddl.SelectedValue = 2 Then
ctl.Text = File.ReadAllText("e:Documents\Visual Studio 2013\Projects\Web\Templates\Up.txt")
Else
ctl.Text = ""
End If
End Sub
At the moment I have hard coded in the functionality for the VB to grab specific .txt files, how can I get this to update dynamically from a folder of .txt files?
Thanks for looking.
Here is some sample code for you. This demo uses an UpdatePanel and a Timer to refresh the DropdownList every 5 seconds.
Add a new aspx file to your Web Application and the following code:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Demo.aspx.vb" Inherits="Zpk_Test2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Asynchronous Update Demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1" />
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" /><br />
<asp:Timer runat="server" ID="Timer1" Interval="5000" Enabled="true" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="DropDownList1" />
</Triggers>
</asp:UpdatePanel>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Width="300" Height="250" />
</form>
</body>
</html>
This is the code-behind:
Partial Class Demo
Inherits System.Web.UI.Page
Private Const FolderName As String = "C:\Temp" '<-- replace with your folder name
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
RefreshDropDownList()
OpenSelectedFile()
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' this event is fired everytime a timer ticks.
' refresh your dropdown list here.
RefreshDropDownList()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
OpenSelectedFile()
End Sub
Private Sub RefreshDropDownList()
Dim currentSelected As String = DropDownList1.SelectedValue
DropDownList1.DataSource = IO.Directory.GetFiles(FolderName, "*.txt").Select(Function(f) IO.Path.GetFileName(f)).ToList
DropDownList1.DataBind()
DropDownList1.SelectedValue = currentSelected
End Sub
Private Sub OpenSelectedFile()
Dim fileName As String = IO.Path.Combine(FolderName, DropDownList1.SelectedValue)
TextBox1.Text = IO.File.ReadAllText(fileName)
End Sub
End Class

Resources