in my solution i have a couple of projects.
At my Allgemein.dll (General.dll) i have a custom httphandler which looks for pdf's and does something with it.
At every project in my solution i include the Allgemein.dll.
Now if i'm logged out of my application and i call a pdf, my httphandler works great.
But if i'm now login to my application and call a pdf, i got the following error: "The type "Allgemein.Handlers.FileProtectionHandler" in the assembly "Allgemein" could not be loaded."
What i'm doing wrong?
My web.config
<httpHandlers>
<add path="*.pdf" verb="*" validate="true" type="Allgemein.Handlers.FileProtectionHandler, Allgemein" />
</httpHandlers>
<handlers>
<add name="PDF" path="*.pdf" verb="*" type="Allgemein.Handlers.FileProtectionHandler, Allgemein" resourceType="Unspecified" />
</handlers>
My FileProtectionHandler.vb
Imports System
Imports System.Web
Imports System.Web.Security
Imports System.IO
Imports System.Web.SessionState
Namespace Allgemein.Handlers
Public Class FileProtectionHandler : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "GET"
If Not context.User.Identity.IsAuthenticated Then
FormsAuthentication.RedirectToLoginPage()
Return
End If
Dim requestedFile As String = context.Server.MapPath(context.Request.FilePath)
If context.User.IsInRole("User") Then
SendContentTypeAndFile(context, requestedFile)
Else
context.Response.Redirect("~/Portal/Fehler403.aspx")
End If
Exit Select
End Select
End Sub
Private Sub IHttpHandler_ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
Throw New NotImplementedException()
End Sub
Private Function SendContentTypeAndFile(ByVal context As HttpContext, ByVal strFile As String) As HttpContext
context.Response.ContentType = GetContentType(strFile)
context.Response.TransmitFile(strFile)
context.Response.[End]()
Return context
End Function
Private Function GetContentType(ByVal filename As String) As String
Dim res As String = Nothing
Dim fileinfo As FileInfo = New FileInfo(filename)
If fileinfo.Exists Then
Select Case fileinfo.Extension.Remove(0, 1).ToLower()
Case "pdf"
res = "application/pdf"
Exit Select
End Select
Return res
End If
Return Nothing
End Function
End Class
End Namespace
After a joined effort with the OP it has been concluded that the MIR.Web.Allgemein is the root namespace.
In this case, the actual type name would be MIR.Web.Allgemein.Allgemein.Handlers.FileProtectionHandler which is the root namespace [dot] the actual namespace from code [dot] class name.
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
What am trying to create is a single login screen that connects the users to different databases depending on a certain code that each user has.
i have created some keys in my config file which corresponds to the user codes as follows
<appSettings>
<add key="ch001" value="h001"/>
<add key="ch002" value="h002"/>
</appSettings>
Then i have created connections string as follows
<connectionStrings>
<add name="Dbconn_h001" connectionString="XXX" providerName="XXX"/>
<add name="Dbconn_h002" connectionString="XXX" providerName="XXX"/>
</connectionStrings>
Then i have created a class to get the key value corresponding to the connection string as follows
Imports System.Web.Compilation
Imports System.CodeDom
Imports System.ComponentModel
Public Class ConnStringExpressionBuilder
Inherits ExpressionBuilder
Public Shared Function GetEvalData(ByVal expression As String, ByVal target As Type, ByVal entry As String) As Object
Return System.Configuration.ConfigurationManager.ConnectionStrings("Dbconn_" & System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString))
End Function
Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression
Dim type1 As Type = entry.DeclaringType
Dim descriptor1 As PropertyDescriptor = TypeDescriptor.GetProperties(type1)(entry.PropertyInfo.Name)
Dim expressionArray1(2) As CodeExpression
expressionArray1(0) = New CodePrimitiveExpression(entry.Expression.Trim())
expressionArray1(1) = New CodeTypeOfExpression(type1)
expressionArray1(2) = New CodePrimitiveExpression(entry.Name)
Return New CodeCastExpression(descriptor1.PropertyType, New CodeMethodInvokeExpression(New CodeTypeReferenceExpression(MyBase.GetType()), "GetEvalData", expressionArray1))
End Function
End Class
The issue is
System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString)
returns a null reference
using(SqlConnection conn = new SqlConnection())
{
var connString=ConfigurationManager.AppSetting["keyname"];
conn.ConnectionString = connString;
// using the code here...
}
and in config file save like
<add key="ch001" value="YourConnectionString" />
After a long hustle i figured it out i created this expression builder class
Public Class ConnStringExpressionBuilder
Inherits ExpressionBuilder
Public Shared Function GetEvalData(ByVal expression As String, ByVal target As Type, ByVal entry As String) As Object
Return System.Configuration.ConfigurationManager.ConnectionStrings(System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString())).ToString()
End Function
Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression
Dim type1 As Type = entry.DeclaringType
Dim descriptor1 As PropertyDescriptor = TypeDescriptor.GetProperties(type1)(entry.PropertyInfo.Name)
Dim expressionArray1(2) As CodeExpression
expressionArray1(0) = New CodePrimitiveExpression(entry.Expression.Trim())
expressionArray1(1) = New CodeTypeOfExpression(type1)
expressionArray1(2) = New CodePrimitiveExpression(entry.Name)
Return New CodeCastExpression(descriptor1.PropertyType, New CodeMethodInvokeExpression(New CodeTypeReferenceExpression(MyBase.GetType()), "GetEvalData", expressionArray1))
End Function
End Class
Then in my markup i call the class like this
<asp:SqlDataSource ID="Ds" runat="server" ProviderName="Mysql.Data.MysqlClient"
ConnectionString="<%$ ConnStringExpression:Dbconn %>" SelectCommand="XXX"></asp:SqlDataSource>
Then from the code behind
Using conn = getConnect(System.Configuration.ConfigurationManager.AppSettings(Session("code").ToString()))
conn.Open()
Try
//logic
Catch ex As Exception
End Try
conn.Close()
End Using
Having a hard time getting reCaptcha to validate on my site :(
I have tried to find other sources for VB.net implementations, but haven't had much luck. Here is what I have tried...
default.aspx.vb
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.Script.Serialization
Public Class _Default
Inherits System.Web.UI.Page
Sub reCaptcha_Click(ByVal sender As Object, ByVal e As EventArgs)
If (capValidate()) Then
MsgBox("Valid Recaptcha")
Else
MsgBox("Not Valid Recaptcha")
End If
End Sub
Public Function capValidate() As Boolean
Dim Response As String = Request("g-captcha-response")
Dim Valid As Boolean = False
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(Convert.ToString("https://www.google.com/recaptcha/api/siteverify?secret=THIS IS WHERE MY KEY IS&response=") & Response), HttpWebRequest)
Try
Using wResponse As WebResponse = req.GetResponse()
Using readStream As New StreamReader(wResponse.GetResponseStream())
Dim jsonResponse As String = readStream.ReadToEnd()
Dim js As New JavaScriptSerializer()
Dim data As MyObject = js.Deserialize(Of MyObject)(jsonResponse)
Valid = Convert.ToBoolean(data.success)
Return Valid
End Using
End Using
Catch ex As Exception
Return False
End Try
End Function
Public Class MyObject
Public Property success() As String
Get
Return m_success
End Get
Set(value As String)
m_success = Value
End Set
End Property
Private m_success As String
End Class
And my front page...
<div class="g-recaptcha"
data-sitekey="THIS IS WHERE MY SITE KEY IS"></div>
<asp:Button ID="btnLogin" CssClass="captcha_click" runat="server" Text="Check Recaptcha" OnClick="reCaptcha_Click" TabIndex ="4"/>
My message boxes always return "not a valid recaptcha"
Can anyone shed some light on why I cannot get a valid recaptcha return?
Thanks!
Try:
Dim Response As String = Request("g-recaptcha-response")
Note the re
I'm working on a legacy web service that was firstly developed in Java using Axis, which its response was:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:TransaccionResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://DefaultNamespace">
<TransaccionReturn xsi:type="xsd:string"><!-- info --></TransaccionReturn>
</ns1:TransaccionResponse>
</soapenv:Body>
</soapenv:Envelope>
And I'm making a .NET Web Service that should be compatible with all current clients, but until now I have:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ns1:TransaccionResponse xmlns:ns1="http://DefaultNamespace">
<TransaccionReturn><!-- info --></TransaccionReturn>
</ns1:TransaccionResponse>
</soap:Body>
</soap:Envelope>
I started with an old ASP.NET Web Service project and I'm wondering if there is a way to replace the soap prefix to soapenv? Also is there any way to force the web service to add the xsi:type declaration?
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Services.Description
Imports System.Xml.Serialization
Imports System.IO
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class ExpedientesService
Inherits System.Web.Services.WebService
Public Sub New()
MyBase.New()
End Sub
<WebMethod()> _
<SoapDocumentMethod("", _
RequestNamespace:="http://DefaultNamespace", _
ResponseNamespace:="http://DefaultNamespace", _
ParameterStyle:=SoapParameterStyle.Bare)> _
Public Function llamarWS( _
<XmlElement("Transaccion", Namespace:="http://DefaultNamespace")> ByVal tr As Transaccion) As _
<XmlElement("TransaccionResponse")> _
RespuestaXML
Return New RespuestaXML(String.format("You sended: '{0}' '{1}' '{2}'", tr.transaccion, tr.usuario, tr.password))
End Function
End Class
'HERE THERE IS A CLASS DECLARATION FOR THE INPUT PARAMETERS OF THE WEB SERVICE
Public Class Transaccion
'CHECK THE DECLARATION OF THE XML NODE AND ITS NAMESPACE
<XmlElement("transaccion", Namespace:="")> _
Public transaccion As String
<XmlElement("usuario", Namespace:="")> _
Public usuario As String
<XmlElement("password", Namespace:="")> _
Public password As String
Public Sub New()
Me.transaccion = "0"
Me.usuario = String.Empty
Me.password = String.Empty
End Sub
Public Sub New(ByVal transaccion As String, ByVal usuario As String, ByVal password As String)
Me.transaccion = transaccion
Me.usuario = usuario
Me.password = password
End Sub
'HERE YOU DECLARE THE NAMESPACES FOR THE XML ELEMENT
<XmlNamespaceDeclarations()> _
Public Property xmlns() As XmlSerializerNamespaces
Get
Dim xsn As New XmlSerializerNamespaces()
xsn.Add("def", "http://DefaultNamespace")
Return xsn
End Get
' needed for xml serialization
Set(ByVal value As XmlSerializerNamespaces)
End Set
End Property
End Class
'HERE THERE IS A CLASS DECLARATION FOR THE OUTPUT RESPONSE
Public Class RespuestaXML
'THIS IS THE SAME AS THE INPUT PARAMETER, THE NODE NAME AND ITS NAMESPACE
<XmlElement("TransaccionReturn", Namespace:="")> _
Public Body As String
Public Sub New()
Me.Body = "##"
End Sub
Public Sub New(ByVal StringReturn As String)
Me.Body = StringReturn
End Sub
'HERE IS THE TRICK, DECLARE THE NAMESPACES FOR THE RESPONSE
<XmlNamespaceDeclarations()> _
Public Property xmlns() As XmlSerializerNamespaces
Get
Dim xsn As New XmlSerializerNamespaces()
xsn.Add("ns1", "http://DefaultNamespace")
Return xsn
End Get
' needed for xml serialization
Set(ByVal value As XmlSerializerNamespaces)
End Set
End Property
End Class
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.