ASP.NET WebForms - VB.NET and SignalR - asp.net

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

Related

How do I fix a null reference error on a dbcontext in vb?

My code builds and runs, but when I reference the dbcontext during runtime I get "System.NullReferenceException: 'Object reference not set to an instance of an object.'". I use the context a lot other places in the solution and it works, but it is c# the other places. This is VB.
Imports DataServices
Imports Previdence.Domain.Model
Imports Previdence.Business.Model.Report
Namespace UserControls
Partial Class RemissionControl
Inherits UserControl
Private previdenceContext As PrevidenceContext
Private patient As Subject
Private remissionButtonStatus As Boolean?
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim snapshotId As Guid = Utility.StringToGuid(Request.QueryString("snapshotId"))
patient = (From su In previdenceContext.Subjects
Join ep In previdenceContext.Episodes On su.SubjectId Equals ep.SubjectId
Join sn In previdenceContext.Snapshots On ep.SubjectId Equals sn.SnapshotId
Where sn.SnapshotId = snapshotId
Select su).FirstOrDefault()
remissionButtonStatus = patient.RemissionButtonOn
If remissionButtonStatus = True Then
remissionRButtonYes.Checked = True
remissionRButtonNo.Checked = False
Else
remissionRButtonYes.Checked = False
remissionRButtonNo.Checked = True
End If
End Sub
'TODO: getting null reference error on the dbcontext
Private Sub remissionRButtonYes_click() Handles remissionRButtonYes.CheckedChanged
If remissionRButtonYes.Checked = True Then
patient.RemissionButtonOn = True
Else patient.RemissionButtonOn = False
End If
previdenceContext.SaveChanges()
End Sub
Private Sub remissionRButtonNo_click() Handles remissionRButtonNo.CheckedChanged
If remissionRButtonNo.Checked = True Then
patient.RemissionButtonOn = False
Else patient.RemissionButtonOn = True
End If
previdenceContext.SaveChanges()
End Sub
End Class
End Namespace
This should be the kind of error that gets caught by IntelliSense.
Anyway, you will avoid the error if you replace the declaration:
Private previdenceContext As PrevidenceContext with Private previdenceContext As New PrevidenceContext, however you code will still not work, because previdenceContext has no data.
You are probably missing a line of code to populate previdenceContext.
Because you use the previdenceContext in several members of your class, you can declared it at class level, and instantiate it in the Sub New(). The context must be disposed of, so your class needs to implements IDisposable and dispose of previdenceContext.
Partial Class RemissionControl
Implements IDisposable
Inherits UserControl
Private previdenceContext As PrevidenceContext
Sub New()
' This is the parameterless constructor. If you have a constructor with
' parameter such as passing the connection string name, use it. Do what you
' you do in your C# code.
previdenceContext New PrevidenceContext()
End Sub
' Your class implementation ...
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
If previdenceContext IsNot Nothing Then previdenceContext.Dispose()
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class

Google reCaptcha V2 Implementation VB.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

Change soap prefix to soapenv in .NET Web Service

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

jabber.net not working for vb.net

i am trying to use jabber.net for web application
i know this is for desktop application as given in below given link
http://www.codeproject.com/Articles/34300/Google-Chat-Desktop-Application-using-Jabber-Net
but i found a post on stack overflow related to this and it say that one dude has implemented it with web application
Web Chat Application - ASP.NET/Jabber/Ajax/WCF/Comet/ReverseAjax - Issues Faced - Seeking Insights
actually the code project code was written in c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using jabber.client;
using System.Threading;
using jabber.protocol.iq;
using jabber;
using Google.GData.Contacts;
using Google.GData.Extensions;
using jabber.protocol;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
static ManualResetEvent done = new ManualResetEvent(false);
private jabber.client.JabberClient jabberClient1=new jabber.client.JabberClient();
protected void Page_Load(object sender, EventArgs e)
{
jabberClient1.OnMessage += new MessageHandler(jabberClient1_OnMessage);
jabberClient1.OnDisconnect += new bedrock.ObjectHandler(jabberClient1_OnDisconnect);
jabberClient1.OnError += new bedrock.ExceptionHandler(jabberClient1_OnError);
jabberClient1.OnAuthError += new jabber.protocol.ProtocolHandler(jabberClient1_OnAuthError);
jabberClient1.User = "sa";
jabberClient1.Server = "gmail.com";
jabberClient1.Password = "download";
jabberClient1.Connect();
jabberClient1.OnAuthenticate += new bedrock.ObjectHandler(jabberClient1_OnAuthenticate);
}
void jabberClient1_OnAuthenticate(object sender)
{
done.Set();
}
void jabberClient1_OnAuthError(object sender, System.Xml.XmlElement rp)
{
if (rp.Name == "failure")
{
Response.Write("Invalid User Name or Password");
}
}
void jabberClient1_OnError(object sender, Exception ex)
{
Response.Write(ex.Message);
}
void jabberClient1_OnDisconnect(object sender)
{
Response.Write("Disconnected");
}
private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
{
Response.Write("Message Posted");
//frmChat[(int)chatIndex[msg.From.Bare]].ReceiveFlag = true;
//string receivedMsg = msg.From.User + " Says : " + msg.Body + "\n";
//frmChat[(int)chatIndex[msg.From.Bare]].AppendConversation(receivedMsg);
//frmChat[(int)chatIndex[msg.From.Bare]].Show();
}
}
}
so i converted it to vb.net like this
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports jabber.client
Imports System.Threading
Imports jabber.protocol.iq
Imports jabber
Imports Google.GData.Contacts
Imports Google.GData.Extensions
Imports jabber.protocol
Public Class GtalkIntegration
Inherits System.Web.UI.Page
Shared done As New ManualResetEvent(False)
Private WithEvents jabberClient1 As New jabber.client.JabberClient()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AddHandler jabberClient1.OnMessage, AddressOf jabberClient1_OnMessage
AddHandler jabberClient1.OnDisconnect, AddressOf jabberClient1_OnDisconnect
AddHandler jabberClient1.OnError, AddressOf jabberClient1_OnError
AddHandler jabberClient1.OnAuthError, AddressOf jabberClient1_OnAuthError
jabberClient1.User = "sa"
jabberClient1.Server = "gmail.com"
jabberClient1.Password = "download"
jabberClient1.Connect()
AddHandler jabberClient1.OnAuthenticate, AddressOf jabberClient1_OnAuthenticate
End Sub
Private Sub jabberClient1_OnAuthenticate(ByVal sender As Object)
done.[Set]()
End Sub
Private Sub jabberClient1_OnAuthError(ByVal sender As Object, ByVal rp As System.Xml.XmlElement)
If rp.Name = "failure" Then
Response.Write("Invalid User Name or Password")
End If
End Sub
Private Sub jabberClient1_OnError(ByVal sender As Object, ByVal ex As Exception)
Response.Write(ex.Message)
End Sub
Private Sub jabberClient1_OnDisconnect(ByVal sender As Object)
Response.Write("Disconnected")
End Sub
Private Sub jabberClient1_OnMessage(ByVal sender As Object, ByVal msg As jabber.protocol.client.Message)
Response.Write("Message Posted")
'frmChat[(int)chatIndex[msg.From.Bare]].ReceiveFlag = true;
'string receivedMsg = msg.From.User + " Says : " + msg.Body + "\n";
'frmChat[(int)chatIndex[msg.From.Bare]].AppendConversation(receivedMsg);
'frmChat[(int)chatIndex[msg.From.Bare]].Show();
End Sub
End Class
but it is giving me error like
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
please help me out guys thanks in advance
Make sure to reference jabber-net.dll, zlib.net.dll, and netlib.Dns.dll.

request querystring in variable

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.

Resources