I'm having a trouble with displaying my image from the database(i'm using sql server 2008)
It says "Could not create type 'LeaveApplication.EmployeePhoto'."
Employee.aspx
<asp:Image ID="empPic" runat="server" Height="200px" ImageUrl="~/Images/pic.jpg" Width="200px" /></div>
Employee.aspx.vb
Dim ses As String
ses = Session("ses_empNum")
txtEmployeeNum.Text = ses
'empPic.ImageUrl = "../usrcontrols/EmployeePhoto.ashx?EmpNum'" & ses & "'"
empPic.ImageUrl = "../usrcontrols/EmployeePhoto.ashx?id=idkey'" & ses & "'"
EmplpyeePhoto.ashx.vb
Imports System.Web
Imports System.Web.Services
Imports System.Data
Imports System.Data.SqlClient
Public Class PatientPhoto
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim ID As New String(context.Request.QueryString("ID"))
Dim sqlConn As New SqlConnection("server=192.168.6.7;uid=sa;pwd=da;database=payroll_hospital;multipleactiveresultsets=true")
sqlConn.Open()
ID = Replace(ID, "^", "'")
Dim sqlComm As New SqlCommand("select dbImage from patient_data.dbo.tbdbImage where " & ID, sqlConn)
'context.Response.Write)
'Exit Sub
'context.Session.Item("test") = "select dbImage from patient_data.dbo.tbdbImage where " & ID
Dim dr As System.Data.SqlClient.SqlDataReader
dr = sqlComm.ExecuteReader
If dr.Read Then
context.Response.BinaryWrite(dr.Item("dbImage"))
Else
'Response.Write("File Not Found.")
context.Response.Write("<img src=../images/blank.jpg>")
End If
sqlConn.Close()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Employee.ashx
I bet you renamed a code class somewhere but did not update the code behind page. The code behind page does not know what the name is when it changes by hand.
Look for somewhere where you modified the class name.
public MyChangedClass:Page{}
<%# CodeBehind="MyChangedClass.aspx.cs" Class="MyOldClassName" %>
Related
I have Ajax AutoExtender control asociated with textbox. Suggested data are selected from database. But my AutoComplete code is not even fired. What can be wrong with the code? Thanks.
<asp:TextBox ID="txtSports" runat="server" CssClass="textbox" placeholder="Sport"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="1" ServicePath="~/AutoComplete.asmx" CompletionSetCount="20" CompletionInterval="0000" EnableCaching="true" UseContextKey="True" ServiceMethod="GetCompletionList" TargetControlID="txtSports" runat="server"></ajaxToolkit:AutoCompleteExtender>
AutoComplete.asmx file:
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports AjaxControlToolkit
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class AutoComplete
Inherits System.Web.Services.WebService
<System.Web.Services.WebMethodAttribute, System.Web.Script.Services.ScriptMethodAttribute> _
Public Shared Function GetCompletionList(prefixText As String, count As Integer, contextKey As String) As String()
Dim listString As New List(Of String)()
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("SportovniPlanetaCS").ConnectionString.ToString()
Using conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand((Convert.ToString("SELECT Sport, SportId FROM Sports WHERE Sport LIKE #Sport")))
cmd.Parameters.AddWithValue("#Sport", prefixText)
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read()
listString.Add(AutoCompleteExtender.CreateAutoCompleteItem(dr("Sport").ToString(), dr("SportId").ToString()))
End While
End If
End Using
Dim str As String() = listString.ToArray()
Return str
End Function
End Class
Well i Don't think you need to use a separate WebService for it. you could create a web method and make it work.
You could see example here...
AutoComplete Demonstration
In AjaxToolKit add
OnClientItemSelected="ClientItemSelected"
add javascript
function ClientItemSelected(source, e)
{
source.get_element().value = (document.all) ? e._item.innerText : e._item.textContent;
var str = $('#<%=txtsports.ClientID %>').val();
}
I am new at ASP.net and VB.net.So i Learn from book beginning ASP.Net 3.5 in VB 2008
the code on select.aspx.vb are
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration
Partial Public Class _Select
Inherits System.Web.UI.Page
Private Conn As String = WebConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
FillAuthorList()
End If
End Sub
Private Sub FillAuthorList()
lstAuthor.Items.Clear()
' Define the Select statement.
' Three pieces of information are needed: the unique id
' and the first and last name.
Dim selectSQL As String = "SELECT Nama_Depan, Nama_Belakang, ID FROM Employee"
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
' For each item, add the author name to the displayed
' list box text, and store the unique ID in the Value property.
Do While reader.Read()
Dim newItem As New ListItem()
newItem.Text = reader("Nama_Depan") & ", " & reader("Nama_Belakang")
newItem.Value = reader("ID").ToString()
lstAuthor.Items.Add(newItem)
Loop
reader.Close()
Catch err As Exception
lblResults.Text = "Error reading list of names."
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
Protected Sub lstAuthor_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstAuthor.SelectedIndexChanged
' Create a Select statement that searches for a record
' matching the specific author ID from the Value property.
Dim selectSQL As String
selectSQL = "SELECT * FROM Employee "
selectSQL &= "WHERE ID='" & lstAuthor.SelectedItem.Value & "' "
' Define the ADO.NET objects.
Dim con As New SqlConnection(Conn)
Dim cmd As New SqlCommand(selectSQL, con)
Dim reader As SqlDataReader
' Try to open database and read information.
Try
con.Open()
reader = cmd.ExecuteReader()
reader.Read()
' Build a string with the record information,
' and display that in a label.
Dim sb As New StringBuilder()
sb.Append("<b>")
sb.Append(reader("Nama_Depan"))
sb.Append(", ")
sb.Append(reader("Nama_Belakang"))
sb.Append("</b><br />")
lblResults.Text = sb.ToString()
reader.Close()
Catch err As Exception
lblResults.Text = "Error getting author. "
lblResults.Text &= err.Message
Finally
con.Close()
End Try
End Sub
End Class
And the select.aspx are
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Select.aspx.vb" Inherits="connn._Select" %>
<!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>
<asp:ListBox ID="lstAuthor" runat="server" ></asp:ListBox>
<br />
<asp:Label ID="lblResults" runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
I am trying when select Listbox with ID="lstAuthor" the label box will pass the value but it failed to show.
Set True to AutoPostBack property:
<asp:ListBox ID="lstAuthor"
runat="server"
AutoPostBack="True" ></asp:ListBox>
How to access controls from class files in app code?
Markup:
<%# Page Language="vb" AutoEventWireup="false" Inherits="shoppingCart1.ShoppingPage" CodeFile="ShoppingPage.aspx.vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>ShoppingPage</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server" name="Form1">
<TABLE id="tblShopping" style="FONT-SIZE:10pt;FONT-FAMILY:verdana" borderColor="black"
width="100%" cellSpacing="0" cellPadding="0" border="1" runat="server">
<tr style="FONT-SIZE:10pt;FONT-FAMILY:verdana;color:white;background-color:#336699;font-weight:bold;">
<td colspan="4">PRODUCT LIST</td>
</tr>
<tr>
***<td id="cellshoping" runat="server" colspan="4" width="100%"></td>***
</tr>
<tr>
</tr>
</TABLE>
</form>
</body>
</HTML>
ShoppingCart.vb In App_Code Folder
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ShoppingCart
Public Sub bindData()
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
**cellshoping**.InnerHtml = strRowGen
End While
End Sub
End Class
I get an error at cellshoping.InnerHtml "cellshoping is not declared"...how to access user controls from class files in app code ??
ADDED ASPX CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Namespace shoppingCart1
Partial Class ShoppingPage
Inherits System.Web.UI.Page
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents txtNK As System.Web.UI.WebControls.TextBox
Protected WithEvents txtCF As System.Web.UI.WebControls.TextBox
Protected WithEvents txtHA As System.Web.UI.WebControls.TextBox
Protected WithEvents dtGrdProducts As System.Web.UI.WebControls.DataGrid
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
'Load data by calling function bindData()
Dim sCart = New ShoppingCart
If Not Page.IsPostBack Then
cellshoping.InnerHtml = sCart.bindData()
End If
Dim strQty As Integer
Dim proId As String
Dim delId As String
delId = Request.QueryString("delItemId")
proId = Request.QueryString("itemId")
'------ Following portion act as controller where code is written as
'------ per the action from the request of the pages like Add To Cart,
'------ Update Cart & Delete Cart
strQty = 1
If Request.QueryString("Actn") <> "" Then
If Request.QueryString("Actn").Equals("Add") Then
If Request.QueryString("itemId") <> "" Then
AddToSession(proId, strQty)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Del") Then
If Request.QueryString("delItemId") <> "" Then
Session.Remove(delId)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Update") Then
If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then
If IsNumeric(Request.QueryString("itemUpId")) Then
updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))
Response.Redirect("./ShoppingCart.aspx")
Else
Response.Redirect("./ShoppingCart.aspx")
End If
End If
End If
End If
End Sub
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
Else
Session.Add(strProduct, intQty)
End If
End Sub
Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(qty))
End If
End Sub
End Class
End Namespace
Assuming that the ShoppingCart class is referenced somewhere in the page's code-behind and the BindData() method is called from that code, you have a few choices:
1) Pass a reference to the page to the shopping cart's bind data method.
2) Return the data from the BindData() method to the page so that it can update the data in the page appropriately.
3) You could access HttpContext.Current.Handler and cast that to an instance of your page.
My recommendation, especially if you want to use the class in other pages, is to either create an interface that has a method that can be used to update the data and use options 1 or 3, or implement option 2.
Here is an example of how you would change the code to implement and interface.
The interface:
Public Interface IShoppingCartPage
Sub UpdateData(sCartContents As String)
End Interface
The page codebeghind (partial):
Public Class ShoppingPage
Implements IShoppingCartPage
Public Sub UpdateData(sCartContents As String) Implements IShoppingCartPage.UpdateData
cellshopping.innerHtml = sCartContents
End Sub
End Class
And finally, the modified shopping cart class (note the use of the stringbuilder class, which will be much more efficient than the string concat in the question):
Public Class ShoppingCart
Public Sub bindData(oPage As IShoppingCartPage)
Using con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Using comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
Using oReader As SqlDataReader = comd.ExecuteReader()
Dim sbHTML As New System.Text.StringBuilder(5000)
While oReader.Read()
sbHTML.Append("<TR>")
sbHTML.Append("<TD>").Append(oReader.GetValue(0)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(1)).Append("</TD>")
sbHTML.Append("<TD>").Append(oReader.GetValue(2)).Append("</TD>")
sbHTML.Append("<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=").Append(oReader.GetValue(0)).Append("';document.Form1.submit();"">Add To Cart</TD>")
sbHTML.Append("</TR>")
End While
oPage.UpdateData(sbHTML.ToString())
End Using
End Using
con.Close()
End Using
End Sub
End Class
Why not have your method return a string?
Public Function bindData() as String
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim objDA As SqlDataAdapter
Dim myRow As SqlDataReader
Dim comd As New SqlCommand("SELECT * FROM products", con)
con.Open()
myRow = comd.ExecuteReader()
Dim strRowGen As String = ""
While myRow.Read()
strRowGen = strRowGen & "<TR>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
strRowGen = strRowGen & "</TR>"
End While
Return strRowGen
End Sub
Then you can call it from your page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
'Set innerHtml here
'cellshoping.InnerHtml = ShoppingCart.bindData()
End Sub
in a web application, i want to insert the XML file content into an access database, i got the code (below), but there is an error with this line
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
this error appear
please take a look at the code below and tell me how to modify to get the "product.xml" from the web application root folder. i tried "~/product.xml" and it did not work
Imports Microsoft.VisualBasic
Imports System.Xml
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Public Shared Sub mimi()
Dim connetionString As String
Dim connection As OleDbConnection
Dim command As OleDbCommand
Dim ds As New DataSet
Dim xmlFile As XmlReader
Dim sql As String
Dim adpter As New OleDbDataAdapter
Dim product_ID As Integer
Dim Product_Name As String
Dim product_Price As Double
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|CRF.mdb;Persist Security Info=True"
connection = New OleDbConnection(connetionString)
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
ds.ReadXml(xmlFile)
Dim i As Integer
connection.Open()
For i = 0 To ds.Tables(0).Rows.Count - 1
product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0))
Product_Name = ds.Tables(0).Rows(i).Item(1)
product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2))
sql = "insert into Product values(" & product_ID & ",'" & Product_Name & "'," & product_Price & ")"
command = New OleDbCommand(sql, connection)
adpter.InsertCommand = command
adpter.InsertCommand.ExecuteNonQuery()
Next
connection.Close()
End Sub
End Class
try to use HttpContext.Current.Server.MapPath("~/Product.xml")
My instructor gave us example code that is very similiar to the code below. I haven't heard back from him yet and wanted to find out why my code won't work properly. Could someone give me some advice on what I'm doing wrong or an easier method to display images. Thanks for your time.
<%# WebHandler Language="VB" Class="images" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Public Class images : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim id As String = context.Request.QueryString("ImageId")
Dim userId As Integer = 4
Dim conn As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = conn
cmd.CommandText = "SELECT Image FROM mrg_Image WHERE UserId=#userId"
cmd.Parameters.AddWithValue("#userId", userId)
conn.Open()
Dim file_bytes As Byte() = cmd.ExecuteScalar()
Dim file_bytes_stream As New System.IO.MemoryStream(file_bytes)
'During the build - The next line of code is highlighted green with the error message of, "Parameter is invalid"
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
context.Response.ContentType = "image/jpg"
the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
conn.Close()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
EDIT: Answer (such as it is) in comments. The questioners code is fine...
Looks fine to me. Are you comitting an implict type conversion between the first and last lines below?
Dim file_bytes_stream As New System.IO.MemoryStream(file_bytes)
'During the build - The next line of code is highlighted green with the error message of, "Parameter is invalid"
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
If you have option explicit set you might need to do...
Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes)
Dim file_bytes_stream as System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream)
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)