Do we need to create an HttpHandler(ashx) for each image? - asp.net

In my page i'm trying to show two images which have the same id. For that, I have two image controls(imgX,imgY). To write the image to the image control I am using an HttpHandler(ashx).
My problem is that i'm getting the same image appending to both controls(imgX,imgY)
In page load event this is my code:
imgPhoto.ImageUrl = "Image.ashx?EmpBadge=" & Session("EmpBadge")
imgSign.ImageUrl = "Image.ashx?EmpBadge=" & Session("EmpBadge")
And in ashx:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Try
Dim imageId As String = context.Request.QueryString("EmpBadge")
Dim drPhoto As SqlDataReader
Dim param(1) As SqlParameter
param(1) = New SqlParameter("#EmpBadge", imageId)
drPhoto = IMSIndia.ExecuteReaderWithParam("SpGetPhotoAndSignature", param)
If drPhoto.HasRows Then
While drPhoto.Read()
context.Response.ContentType = "image/" & drPhoto("PhotoType")
context.Response.BinaryWrite(DirectCast(drPhoto("Photo"), Byte()))
context.Response.ContentType = "image/" & drPhoto("Signaturetype")
context.Response.BinaryWrite(DirectCast(drPhoto("Signature"), Byte()))
End While
End If
Catch ex As Exception
Finally
If IMSIndia.con.State = ConnectionState.Open Then
IMSIndia.ConnectionClose()
End If
End Try
End Sub
Thanks.

Umm... of course you are getting the same image for each; you are passing exactly the same URL for each. You are using the same Session value for both.
Then, in your code you seem to be trying to send two images within the same response. That makes no sense at all, to the point that I'm not sure if it's related to this problem in the first place.
You need to differ the image based on the QueryString value. Your handler can't tell the difference unless you do.

You should be altering your code like this.
At Page_Load
imgPhoto.ImageUrl = "Image.ashx?ImageType=photo&EmpBadge=" & Session("EmpBadge")
imgSign.ImageUrl = "Image.ashx?ImageType=signature&EmpBadge=" & Session("EmpBadge")
Inside the while loop inside the ProcessRequest, place an if-else like this.
If drPhoto.HasRows Then
While drPhoto.Read()
If context.Request.QueryString("ImageType") = "photo" Then
context.Response.ContentType = "image/" & drPhoto("PhotoType")
context.Response.BinaryWrite(DirectCast(drPhoto("Photo"), Byte()))
Else
context.Response.ContentType = "image/" & drPhoto("Signaturetype")
context.Response.BinaryWrite(DirectCast(drPhoto("Signature"), Byte()))
End If
End While
End If

Related

Validation Summary

I use a login entrance in my Asp.Net project
And I use validationSummary for User Name and password.
Everything goes well but.
What I want is to know if the ValidationSummary has errors to show me or not before the appearance of the errors window
I use vb.net to build the project
I don't have any code to show. And also I can't find anything relative in on the Internet to assist me on this issue.
You are probably using the ValidationSummary method in your Razor views, which - as per MSDN
Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object.
So, if you want to know if there will be any errors shown by the ValidationSummary method, you can check this ModelStateDictionary in your controller before delivering your response to the browser. Doing this is described i.e. here (in C#).
In your controller method you can access ModelState.IsValid if you want to know if there are any errors which will be displayed.
This does directly answer your question, but this might not be the optimal way to achieve what you want when looking at the bigger picture. If you want to i.e. do something special if the login fails in your controller you should check directly if the login failed, not if some other method added model errors. To provide an answer, which might be more on point, you need to clarify your question and add more details about what you specifically want to do and possibly add some of your code too.
The idea to use the code I post is finally correct.
Public Sub IsGroupValid(ByVal sValidationGroup As String, ByVal sender As Object, ByVal e As EventArgs)
For Each validator As BaseValidator In Validators
If validator.ValidationGroup = sValidationGroup Then
Dim fValid As Boolean = validator.IsValid
Dim CtrlToValidate As String = validator.ControlToValidate
validator.DataBind()
If Not fValid And CtrlToValidate = ServerHandler.UName Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRq Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRegEx Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
End If
End If
Next
End Sub
But has condition that someone or something give him the error list from ValidationSummaryGroup
And this is done with the following code
Public Function LoadModel(ByVal sender As Object, ByVal e As EventArgs) As Boolean
Dim retVal As New Boolean
Try
If Not ModelState.IsValid Then
Dim result As StringBuilder = New StringBuilder()
For Each item In ModelState
Dim key As String = item.Key
Dim errors = item.Value.Errors
For Each [vError] In errors
ModelAnswer.Add(key & "^" & [vError].ErrorMessage)
retVal = True
Next
Next
End If
ModelState.Clear()
Catch ex As Exception
Environment.AssemblyInfo.ErrorAnswer = ServerHandler.ErrHandler.GetError(3, Nothing, Nothing, ex, Nothing)
Environment.AssemblyInfo.ErrorAnswer = Environment.AssemblyInfo.ErrorAnswer & "\r\n ifExistConsistencyRecord "
ServerHandler.ErrProperty._InnerError = Environment.AssemblyInfo.ErrorAnswer
Environment.AssemblyInfo.errorCall = True
retVal = False
End Try
Return retVal
End Function
Of course ModelAnswer is an ArrayList and declared as Public
And all this under the very basic prerequisite, all the processes to work within the main page and NOT in a "class"
Thank you very much for those who helped to solve this puzzle

How to get Description of Youtube embeded videos in my asp.net application?

I am using the below code to get the Title and description of the youtube video embeded in my asp.net application. I am able to see the Title, but not description.
I use Atomfeed to do this...
Problem is i get the Description as "Google.GData.Client.AtomTextConstruct" for all my videos.
Private Function GetTitle(ByVal myFeed As AtomFeed) As String
Dim strTitle As String = ""
For Each entry As AtomEntry In myFeed.Entries
strTitle = entry.Title.Text
Next
Return strTitle
End Function
Private Function GetDesc(ByVal myFeed As AtomFeed) As String
Dim strDesc As String = ""
For Each entry As AtomEntry In myFeed.Entries
strDesc = entry.Summary.ToString()
Next
Return strDesc
End Function
I believe that when the XML from the atom feed is parsed, that the description is not handled. Take a look at this: http://code.google.com/p/google-gdata/wiki/UnderstandingTheUnknown
But what happens with things that are not understood? They end up as
an element of the ExtensionElements collection, that is a member of
all classes inherited from AtomBase, like AtomFeed, AtomEntry,
EventEntry etc...
So, what we can do is pull out the description from the extensionelement like this:
Dim query As New FeedQuery()
Dim service As New Service()
query.Uri = New Uri("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated")
Dim myFeed As AtomFeed = service.Query(query)
For Each entry In myFeed.Entries
For Each obj As Object In entry.ExtensionElements
If TypeOf obj Is XmlExtension Then
Dim xel As XElement = XElement.Parse(TryCast(obj, XmlExtension).Node.OuterXml)
If xel.Name = "{http://search.yahoo.com/mrss/}group" Then
Dim descNode = xel.Descendants("{http://search.yahoo.com/mrss/}description").FirstOrDefault()
If descNode IsNot Nothing Then
Console.WriteLine(descNode.Value)
End If
Exit For
End If
End If
Next
Next
Also, the reason why you are getting "Google.GData.Client.AtomTextConstruct" is because Summary is an object of type Google.GData.Client.AtomTextConstruct, so doing entry.Summary.ToString() is just giving you the default ToString() behavior. You would normally do Summary.Text, but this of course is blank because as I say above, it's not handled properly by the library.
For youtube, I fetch the information for each video using the Google.GData.YouTube.
Something like this returns a lot of information from the video.
Dim yv As Google.YouTube.Video
url = New Uri("http://gdata.youtube.com/feeds/api/videos/" & video.Custom)
r = New YouTubeRequest(New YouTubeRequestSettings("??", "??"))
yv = r.Retrieve(Of Video)(url)
Then it's possible to get the description with: yv.Description

how to find a Last Modified Date of a webPage?

i have a problem in my project to find the Last Modified date of a site..
is any code to find that in asp.net
thanks in advance..
Check out this question
How can you mine the "Last Modified Date" for an ASP.NET page which is based on a Master Page?
the basic code you need is this
Dim strPath As String = Request.PhysicalPath
Label1.Text = "Modified: " + System.IO.File.GetLastWriteTime(strPath).ToString()
FileInfo.LastWriteTime should give you what you need:
System.IO.File.GetLastWriteTime(Request.PhysicalPath).ToString();
According to your comment on the other answer, you instead want to get the last modified time of any web-site (not your own ASP.NET page). You could use Net.HttpWebRequest to request a given URL to get the LastModified property of the HttpResponse:
Protected Sub GetLastModifiedTimeOfWebPage(sender As Object, e As EventArgs)
Dim url = Me.TxtURL.Text.Trim
If Not url.StartsWith("http:") Then url = "http://" & url
Dim ResponseStatus As System.Net.HttpStatusCode
Dim lastModified As Date
Try
lastModified = RequestLastModified(url, ResponseStatus)
Catch ex As System.Exception
' log and/or throw
Throw
End Try
If ResponseStatus = Net.HttpStatusCode.OK Then
Me.LblLastModified.Text = lastModified.ToString
End If
End Sub
Public Shared Function RequestLastModified( _
ByVal URL As String, _
ByRef retStatus As Net.HttpStatusCode
) As Date
Dim lastModified As Date = Date.MinValue
Dim req As System.Net.HttpWebRequest
Dim resp As System.Net.HttpWebResponse
Try
req = DirectCast(Net.HttpWebRequest.Create(New Uri(URL)), Net.HttpWebRequest)
req.Method = "HEAD"
resp = DirectCast(req.GetResponse(), Net.HttpWebResponse)
retStatus = resp.StatusCode
lastModified = resp.LastModified
Catch ex As Exception
Throw
Finally
If resp IsNot Nothing Then
resp.Close()
End If
End Try
Return lastModified
End Function
Note: Many sites lie with this property and return only the current time.

First time implementing telerik RadUpload control

I am implementing telerik RadUpload in my asp.net web application.I added corresponding the handler and module entries in web.config.
<add path="Telerik.RadUploadProgressHandler.ashx"
type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
<add name="RadUploadModule"
type="Telerik.Web.UI.RadUploadHttpModule" />
I have a functionality where I need to upload excel file and need to see the progress bar while uploading until it completes 100%.
PROBLEM: I am wondering how to capture the percentage of file uploaded and show it in progressarea.
MY CODE (Button_Click):
Const total As Integer = 100
Dim progress As RadProgressContext = RadProgressContext.Current
progress.Speed = "N/A"
Dim files As UploadedFileCollection = RadUpload1.UploadedFiles
Dim up As RadUpload = RadUpload1
If files IsNot Nothing AndAlso 0 <> files.Count Then
For i As Integer = 0 To total - 1
progress("SecondaryTotal") = total.ToString()
progress("SecondaryValue") = i.ToString()
progress("SecondaryPercent") = i.ToString()
progress("CurrentOperationText") = files(0).GetName() & " is being processed..."
If Not Response.IsClientConnected Then
Exit For
End If
progress.TimeEstimated = (total - i) * 100
---------ACTUAL UPLOAD FUNCTIONALITY HERE----------
objUpload.CreateBulkUploadRequest(bytes)
Next
End If
Private Sub CreateBulkUploadRequest(bytes)
StoreDocumentinImageServer(bytes)
End Sub
Public Function StoreDocumentinImageServer(ByVal PostData As Byte()) As Integer
Try
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim postStream As Stream
Dim respStream As StreamReader
Dim Url As String
Dim response As String = String.Empty
Dim ImageId As Integer = 0
Dim qryString As New StringBuilder("?fileSize=")
qryString.Append(PostData.Length)
qryString.Append("&userId=" + RequestedBy.ToString)
qryString.Append("&applicationName=" + RequestType.ToString)
qryString.Append("&imageName=" + FileName)
qryString.Append("&mode=Insert")
Url = ImageServiceUrl + qryString.ToString
req = CType(WebRequest.Create(Url), HttpWebRequest)
req.Method = "POST"
req.ContentType = contenttype
req.KeepAlive = True
req.ContentLength = PostData.Length
postStream = req.GetRequestStream()
postStream.Write(PostData, 0, PostData.Length)
resp = CType(req.GetResponse(), HttpWebResponse)
respStream = New StreamReader(resp.GetResponseStream(), Encoding.Default)
response = respStream.ReadToEnd()
respStream.Close()
resp.Close()
Catch ex As Exception
Throw ex
End Try
End Function
PROBLEM---- Now CreateBulkUploadRequest() method is Synchronous , it will take 10 min to upload and finally come out of the method execution. Now mean while how would I update the progress area and percentage of file upload status.
My biggest problem is CreateBulkUploadRequest() is in the loop of progress bar update code.
so it calls as many times it is trying to update the progress area.
AM I DOING CORRECT ????????
Please Let me know If my question is not clear.
Looking forward for any suggestions.
You don't have to handle the display of progress information yourself, it should be done automatically. Have a look at this sample code.
If you are just using the RadUpload and progress area to check the uploaded % then you do not need any additional code in the code-behind. The code (markup) mentioned in this demo should suffice.
However, If you want some custom progress monitoring, which it seems that you are doing with the code provided, you will need to go about this slightly differently. This demo covers just how custom progress monitoring should be implemented. I would double check that the code that you have implemented aligns with the sample in that demo.

Why am I getting this generic, non-descript error in GDI+ when trying to save a PNG?

I have a function that dynamically adds text to an image in a predesignated spot. Originally I did it with jpegs, and it was working. I switched to PNG so the images would be better quality, as the original jpegs were kind of pixely. Anyway, here is my code. It executes down to the oBitmap.Save(), then dies with "A General Error Has Occurred in GDI+".
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "image/png"
context.Response.Clear()
context.Response.BufferOutput = True
Try
Dim oText As String = context.Server.HtmlDecode(context.Request.QueryString("t"))
If String.IsNullOrEmpty(oText) Then oText = "Placeholder"
Dim oPType As String = context.Server.HtmlDecode(context.Request.QueryString("p"))
If String.IsNullOrEmpty(oPType) Then oPType = "none"
Dim imgPath As String = ""
Select Case oPType
Case "c"
imgPath = "img/banner_green.png"
Case "m"
imgPath = "img/banner_blue.png"
Case Else
Throw New Exception("no ptype")
End Select
Dim oBitmap As Bitmap = New Bitmap(context.Server.MapPath(imgPath))
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
Dim frontColorBrush As New SolidBrush(Color.White)
Dim oFont As New Font(FONT_NAME, 30)
Dim oInfo() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders
Dim oEncoderParams As New EncoderParameters(2)
Dim xOffset As Single = Math.Round((oBitmap.Height - oFont.Height) / 2, MidpointRounding.ToEven)
Dim oPoint As New PointF(275.0F, xOffset + 10)
oEncoderParams.Param(0) = New EncoderParameter(Encoder.Quality, 100L)
oEncoderParams.Param(1) = New EncoderParameter(Encoder.ColorDepth,8L)
oGraphic.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
oGraphic.DrawString(oText, oFont, frontColorBrush, oPoint)
oBitmap.Save(context.Response.OutputStream, oInfo(4), oEncoderParams)
context.Response.Output.Write(oBitmap)
oFont.Dispose()
oGraphic.Dispose()
oBitmap.Dispose()
context.Response.Flush()
Catch ex As Exception
End Try
End Sub
The only changes I made to this from the jpeg version are:
context.Response.ContentType = "image/jpeg" changed to "image/png"
changed base images (img/banner_green.jpg, img/banner_blue.jpg) to .png
added the second encoding parameter specifying color depth
changed oInfo(1) (jpeg) to oInfo(4) (png)
Are there more things I need to tweak to get this routine to properly generate the PNG?
According to this post, Bitmap.Save requires a seekable stream to save as PNG, which HttpResponse.OutputStream isn't. You'll have to save the image into a MemoryStream first, and then copy the contents of it to Response.OutputStream, like:
Dim tempStream as New MemoryStream
oBitmap.Save(tempStream, ImageFormat.Png, oEncoderParams)
Response.OutputStream.Write(tempStream.ToArray(), 0, tempStream.Length)
Also note that the line
context.Response.Output.Write(oBitmap)
does something different then what you are probably expecting. HttpResponse.Output is a TextWriter, and the overload you use here, TextWriter.Write(object) will just call ToString on the object and write the results into the stream, what in this case results in writing "System.Drawing.Bitmap" to the output.
You're disposing of the bitmap before you're flushing the Response? Try flipping that around. Also, it looks like you're writing the bitmap to the stream twice. I'm not sure why you're doing that. Save the bitmap to the output stream or use the Write method of the Response object, but not both.

Resources