Displaying images - asp.net

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)

Related

ASP.NET page getting Timeout expired requiring the application pool being recycled every hour

My new application page is getting a timeout error every hour or so after getting some traffic on the page, and by traffic I mean users submitting 5-10 applications. How do I find the cause of the connections getting tied up?
This has been an issue in the past so whenever I use a sql data reader object I make sure to implement the "Using" statement. I've also made sure that the thread isn't aborted before the data reader is disposed of. I doubt that my use of data readers is the issue, so maybe it's my non-query code that's causing the issue, but I can't see why.
I also use a few sqldatasource objects for my dropdownlist controls, and as far as I know it wouldn't be the source of my issue.
See code example for how I use my sql objects.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Using drApp As SqlDataReader = LookupAppByID()
'some code
drApp.Close()
End Using
End Sub
Public Function LookupAppByID() As SqlDataReader
Dim Command As New SqlClient.SqlCommand
Command.Connection = GetDBConnection()
Command.CommandType = CommandType.Text
Command.CommandText = "select statement"
Return Command.ExecuteReader(CommandBehavior.CloseConnection)
End Function
Public Function UpdateAppStatus() As Integer
UpdateAppStatus = 0
Using Command As New SqlClient.SqlCommand("update statement", GetDBConnection())
UpdateAppStatus = Command.ExecuteNonQuery()
Command.Connection.Close()
Command.Connection.Dispose()
Command.Dispose()
End Using
End Function
Public Function GetDBConnection() As SqlClient.SqlConnection
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "connection string"
connection.Open()
Return connection
End Function
Obviously I expect it to chug along without a hitch but when users start hitting the page it gets this error: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Is there a problem with my code?
How can I narrow down what is causing this issue?
I would keep the database objects local so I can ensure that they are closed and disposed. Create and dispose within one method. I created a class so you can easily pass all its properties in a single variable.
'User Interface Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim id As Integer 'No sure where the value comes from
Using dtApp As DataTable = DataAccess.LookupAppByID(id)
'some code
End Using
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs) Handles Update.Click
Dim Applic As New ApplicationData()
Applic.ApplicantsName = txtName.Text
Applic.ID = CInt(txtID.Tex)
Applic.ApplicationStatus = "Approved"
Dim retVal = DataAccess.UpdateAppStatus(Applic)
If retVal = 1 Then
'Alert user of success
Else
'Alert user of failure
End If
End Sub
Public Class ApplicationData
Public Property ID As Integer
Public Property AppDate As Date
Public Property ApplicantsName As String
Public Property ApplicationStatus As String
End Class
Public Class DataAccess
Private Shared ConString As String = "Your connection string"
Public Shared Function LookupAppByID(AppID As Integer) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(ConString)
Using Command As New SqlCommand("select * From YourTable Where ID = #ID", cn)
Command.Parameters.Add("#ID", SqlDbType.Int).Value = AppID
cn.Open()
dt.Load(Command.ExecuteReader)
End Using
End Using
Return dt
End Function
Public Shared Function UpdateAppStatus(App As ApplicationData) As Integer
Dim AppStatus = 0
Using cn As New SqlConnection(ConString)
Using Command As New SqlClient.SqlCommand("Update YourTable Set Status = #Status Where ID = #ID;", cn)
Command.Parameters.Add("#Status", SqlDbType.VarChar, 50).Value = App.ApplicationStatus
Command.Parameters.Add("#ID", SqlDbType.Int).Value = App.ID
cn.Open()
AppStatus = Command.ExecuteNonQuery()
End Using
End Using
Return AppStatus
End Function
End Class

Can't read data from SQL Server database

I'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))

WebException was caught When Consuming RSS Feed on ASP.net

I want to consume my blog's RSS feed from other asp.net site. I can't get rss data. I try different methods (like HttpWebRequest) for consuming RSS feed but I always get same error.
WebException was caught.
The underlying connection was closed: An unexpected error occurred during an import operation.
What was the problem ?
feed address: http://blog.melihmucuk.com/feed/
I need post title, link and posted date.
for example :
Try
Dim reader As XmlTextReader = New XmlTextReader("http://blog.melihmucuk.com/feed/")
Dim ds As DataSet = New DataSet()
ds.ReadXml(reader) // incorrect line
Catch ex As Exception
End Try
I think, that's a simple task, but I don't know what is the problem.
Also I try this:
Try
Dim title As String
Dim link As String
Dim description As String
Dim reader = XmlReader.Create("http://blog.melihmucuk.com/feed/")//incorrect line
Dim feed = SyndicationFeed.Load(reader)
For Each item In feed.Items
title = item.Title.Text
link = item.Links(0).Uri.ToString
Next
HyperLink1.Text = title
HyperLink1.NavigateUrl = link
Label1.Text = description
Catch ex As Exception
End Try
Try this out:-
Imports System.Web
Imports System.Net
Imports System.IO
Public Class Reader
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim rssFeed = New Uri("http://blog.melihmucuk.com/feed/")
Dim request As WebRequest = WebRequest.Create(rssFeed)
Dim response As WebResponse = request.GetResponse()
Using reader As New StreamReader(response.GetResponseStream())
Dim xdoc As XDocument = New XDocument()
xdoc = XDocument.Load(reader)
'Read the nodes and display as per your requirement.
End Using
Catch ex As Exception
End Try
End Sub
End Class
Also add this block in your web.config file:-
<configuration>
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="true"/>
</defaultProxy>
</system.net>
</configuration>

SQL and GridView

I am currently doing a project on web service for wine. I have the wine table with wineName and wineType. Also I have the search function implemented in the webservice coding as well as a separate webform to call the function of the search function
I have the following code for performing search in the search service:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
Dim ds As New Data.DataSet
con.Open()
selectAdapter.Fill(ds, "Wine")
con.Close()
Return ds
End Function
As for the webform, it's just a simple page with textbox labeled as searchName, a button and a gridView1 tied to ObjectDataSource.
This is the coding i have for webform:
Partial Class Search
Inherits System.Web.UI.Page
Dim searching As searchwine.Service = New searchwine.Service
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If searchName.Text = "" Then
lblDisplayError.Text = "Can't search empty field!"
Else
Dim ds As DataSet = searching.Search(searchName.Text)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
GridView1.Visible = True
lblDisplayError.Visible = False
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDisplayError.Text = ""
GridView1.Visible = False
End Sub
End Class
Everything seems fine, but i have the following error when i want to do a search:
System.NullReferenceException: Object reference not set to an instance of an object. at Service.Search(String searchName)
Can anyone help me out please?
I've looked through your code a couple times and I can't see what's causing the NullReferenceException. My best guess is that it couldn't find a connection string name "ConnectionString" in your web.config file, but even that doesn't quite seem to fit.
I can suggest some improvements to your search code. Hopefully you'll at least get a better error message out of this:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim ds As New Data.DataSet()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(connectionString), _
cmd As New SqlCommand("SELECT * From Wine WHERE WineType= #SearchName", con)
'I had to guess at the exact length and type of the field here
cmd.Parameters.Add("#SearchName", SqlDbType.VarChar, 50).Value = searchName
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
selectAdapter.Fill(ds, "Wine")
End Using
Return ds
End Function
But in the end I expect you'll need to step through the method and see exactly which line above throws the exception.
Looks like you are missing a New
Dim ds As DataSet = searching.Search(searchName.Text)
Should be...
Dim ds As **New** DataSet = searching.Search(searchName.Text)

Accessing values from partial classes

Please help! I'm still learning so this might be completely wrong. I have built a multi-user web application for internal purposes. I have split my code up to make it more manageable and have run into some problems. I suspect that I have done something very silly!
I have a class in a separate file (quoteStatus.vb) in App_Code here it is:
Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Data
Public Class quoteStatusHelper
Public Shared QuoteStatus As String
Public Shared Sub GetQuoteStatus(ByVal QuoteID As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = ConfigurationManager.AppSettings("quotingSystemConnectionString")
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Status FROM Quote WHERE QuoteID =" & QuoteID & ";"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
QuoteStatus = lrd("Status")
End While
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
End Class
I use this to fire the code from another file:
quoteStatusHelper.GetQuoteStatus(QuoteID)
Then grab the result with
Dim returnedStatus = quoteStatusHelper.QuoteStatus
This seems really wrong, as the value seems to be held in the partial class after the first run. So if I have two users accessing the class the public shared dim is changed for both users! There must be a better way to do this. I have looked everywhere and I'm more confused now than when I started off...
How can I make QuoteStatus in the partial class unique to every user and access it from my code. I cant figure it out :( Please help
Many thanks in advance.
The problem is that your QuoteStatus variable is shared/static. You don't need to do that here. Declaring it as Public will make it visible to other classes. Remove Shared from the method and the QuoteStaus variable, and all should be well.
Once you remove Shared it will be an instance class, which means that you'll need to initialize it in your code:
Dim statusHelper As New quoteStatusHelper()
statusHelper.GetQuoteStatus("QuoteID")
EDIT
Taking a closer look at your code, it looks like you could make GetQuoteStatus a function that returns the QuoteStatus as a string, as #Claudio Redi suggested.
Public Function GetQuoteStatus(ByVal QuoteID As String) As String
Dim quoteStatus As String
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = ConfigurationManager.AppSettings("quotingSystemConnectionString")
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Status FROM Quote WHERE QuoteID =" & QuoteID & ";"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
quoteStatus = lrd("Status")
End While
Catch ex As Exception
Finally
con.Close()
End Try
Return quoteStatus
End Function
By making GetQuoteStatus a function, you'll be able to get the value like this:
Dim statusHelper As New quoteStatusHelper()
Dim quoteStatus As String = statusHelper.GetQuoteStatus("QuoteID")
An option would be using a local variable on your method for quoteStatus and using it as return value of GetQuoteStatus. So you wouldn't use anymore the shared member QuoteStatus
EDIT
Added a function example. You should remove your shared member QuoteStatus from your class. I don't use VB on my day to day work so I hope I didn't make any stupid syntax mistake
Public Shared Function GetQuoteStatus(ByVal QuoteID As String) as String
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim quoteStatus As String
Try
con.ConnectionString = ConfigurationManager.AppSettings("quotingSystemConnectionString")
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Status FROM Quote WHERE QuoteID =" & QuoteID & ";"
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
quoteStatus = lrd("Status")
End While
Catch ex As Exception
Finally
con.Close()
End Try
return quoteStatus
End Function

Resources