Google reCaptcha V2 Implementation VB.net - asp.net

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

Related

ASP.NET WebForms - VB.NET and SignalR

This is my Hub code (very simple):
Imports System
Imports System.Web
Imports Microsoft.AspNet.SignalR
Imports Microsoft.AspNet.SignalR.Hubs
Imports Microsoft.AspNet.SignalR.Client
Imports Microsoft.AspNet.SignalR.Messaging
Imports System.Threading.Tasks
Namespace SignalRChat
Public Class ChatHub
Inherits Hub
Public Sub Send(userName As String, message As String)
Clients.All.broadcastMessage(userName, message)
End Sub
End Class
End Namespace
This is my Aspx page code:
Imports System.Web.UI.WebControls
Imports Microsoft.AspNet.SignalR.Client
Imports System.Threading.Tasks
Public Class WebForm9
Inherits System.Web.UI.Page
Public Shared hubConnection As HubConnection
Public Shared chatHubProxy As IHubProxy
Public Sub MyChat_init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack = False Then
hubConnection = New HubConnection("https://localhost:44343/")
hubConnection.TraceLevel = TraceLevels.All
hubConnection.TraceWriter = Console.Out
chatHubProxy = hubConnection.CreateHubProxy("ChatHub")
hubConnection.Start().Wait()
End If
chatHubProxy.On(Of String, String)("broadcastMessage", Sub(ByVal userName As String, ByVal message As String)
Dim li As ListItem = New ListItem
li.Value = userName & " - " & message
li.Text = userName & " - " & message
ListBox1.Items.Add(li)
End Sub)
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
chatHubProxy.Invoke("Send", "Io", "Messaggio")
End Sub
End Class
I made a lot of tries but always ended up with no result... I added the postback checking because I noticed I was having the connection to the hub starting and starting again on each button_click...
By the way, if I add in the same project a page with JScript code I can catch all the messages sent on the JScript code, but none of the messages sent from the html page is catched by the aspx codebehind...
It's really strange because if I take away the listbox.items.add method and I put a "MsgBox" instead, then it fires up and work... but I have found no way to manage the "messages" from my codebehind and so update controls on my page... Maybe it's a connection mistake? Did anyone of you has any experience with SignalR and WebForms with VB.NET codebehind?
If this helps, I have a working client code (for testing purposes) in VB.NET WinForms app. (My Hub is in C#):
Hub (ASP.NET Core in net5.0 - created using Gerald Versluis' tutorial: https://www.youtube.com/watch?v=pDr0Hx67guk):
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;
namespace SignalR.Hubs;
public class OneHub : Hub
{
public async Task SendMessage(Message message)
{
Console.WriteLine($"{message.SentDateTime} Sender : {message.SenderId} - {message.MessageText}");
await Clients.All.SendAsync("MessageReceived", message);
}
}
WinForms (net4.8):
Imports Microsoft.AspNetCore.SignalR.Client
Imports SignalRWinForms.Client.Messaging.Models
Public Class Form1
Private connection As HubConnection
Sub New()
InitializeComponent()
connection = New HubConnectionBuilder().WithUrl("http://192.168.1.230:5296/chat").Build()
connection.On(Of Messages)("MessageReceived", Sub(Messages)
Invoke(Sub()
ReceiveMessage(Messages)
End Sub)
End Sub)
connection.StartAsync()
End Sub
Private Sub ReceiveMessage(msg As Messages)
chatMessages.Text &= $"{Environment.NewLine}{msg.MessageText}"
End Sub
Private Async Sub btnSendMessage_Click(sender As Object, e As EventArgs) Handles btnSendMessage.Click
Dim message = New Messages With {
.MessageText = txtMessage.Text,
.SenderId = 1111,
.ReceiverId = 2222,
.Token = "token",
.SentDateTime = DateTime.Now
}
Await connection.InvokeCoreAsync("SendMessage", args:={message})
txtMessage.Text = String.Empty
End Sub
End Class
Form1 is very simple - chatMessages label to populate messages, txtMessage textbox to write message and a btnSendMessage button.
Messages Class (common for both projects)
Public Class Messages
Public Property SenderId As Integer
Public Property ReceiverId As Integer
Public Property MessageText As String
Public Property Token As String
Public Property SentDateTime As DateTime
End Class

How to convert returned asmx class in aspx

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

import database connection file

I can't manage to connect to an SQL database using an external connection file
I am getting an error which is something like namespace or type specified in the imports 'Pirelli.dbPirelli' does not contain any public member
Any idea how I can do this??
Thanks!!
Default.aspx.vb
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common.DbDataReader
Imports System.Web.UI
Imports System.IO
Imports Pirelli.dbPirelli
Partial Class _Default
Inherits System.Web.UI.Page
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
Dim cmd As New SqlCommand
Dim SQLdr As SqlDataReader 'The Local Data Store
cmd.Connection = dbConnectDBOStr
End Sub
dbPirelli.vb - database connection file:
Imports System.Data.SqlClient
Namespace Pirelli
Public Class dbPirelli
Public Const strServerName As String = "testserver" 'DEV
Public Const dbConnectDBOStr As String = "uid=[MYIDHERE];password=[MYPASSHERE];database=[DBNAMEHERE];server=" & strServerName & ";Connection Timeout=60;"
End Class
End Namespace
You need to reference it in this way
Imports YourProjectName.Pirelli.dbPirelli

vb.net using ashx handler to get image from SQL Server

I have employee images stored in my EMPPhotos table on SQL Server 2008 R2 in an image datatype. I created a generic handler to get the image from the table and send it to the page. It does not work. I have tested the query itself and I am getting data.
The handler:
<%# WebHandler Language="VB" Class="EmpImageHandler" %>
Imports System
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class EmpImageHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/bmp"
'context.Response.Write("Hello World")
context.Response.ContentType = "text/bmp"
Dim img As Image = GetImage(context.Request.QueryString("id"))
img.Save(context.Response.OutputStream, ImageFormat.Bmp)
End Sub
Private Function GetImage(inID As Long) As Image
Dim ms As MemoryStream = New MemoryStream
Dim cnSTR As New clsConnections
Dim cn As New SqlConnection(cnSTR.ConnectToDB("AgencyStaff"))
Try
cn.Open()
Catch ex As Exception
End Try
Dim ssql As String = "Select BMPPhoto From EMPPhotos where empid = " & inID
Dim CMD As SqlCommand = New SqlCommand(ssql, cn)
Dim dr As SqlDataReader = CMD.ExecuteReader
dr.Read()
Dim img() As Byte = CType(dr("BMPPhoto"), Byte())
ms = New MemoryStream(img, False)
Return Image.FromStream(ms)
End Function
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
Thanks in advance for your assistance.
Change your ContentType.
From:
context.Response.ContentType = "text/bmp"
To:
context.Response.ContentType = "image/bmp"

Pass parameters to a webmethod from querystring

guys. I'm developing a website with ASP and VB.NET 4. I'm also using the FullCalendar jQuery plugin, but I have a trouble: catching a parameter from querystring to the webmethod in the .asmx. I've tried to refer the querystring property with the Request.QueryString() and it doesn't work.
Here's the webmethod:
<%# WebService Language="VB" Class="wbsCalendario" %>
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports System.Configuration.ConfigurationManager
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ScriptService> _
Public Class wbsCalendario
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function ListarEventos(ByVal starte As String, ByVal ende As String, ByVal v As String) As List(Of CalendarioEvento)
Dim conexaoSql As New SqlConnection(ConnectionStrings("praeConnectionString").ConnectionString)
Dim comandoSql As SqlCommand = New SqlCommand("spListarEventosCalendario", conexaoSql)
comandoSql.CommandType = CommandType.StoredProcedure
comandoSql.Parameters.AddWithValue("#bitPendentes", 0)
comandoSql.Parameters.AddWithValue("#agendamentos", "188,135")
comandoSql.Parameters.AddWithValue("#start", FromUnixTimespan(starte))
comandoSql.Parameters.AddWithValue("#end", FromUnixTimespan(ende))
comandoSql.Parameters.AddWithValue("#veiculo", v)
Dim eventos As List(Of CalendarioEvento) = New List(Of CalendarioEvento)
Try
conexaoSql.Open()
Dim sdrEventos As SqlDataReader = comandoSql.ExecuteReader
While sdrEventos.Read
Dim evento As New CalendarioEvento
evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
eventos.Add(evento)
End While
Catch ex As Exception
Finally
conexaoSql.Close()
End Try
comandoSql.Parameters("#bitPendentes").Value = 1
Try
conexaoSql.Open()
Dim sdrEventos As SqlDataReader = comandoSql.ExecuteReader
While sdrEventos.Read
Dim evento As New CalendarioEvento
evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
evento.color = "#6AB0D8"
eventos.Add(evento)
End While
Catch ex As Exception
Finally
conexaoSql.Close()
End Try
Return eventos
End Function
Private Shared Function ToUnixTimespan(ByVal d As DateTime) As Long
Dim time As New TimeSpan()
time = d.ToUniversalTime().Subtract(New DateTime(1970, 1, 1, 0, 0, 0))
Return CType(Math.Truncate(time.TotalSeconds), Int64)
End Function
Private Shared Function FromUnixTimespan(ByVal s As String) As DateTime
Dim time As DateTime = New DateTime(1970, 1, 1, 0, 0, 0)
Return time.AddSeconds(s)
End Function
End Class
Can someone help me?
Thanks.
The values in the query string are automatically translated into arguments defined on the webmethod.
If you had this Webmethod:
<WebMethod()> Public Sub DoWork(arg1 As Integer, arg2 As String)
And called it by a url of:
http://domain/webservice.asmx/DoWork?arg=2&arg2=hello
Those two querystring parameters would be translated into the two arguments arg1 and arg2, which could be referenced as normal within the DoWork() method.

Resources