display uploded image in image control - asp.net

i want to upload an image to a folder which is in my website's folder and then save it's path to database and display the uploaded image in control image.
when i executed my page the image is uploaded succefully and it's saved to database but it dosent displayed on the image control.
this is my view :
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!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">
<div>
</div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Image ID="Image1" runat="server" Height="91px" Width="145px" />
</form>
<p>
</p>
</body>
</html>
and this is my code :
Imports System.Data.SqlClient
Imports System.IO
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim cn As SqlConnection
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If FileUpload1.PostedFile IsNot Nothing Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("~/im/" & FileName))
'Add Entry to DataBase
Dim strQuery As String = "insert into dbo.images" & " values(#FileName, #FilePath)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#FileName", FileName)
cmd.Parameters.AddWithValue("#FilePath", "~/im/" & FileName)
cmd.CommandType = CommandType.Text
cmd.Connection = cn
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cn.Close()
cn.Dispose()
End Try
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn = New SqlConnection("server=SEVO-PC;initial catalog=controle;integrated security=true")
End Sub
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = "im/" & FileUpload1.FileName
End Sub
End Class

Try the following edit
Protected Sub FileUpload1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles FileUpload1.Load
Image1.ImageUrl = Server.MapPath("/im/") & FileUpload1.FileName
End Sub

Related

Create Chart using Fusionchart and get data from database in VB.NET

I want to create a bar chart using fusionchart, and get the data from database
This is my UI, if I click this link will go to the chart page
FRONT CODE FOR UI PAGE (Statistics.aspx)
<form id="form_statistics" runat="server">
<div>
<label for="name"></label>
<asp:DropDownList ID="ddlGender" runat="server"></asp:DropDownList>
<asp:Button ID="BtnSearch" runat="server" Text="Search" />
<br/><br/>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
<asp:Repeater ID="repGender" runat="server">
<HeaderTemplate>
<table cellspacing="0" rules="all" border="1">
<tr>
<th>Gender</th>
<th>Total</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("GENDER")%>
</td>
<td style="text-align: center">
<a href='<%# "Chart.aspx?GENDER_ID=" & Eval("GENDER") & ""%>'> <%# Eval("TOTAL")%></a>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr style="font-weight: bold">
<td>Grand Total</td>
<td style="text-align: center">
<asp:Label runat="server" ID="lblTotal"></asp:Label>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
BEHIND CODE Statistics.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Statistics
Inherits App.Main
Dim MyTotal As Integer
Dim MethodBase As Object
Private Property Label As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
ddlGender_Bind()
End If
End Sub
Sub BindData()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_BB") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
Protected Sub repGender_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles repGender.ItemCommand
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
End Sub
Protected Sub repGender_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repGender.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim gData As DataRowView = e.Item.DataItem
MyTotal = MyTotal + gData.Item("TOTAL")
End If
If e.Item.ItemType = ListItemType.Footer Then
' set the total value in footer
Dim lblTotal As Label = e.Item.FindControl("lblTotal")
lblTotal.Text = MyTotal
End If
End Sub
Public Sub ddlGender_Bind()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
If dal.DB.ExecuteProcedure(dt, "GENDER_R") Then
Share.LoadList(ddlGender, "GENDER", "GENDER_ID", dt, Enums.MsgCode.PleaseSelect.ToString, ListOrder.ByValue)
End If
End Sub
Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
dal.DB.Parameters.Clear()
dal.DB.AddParameter("#GENDER", ddlGender.SelectedValue)
If dal.DB.ExecuteProcedure(dt, "GENDER_B") Then
repGender.DataSource = dt
repGender.DataBind()
End If
End Sub
End Class
FRONT CODE FOR Chart.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Chart.aspx.vb" Inherits="Chart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<!-- Include jQuery -->
<script type="text/javascript" src=" https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Include fusioncharts core library file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<!-- Include fusion theme file -->
<script type="text/javascript" src=" https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<!-- Include fusioncharts jquery plugin -->
<script type="text/javascript" src=" https://rawgit.com/fusioncharts/fusioncharts-jquery-plugin/develop/dist/fusioncharts.jqueryplugin.min.js"></script>
<title>Chart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
BEHIND CODE Chart.aspx
Imports System.Data.SqlClient
Imports System.IO
Imports WebUserCtrl
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports FusionCharts.Charts
Imports System.Reflection
Partial Class Chart
Inherits App.Main
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If Not IsPostBack Then
CreateChart()
End If
End Sub
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
End Class
I can go to the other page(Chart.aspx) but I did not get the output, the data is not display. I am not sure where should I put the
Sub CreateChart()
Dim dal As New DBWrapper.DAL(strConnectionString, strProviderName)
Dim dt As New DataTable
Dim jsonData As New StringBuilder()
Dim ReqComma As Boolean = False
jsonData.Append("{'chart': {")
jsonData.Append("'caption': 'Chart',")
jsonData.Append("'yAxisName': 'Number',")
jsonData.Append("'theme': 'fusion'")
jsonData.Append("},")
jsonData.Append("'data' : [")
For Each dr As DataRow In dt.Rows
If ReqComma Then
jsonData.Append(",")
Else
ReqComma = True
End If
jsonData.Append("{" + "'label': '" & Replace(dr("GENDER"), "'", "\'") & "', 'value': '" & dr("TOTAL") & "'" + "}")
Next
jsonData.Append("]")
jsonData.Append("}")
Dim ChartOutput As New FusionCharts.Charts.Chart("column2d", MethodBase.GetCurrentMethod().Name, "100%", "300", "json", jsonData.ToString())
Literal1.Text = ChartOutput.Render()
End Sub
It is either at behind code at Statistics.aspx or Chart.aspx. Please help me, I am new with vb.net

In vb asp.net I'm unable to obtain the selected TreeView node

The problem I'm having is: when a node is clicked, the selected node index is always -1 and the selected node text is always the text of the first node.
As you can see in the code below, I've created a test-app. This test-app shows the same problem
This is my Default.aspx:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="Treeviewer._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="tvDir" OnSelectedNodeChanged="tvDir_SelectedNodeChanged" OnTreeNodeExpanded="tvDir_TreeNodeExpanded" runat="server"></asp:TreeView>
</div>
</form>
</body>
</html>
And this is the code-behind:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tvDir.Nodes.Add(New TreeNode("C:\"))
For Each aDir As String In IO.Directory.EnumerateDirectories("C:\")
Dim aNode As TreeNode = New TreeNode(aDir, 0)
If hasSubDirectories(aDir) Then
aNode.ChildNodes.Add(New TreeNode("", 1))
End If
aNode.SelectAction = TreeNodeSelectAction.Select
tvDir.Nodes(0).ChildNodes.Add(aNode)
Next
tvDir.CollapseAll()
End Sub
Protected Sub tvDir_SelectedNodeChanged(sender As Object, e As EventArgs)
Dim tvIndex = tvDir.Nodes.IndexOf(tvDir.SelectedNode)
Debug.Write(tvIndex & " " & tvDir.SelectedNode.Text)
End Sub
Protected Sub tvDir_TreeNodeExpanded(sender As Object, e As TreeNodeEventArgs)
End Sub
Private Function hasSubDirectories(inDirectory As String) As Boolean
Try
If IO.Directory.Exists(inDirectory) Then
Return IO.Directory.EnumerateDirectories(inDirectory).Count > 0
End If
Catch ex As Exception
'
End Try
Return False
End Function
End Class

How to generate PDF with current pageweb in vb.net?

I want to to generate a PDF with all my tables, I searched on google and I found code above and work but for o image and some text:
Imports System.Web
Imports System.Web.UI
Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnPDF_Click(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub
End Class
This is page with code and in desgin mode is that:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="VBCode.aspx.vb" Inherits="VBCode" EnableEventValidation="false" %>
<!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>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div><img src="https://lh5.googleusercontent.com/_B28NJpJ61hA/TdgnS7lh7mI/AAAAAAAAAi4/oLTicIRgEIw/FinalLogo.png" /></div>
<div><b>Export Webpage with images to pdf using itextsharp dll</b>
<br />
</div><br />
<div>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>
</form>
</body>
</html>
I want to generate pdf withh my asp table and what i want in him but doesn't work, if you have an alternative please help me....
if i put my code with all codes give me that error:
Invalid URI: The hostname could not be parsed.
On line: htmlparser.Parse(sr)

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

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>

Resources