i have this code ImageHandler.
Public Class ImageHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpH
Dim oBJDB As New DBX
Try
Dim oSDR As System.Data.SqlClient.SqlDataReader
oSDR = oBJDB.CreateSDRFromSQLSelect("SELECT SIGNIMAGE FROM APPUSERDTL WHERE UID =#UID")
If oSDR.Read() Then
context.Response.BinaryWrite(CType(oSDR("SIGNIMAGE"), Byte()))
Dim ImageID As New SqlParameter("#UID", Data.SqlDbType.Int)
ImageID.Value = context.Request.Cookies("UID").Value
End If
oSDR.Close()
oSDR = Nothing
Catch ex As Exception
Finally
oBJDB.Close()
oBJDB = Nothing
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
images displayed in the application does not appear if use this.
please help me
Place an image control in .aspx file:
<asp:Image ID="Image1" runat="server" Height="75px" Width="76px" />
and then in your .vb file:
imageId as string=context.Request.Cookies("UID").Value
Image1.ImageUrl = "~/Profile/ImageHandler.ashx?ImageId= "& imageId
Feel free to contact and don't forget to mark as answer that would help you.
Related
I need some pointers with understanding how to convert a returned asmx class from within aspx codebehind. I created a prototype asmx and aspx pages to test this functionality that once sucessfully working I'd like to extend to a project I'm working on.
Although I'm using the same class definition within the asmx and aspx vb codebehind, visual studio is noting a conversion incompatiability error "Error BC30311 Value of type 'websvc_returnvalues' cannot be converted to 'WebServiceConsume.websvc_returnvalues'". This error is denoted in visual studio on the following line in aspx.vb:
rtnvals = websvc.test()
I tried doing a simple type conversion but it has the same kind of error: Unable to cast object of type 'websvctest.websvc_returnvalues' to type 'websvc_returnvalues' ... so obviously I'm not understanding how to convert between the two classes.
Private Function cvt_websvc_returnvalues(i As Object) As websvc_returnvalues
Return CType(i, websvc_returnvalues)
End Function
Thanks in advance for any suggestions I can try! Stackoverflow is my primary source for answering my software questions!
Webservice:
I have the following webservice referenced as websvctest in my project:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://sample.org/")>
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebServiceTest
Inherits System.Web.Services.WebService
<Serializable()>
Public Class websvc_returnvalues
Public w_brtn As Boolean
Public w_rtnval As String
Public w_rtnerr As String
Sub New()
w_brtn = False
w_rtnval = ""
w_rtnerr = ""
End Sub
Public Property Ok As Boolean
Get
Return w_brtn
End Get
Set(value As Boolean)
w_brtn = value
End Set
End Property
Public Property value As String
Get
Return w_rtnval
End Get
Set(value As String)
w_rtnval = value
End Set
End Property
Public Property err As String
Get
Return w_rtnerr
End Get
Set(value As String)
w_rtnerr = value
End Set
End Property
End Class
Public Sub New()
End Sub
<WebMethod()>
Public Function test() As websvc_returnvalues
Dim b As Boolean = False
Dim rtn As websvc_returnvalues = New websvc_returnvalues
Try
b = True
Catch ex As Exception
rtn.err = ex.Message
End Try
rtn.Ok = b
Return rtn
End Function
End Class
WebServiceConsume.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="WebServiceTestConsume.aspx.vb" Inherits="WebServiceConsume" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="websvc_ok">ok</label><asp:Literal ID="websvc_ok" runat="server"></asp:Literal><br />
<label for="websvc_value">value</label><asp:Literal ID="websvc_value" runat="server"></asp:Literal><br />
<label for="websvc_err">err</label><asp:Literal ID="websvc_err" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
WebServiceconsume.aspx.vb
Note the same class definition for websvc_returnvalues here as in the asmx
Partial Class WebServiceConsume
Inherits System.Web.UI.Page
Private websvc As New websvctest.WebServiceTest
Public Class websvc_returnvalues
Public w_brtn As Boolean
Public w_rtnval As String
Public w_rtnerr As String
Sub New()
w_brtn = False
w_rtnval = ""
w_rtnerr = ""
End Sub
Public Property Ok As Boolean
Get
Return w_brtn
End Get
Set(value As Boolean)
w_brtn = value
End Set
End Property
Public Property value As String
Get
Return w_rtnval
End Get
Set(value As String)
w_rtnval = value
End Set
End Property
Public Property err As String
Get
Return w_rtnerr
End Get
Set(value As String)
w_rtnerr = value
End Set
End Property
End Class
Private Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load
Dim rtnvals As websvc_returnvalues
Try
rtnvals = websvc.test() ' visual studio error
rtnvals = cvt_websvc_returnvalues(websvc.test()) ' runtime error
Me.websvc_ok.Text = rtnvals.Ok.ToString
simp Me.websvc_value.Text = rtnvals.value.ToString
Me.websvc_err.Text = rtnvals.err.ToString
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Testing")
End Try
End Sub
Private Function cvt_websvc_returnvalues(i As Object) As websvc_returnvalues
Return CType(i, websvc_returnvalues)
End Function
End Class
Doh! I can answer my own question ...
I just needed to type in the correct namespace against the websvc_returnvalues class:
Dim rtnvals As websvctest.websvc_returnvalues
I'm trying to build a custom sitemap
I look into code on this site
http://harriyott.com/2007/03/adding-dynamic-nodes-to-aspnet-site
I have convert it into vb.net as far as I could
here is my code
Partial Class Main
Inherits StaticSiteMapProvider
Dim conn As New ConnectionVB
Dim _rootNode As SiteMapNode = Nothing
Dim _siteMapFileName As String
Dim SiteMapNodeName As String = "siteMapNode"
Public Sub DynamicSiteMapProvider()
End Sub
Public Shadows Function RootNode() As SiteMapNode
Return BuildSiteMap()
End Function
Public Overrides Sub Initialize(name As String, attributes As NameValueCollection)
//Me.Initialize(name, attributes)
_siteMapFileName = attributes("siteMapFile")
End Sub
Protected Overrides Function GetRootNodeCore() As SiteMapNode
Return RootNode()
End Function
Protected Overrides Sub clear()
SyncLock Me
_rootNode = Nothing
//Me.clear()
End SyncLock
End Sub
Public Overrides Function BuildSiteMap() As SiteMapNode
SyncLock Me
If _rootNode Is Nothing Then
clear()
Dim siteMapXml As XmlDocument = LoadSiteMapXml()
Dim rootElement As XmlElement = CType(siteMapXml.GetElementsByTagName(SiteMapNodeName)(0), XmlElement)
AddDynamicNodes(rootElement)
GenerateSiteMapNodes(rootElement)
End If
End SyncLock
Return _rootNode
End Function
Private Function LoadSiteMapXml() As XmlDocument
Dim siteMapXml As XmlDocument = New XmlDocument()
siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName)
Return siteMapXml
End Function
Protected Sub AddDynamicNodes(rootElement As XmlElement)
Dim teams As XmlElement = AddDynamicChildElement(rootElement, "", "FootballTeams", "List of football team")
End Sub
Protected Function AddDynamicChildElement(parentElement As XmlElement, url As String, title As String, description As String) As XmlElement
Dim childElement As XmlElement = parentElement.OwnerDocument.CreateElement(SiteMapNodeName)
childElement.SetAttribute("url", url)
childElement.SetAttribute("title", title)
childElement.SetAttribute("description", description)
parentElement.AppendChild(childElement)
Return childElement
End Function
Protected Sub GenerateSiteMapNodes(rootElement As XmlElement)
_rootNode = GetSiteMapNodeFromElement(rootElement)
AddNode(_rootNode)
CreateChildNodes(rootElement, _rootNode)
End Sub
Protected Sub CreateChildNodes(parentElement As XmlElement, parentNode As SiteMapNode)
For Each XmlElement As XmlNode In parentElement.ChildNodes
If XmlElement.Name = SiteMapNodeName Then
Dim childNode As SiteMapNode = GetSiteMapNodeFromElement(CType(XmlElement, XmlElement))
AddNode(childNode, parentNode)
CreateChildNodes(CType(XmlElement, XmlElement), childNode)
End If
Next
End Sub
Protected Function GetSiteMapNodeFromElement(rootElement As XmlElement) As SiteMapNode
Dim newSiteMapNode As SiteMapNode
Dim url As String = rootElement.GetAttribute("url")
Dim title As String = rootElement.GetAttribute("title")
Dim description As String = rootElement.GetAttribute("description")
newSiteMapNode = New SiteMapNode(Me, (url + title).GetHashCode().ToString(), url, title, description)
Return newSiteMapNode
End Function
End Class
I got this kind of error
System.ArgumentException: Provider name cannot be null or empty.
I don't have any idea what the cause of this error
could someone help me??
Appreciate all help
thanks
PS : Sorry if my English messed up
Please make sure that you have add this in web config.
<system.web>
<siteMap defaultProvider="main">
<providers>
<add siteMapFile="Web.sitemap" name="main" type="System.Web.XmlSiteMapProvider"/>
</providers>
</siteMap>
hello iam trying to get the id from a url and send it to the clint side this is what i did
this is my url :
http://localhost:53010/edit.aspx?Id=4
code behind
Public Partial Class Edit
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
End Sub
Private _myId As String = Request.QueryString("id")
Public Property myId() As String
Get
Return _myId
End Get
Set(ByVal value As String)
_myId = value
End Set
End Property
End Class
client
<%= myId%>
error
Request is not available in this context
this is also what i get when i move the private prop to page_load()
"private " is not valid on local variable declaration –
any idea what is going on
Thanks
i solve this problem here is the answer
Public Partial Class Edit
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
MyIdVal = Request.QueryString("id")
End Sub
Private _myIdVal As String
Public Property MyIdVal() As String
Get
Return _myIdVal
End Get
Set(ByVal value As String)
_myIdVal = value
End Set
End Property
End Class
That's a field initializer.
Field initializers run before the constructor and cannot access the instance they're initializing.
Therefore, you can't use the Request property there.
You need to move that to the constructor or Page_Load.
You're accessing the Request too early.
It will work if you set myId on Init, Page_Load or any other similar page event.
Try to set _myId in your PageLoad.
So I wanted a class with properties that were set from querystrings and found this thread. I also wanted to be able to access properties on the front page and even in JavaScript from a single location. Here is what I came up with:
// App_Code/QueryStrings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for QueryStrings
/// </summary>
public class QS
{
private int id = -1;
public QS()
{
if (HttpContext.Current.Request.QueryString["id"] != null)
try
{
Int32.TryParse(HttpContext.Current.Request.QueryString["id"], out id);
}
catch
{
id = -2;
}
else
id = -3;
}
public int ID
{
get
{
return id;
}
}
}
Then you can call it from your .aspx page as follows:
<body>
<form id="form1" runat="server">
<div>
<% QS qs = new QS(); %>
ID = <%= qs.ID %>
</div>
</form>
</body>
Of course you can call from code behind with the same syntax.
I am trying to upload images using generic handler as shown below and I have a normal aspx page where I am showing all the uploaded images after uploading.Everything is working fine.
<%# WebHandler Language="VB" Class="Upload"%>
Imports System
Imports System.Web
Imports System.Threading
Imports System.Web.Script.Serialization
Imports System.IO
Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Class FilesStatus
Public Property thumbnail_url() As String
Public Property name() As String
Public Property url() As String
Public Property size() As Integer
Public Property type() As String
Public Property delete_url() As String
Public Property delete_type() As String
Public Property [error]() As String
Public Property progress() As String
End Class
Private ReadOnly js As New JavaScriptSerializer()
Private ingestPath As String
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim r = context.Response
ingestPath = context.Server.MapPath("~/UploadedImages/")
r.AddHeader("Pragma", "no-cache")
r.AddHeader("Cache-Control", "private, no-cache")
HandleMethod(context)
End Sub
Private Sub HandleMethod(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "HEAD", "GET"
ServeFile(context)
Case "POST"
UploadFile(context)
Case "DELETE"
DeleteFile(context)
Case Else
context.Response.ClearHeaders()
context.Response.StatusCode = 405
End Select
End Sub
Private Sub DeleteFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
File.Delete(filePath)
End If
End Sub
Private Sub ServeFile(ByVal context As HttpContext)
If String.IsNullOrEmpty(context.Request("f")) Then
ListCurrentFiles(context)
Else
DeliverFile(context)
End If
End Sub
Private Sub UploadFile(ByVal context As HttpContext)
Dim statuses = New List(Of FilesStatus)()
Dim headers = context.Request.Headers
If String.IsNullOrEmpty(headers("X-File-Name")) Then
UploadWholeFile(context, statuses)
Else
UploadPartialFile(headers("X-File-Name"), context, statuses)
End If
WriteJsonIframeSafe(context, statuses)
End Sub
Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
If context.Request.Files.Count <> 1 Then
Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request")
End If
Dim inputStream = context.Request.Files(0).InputStream
Dim fullName = ingestPath & Path.GetFileName(fileName)
Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write)
Dim buffer = New Byte(1023) {}
Dim l = inputStream.Read(buffer, 0, 1024)
Do While l > 0
fs.Write(buffer, 0, l)
l = inputStream.Read(buffer, 0, 1024)
Loop
fs.Flush()
fs.Close()
End Using
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"})
End Sub
Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
For i As Integer = 0 To context.Request.Files.Count - 1
Dim file = context.Request.Files(i)
file.SaveAs(ingestPath & Path.GetFileName(file.FileName))
Thread.Sleep(1000)
Dim fname = Path.GetFileName(file.FileName)
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"})
Next i
End Sub
Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
context.Response.AddHeader("Vary", "Accept")
Try
If context.Request("HTTP_ACCEPT").Contains("application/json") Then
context.Response.ContentType = "application/json"
Else
context.Response.ContentType = "text/plain"
End If
Catch
context.Response.ContentType = "text/plain"
End Try
Dim jsonObj = js.Serialize(statuses.ToArray())
context.Response.Write(jsonObj)
End Sub
Private Sub DeliverFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
context.Response.ContentType = "application/octet-stream"
context.Response.WriteFile(filePath)
context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """")
Else
context.Response.StatusCode = 404
End If
End Sub
Private Sub ListCurrentFiles(ByVal context As HttpContext)
Dim files = New List(Of FilesStatus)()
Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly)
For Each name In names
Dim f = New FileInfo(name)
files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"})
Next name
context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""")
Dim jsonObj = js.Serialize(files.ToArray())
context.Response.Write(jsonObj)
context.Response.ContentType = "application/json"
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now I want to add a session variable by generating a random string and add the uploaded images to the newly created random string.
1.I have seen this Question on SO to use System.Web.SessionState.IRequiresSessionState for sessions and how do I create a folder with that and add my images to that folder after doing that how do I access this session variable in my normal aspx page.
2.(Or) the better way is create session variable in aspx page and pass that to handler?If so how can I do that?
3 .I am trying to find the control from my handler.Is that possible?If anyone knows how to get this then also my problem will get resolved so that I am trying to create a session from m aspx page.
Can anyone explain the better way of handling this situation.
I completely agree with jbl's comment.
You can get and set session using HttpContext.Current.Session anywhere on your project.
No matter where you create the session. Just make sure that the session exists before you access it.
Not sure what exactly you are asking here(need some more explanation).
Here is an example, where I used session on HttpHandler. However, it is on c#(hope you can understand).
This is not really an answer but #Knvn wrote a C# example which I couldn't understand so I used a converter to convert it to VB. Posted it here in case it helps someone in the future.
Public Class HttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
Public Sub New()
End Sub
Public Sub ProcessRequest(context As HttpContext)
Dim Request As HttpRequest = context.Request
Dim Response As HttpResponse = context.Response
If SessionHandler.Current.UserID = 0 Then
Response.Redirect("~/Default.aspx")
Else
Try
If Request.Path.EndsWith(".pdf") Then
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path))
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Else
Using reader As New StreamReader(HttpContext.Current.Server.MapPath(Request.Path))
Response.Write(reader.ReadToEnd())
End Using
End If
Catch
Response.Redirect("~/Default.aspx")
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean
' To enable pooling, return true here.
' This keeps the handler in memory.
Get
Return False
End Get
End Property
End Class
I can bind a inner object property to gridview using the following setup at design time in an ASP.NET gridview
<asp:TemplateField HeaderText="ObjectName" >
<ItemTemplate>
<%# Eval("Object.property")%>
</ItemTemplate>
</asp:TemplateField>
but what I would like to do know is create this programmatically at runtime
i.e. define my columns, add them to the gridview and then databind
I'm not sure if this is what you want to achieve. But if you want to create columns dynamically according to your object's properties on runtime, have a look at following code(example is with BoundColumns, have a look at Volpa's answer when you need TemplateColumns):
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"></asp:GridView>
Codebehind:
Public Partial Class GridViewTest
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
Dim cList As New List(Of CustomClass)
For i As Int32 = 1 To 10
Dim c As New CustomClass
c.ID = i
c.Name = "Object " & i
cList.Add(c)
Next
Dim model As New CustomClass
For Each prop As Reflection.PropertyInfo In model.GetType.GetProperties
If prop.CanRead Then
Dim field As New BoundField()
field.HeaderText = prop.Name
field.DataField = prop.Name
Me.GridView1.Columns.Add(field)
End If
Next
Me.GridView1.DataSource = cList
Me.GridView1.DataBind()
End Sub
End Class
Public Class CustomClass
Private _id As Int32
Private _name As String
Public Property ID() As Int32
Get
Return _id
End Get
Set(ByVal value As Int32)
_id = value
End Set
End Property
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
One way would be to create a class that implements ITemplate interface:
public class PropertyTemplate : ITemplate
{
private string _value = string.Empty;
public PropertyTemplate(string propValue)
{
this._value = propValue;
}
public void InstantiateIn(Control container)
{
container.Controls.Add(new LiteralControl(this._value));
}
}
Then in your code-behind assing the ItemTemplate as following:
myTemplateField.ItemTemplate = new PropertyTemplate(myBusinessObject.MyProperty);
Another way would be to use Page.LoadTemplate if your custom template resides in the separate .ascx file:
myTemplateField.ItemTemplate = Page.LoadTemplate("~/MyTemplate.ascx");
And the .ascx file will look like:
<%# Eval("MyProperty") %>