Binary Image Not Visible From Live Sql Table ASP.NET - 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.

Related

Require logging in to view page

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>

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" ... %>

display image from db alongside other webpage elements

A continuation of the question on display (not download) image from db
<%# Page Language="VB" AutoEventWireup="false" CodeFile="imgTest1.aspx.vb" Inherits="imgTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="background-color: aliceblue;">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<br />
</div>
<div style="background-color: burlywood;">
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?id=1" />
<br />
<br />
<br />
</div>
</div>
</form>
</body>
</html>
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class imgTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Request.QueryString("id") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "filename=" & dt.Rows(0)("name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("CapstoneConnectionString1").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
End Class
I can now display the image on the aspx page but only the image is being displayed, all other web elements are missing.
I can only think of one reason for this, given that following are true:
Page used to render contents is imgTest1.aspx as well as page used to return image is also imgTest1.aspx.
imgTest1.aspx is always invoked with query parameter, id.
because of this page always returns an image.
Can you change the code as follows and tell us how it works:
...
...
<asp:Image ID="Image1" runat="server" ImageUrl="imgTest1.aspx?imageId=1" />
...
...
and in code-behind
If Request.QueryString("imageId") IsNot Nothing Then
Dim strQuery As String = "select name, contentType, data from [imageTest] where id=1"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32("1")

Using SqlBulkCopy SqlRowsCopied to update a label

I have a simple web application that is reading records from a CSV file and storing them in a database table. Then I am using SqlBulkCopy to copy the records into an SQL database using batches. All is fine with the insert. I am trying to give the user some feedback using OnSqlRowsCopied and NotifyAfter. The goal is to update a label that is contained in an UpdatePanel to display the number of records copied at the current NotifyAfter interval. However, the label will not update until SqlBulkCopy has complete. I can see that the s_OnSqlRowsCopied event is firing using Debug.WriteLine. What is the reason why the label won't update and how can I overcome this?
Code Behind
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Dim filePath As String
Dim rowsCopied As String
Public Sub btnGetCSV_Click(sender As Object, e As EventArgs) Handles btnGetCSV.Click
filePath = System.IO.Path.GetFullPath(fileUpload1.PostedFile.FileName)
lblInfo.Text = filePath
End Sub
Protected Sub btnToSQL_Click(sender As Object, e As EventArgs) Handles btnToSQL.Click
Dim cs As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("csMediaPortal").ConnectionString
CopyData(CSVtoDataTable(lblInfo.Text.ToString()), cs)
End Sub
Private Function CSVtoDataTable(filePath As String) As DataTable
Dim dt As DataTable = Nothing
Dim sourcePath As String = String.Empty
Dim csvFile As String = String.Empty
Dim conString As String = String.Empty
Dim conn As OleDb.OleDbConnection = Nothing
Dim adapter As OleDb.OleDbDataAdapter = Nothing
Dim selString As String = String.Empty
Try
sourcePath = System.IO.Path.GetDirectoryName(filePath)
csvFile = System.IO.Path.GetFileName(filePath)
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sourcePath & ";Extended Properties=""text;HDR=No;FMT=FixedLength"""
conn = New OleDb.OleDbConnection(conString)
selString = "Select * From " & csvFile
adapter = New OleDb.OleDbDataAdapter(selString, conn)
dt = New DataTable(System.IO.Path.GetFileNameWithoutExtension(filePath))
conn.Open()
adapter.Fill(dt)
conn.Close()
Catch ex As Exception
lblInfo.Text = ex.Message
Finally
adapter.Dispose()
conn.Dispose()
End Try
Return dt
End Function
Protected Sub CopyData(sourceTable As DataTable, cs As String)
Using s As SqlBulkCopy = New SqlBulkCopy(cs, SqlBulkCopyOptions.UseInternalTransaction)
s.DestinationTableName = "test"
s.BatchSize = 1000
Try
AddHandler s.SqlRowsCopied, AddressOf s_OnSqlRowsCopied
s.NotifyAfter = 900
s.WriteToServer(sourceTable)
Catch ex As Exception
DirectCast(DirectCast(HttpContext.Current.Handler, Page).FindControl("lblInfo"), Label).Text = "Commit Error: " & ex.Message
End Try
s.Close()
End Using
End Sub
Protected Sub s_OnSqlRowsCopied(sender As Object, e As SqlRowsCopiedEventArgs)
Me.lblProgress.Value = e.RowsCopied.ToString()
Me.UpdatePanel1.Update()
Debug.WriteLine(e.RowsCopied)
End Sub
End Class
Web Form
<%# Page Language="vb" CodeBehind="WebForm1.aspx.vb" Inherits="CSVUpload.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:FileUpload ID="fileUpload1" runat="server" />
<asp:Button ID="btnGetCSV" runat="server" Text="Post" OnClick="btnGetCSV_Click" />
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
</div>
<asp:Button ID="btnToSQL" runat="server" Text="Insert To SQL" OnClick="btnToSQL_Click" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<input runat="server" type="text" id="lblProgress" value="0" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

OnClientClick does not work with asp.net and vb.net

I try to create a dynamic web solution with ASP.NET and VB.
My webpage looks like this:
<div id="menu" style="position:relative;text-align:center">
<asp:PlaceHolder runat="server" id="PHimg1" />
<asp:PlaceHolder runat="server" id="PHimg2" />
<asp:PlaceHolder runat="server" id="PHimg3" />
<br />
<asp:PlaceHolder runat="server" id="PHimg4" />
<asp:PlaceHolder runat="server" id="PHimg5" />
<asp:PlaceHolder runat="server" id="PHimg6" />
<br />
<asp:PlaceHolder runat="server" id="PHimg7" />
<asp:PlaceHolder runat="server" id="PHimg8" />
<asp:PlaceHolder runat="server" id="PHimg9" />
</div>
The VB part like this:
Public Class index
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Load_Main()
End Sub
Protected Sub Load_Main()
Dim img1 As New ImageButton()
Dim img2 As New ImageButton()
Dim img3 As New ImageButton()
Dim img4 As New ImageButton()
Dim img5 As New ImageButton()
Dim img6 As New ImageButton()
img1.ImageUrl = "./resources/EssenTrinken.png"
img1.OnClientClick = "Load_Eating()"
img2.ImageUrl = "./resources/Einkaufen2-black.png"
img3.ImageUrl = "./resources/Special-black.png"
img4.ImageUrl = "./resources/KosmetikWellness.png"
img5.ImageUrl = "./resources/KulturGeschichte.png"
img6.ImageUrl = "./resources/Unterhaltung2-black.png"
PHimg1.Controls.Add(img1)
PHimg2.Controls.Add(img2)
PHimg4.Controls.Add(img3)
PHimg5.Controls.Add(img4)
PHimg7.Controls.Add(img5)
PHimg8.Controls.Add(img6)
End Sub
Protected Sub Load_Eating()
Dim img1 As New ImageButton()
Dim img2 As New ImageButton()
Dim img3 As New ImageButton()
Dim img4 As New ImageButton()
Dim img5 As New ImageButton()
Dim img6 As New ImageButton()
img1.ImageUrl = "./resources/zurueck.png"
img2.ImageUrl = "./resources/Bars2.png"
img3.ImageUrl = "./resources/Cafe.png"
img4.ImageUrl = "./resources/FastFood2.png"
img5.ImageUrl = "./resources/Restaurant.png"
img6.ImageUrl = "./resources/Baeckerei.png"
PHimg1.Controls.Add(img1)
PHimg2.Controls.Add(img2)
PHimg3.Controls.Add(img3)
PHimg4.Controls.Add(img4)
PHimg5.Controls.Add(img5)
PHimg6.Controls.Add(img6)
End Sub
End Class
I want that if I click on one of the imagebutton the hole appereance of the frontpage dynamicly changes without loading the hole page new. So I defined several PlacHolder for that.
If I run the webapp but the functionality is not working if I hit the button.
I checked the source and found this tag:
<input type="image" name="ctl03" src="./resources/EssenTrinken.png" onclick="Load_Eating();" />
What is wrong with this solution?
If you are trying to do this from the code behind, then you need to add the Click event handler:
Protected Sub Load_Main()
Dim img1 As New ImageButton()
AddHandler img1.Click, AddressOf Img1Click
'rest of your code
and then have some function that does what you want:
Private Sub Img1Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
'some code
End Sub
Note, this will cause a postback. It is confusing on how you expect to dynamically change the front page without reloading the page and without using JavaScript...
Add to your Page_load a check for IsPostBack
if Not IsPostBack Then
Load_main()
End If
This will prevent your page_load method to recreate every button and resetting the value for the Image_click event

Resources