connection to SQL server - asp.net

I am trying to do connection between SQL server and asp.net (vb code).My SQl Server name is (Local)
and my vb codes are:
Imports System.Data
Imports System.Data.Sql
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.UI
Imports System.Web.Security
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls.WebParts
Partial Class _Default
Inherits System.Web.UI.Page
Public cn As New SqlConnection
Public cmd As New SqlCommand
Public da As SqlDataAdapter
Public dr As SqlDataReader
Public ds As DataSet = New DataSet
Public sql As String = Nothing
Public ConString As String = ("Data Source=(local);Initial Catalog=dbSQL;Integrated Security=True") 'this is connected to the server
Public Sub MyCn()
If cn.State = Data.ConnectionState.Open Then cn.Close()
cn.ConnectionString = ConString
cn.Open()
End Sub
but an error message keeps appearing which is :
Cannot open database "dbSQL" requested by the login. The login failed.
Login failed for user 'window8\windows 8'.
please help

Be sure to add window8\windows 8 user to the allowed accounts and add the login entry for this user in the desired database. See this:
http://www.youtube.com/watch?v=t8f1lGdnXJY

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

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

how to dynamically compile a ashx file?

I have a ashx file in a asp.net web project. It has a code behind cs file. The cs file is compiled into project dll & deployed to production. I found no way to dynamically change the cs file without deploying the whole project dll.
I have been putting c# code into aspx (not .cs) file, after deployment, I can make change to a single aspx file, and deploy, IIS can dynamically compile & merge with its code behind c# code.
Can I do the similar thing with ashx file?
Here is a quote from MSDN. http://msdn.microsoft.com/en-us/library/ms366723(v=vs.100).aspx
ASP.NET supports the dynamic compilation of ASP.NET pages (.aspx files), ASP.NET Web services (.asmx files), ASP.NET HTTP handlers (.ashx files)
thanks, this can save me lots of time!
I figured it out.
add a Generic handler - Handler1.ashx in visual studio
delete the cs file which auto-created.
open ashx again,
remove CodeBehind="Handler1.ashx.cs"
add c# code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World2");
}
public bool IsReusable
{
get
{
return false;
}
}
}
<%# WebHandler Language="VB" Class="FileVB1" %>
Imports System
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class FileVB1 : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim Slno As Integer = GlobalVariables.Slno
Dim bytes As Byte()
Dim fileName As String, contentType As String
Dim constr As String = ConfigurationManager.ConnectionStrings("APMCUBIntranetConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Slno,FileName, Valid FROM Manuals WHERE Slno=#Id"
cmd.Parameters.AddWithValue("#Id", Slno)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
Bytes = DirectCast(sdr("Valid"), Byte())
contentType = "application/pdf"
fileName = sdr("FileName").ToString()
End Using
con.Close()
End Using
End Using
context.Response.Buffer = True
context.Response.Charset = ""
If context.Request.QueryString("download") = "1" Then
context.Response.AppendHeader("Content-Disposition", Convert.ToString("attachment; filename=") & fileName)
End If
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
context.Response.ContentType = "application/pdf"
context.Response.BinaryWrite(bytes)
context.Response.Flush()
context.Response.[End]()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Please solve my problem i'm getting error at (Bytes = DirectCast(sdr("Valid"), Byte()))

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"

Resources