clr table valued functions - sql-server

I created this clr table valued functions in VB.NET using VS 2017 and sql 2014:
Imports System.Collections
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Partial Public Class UserDefinedFunctions
<SqlFunction(DataAccess:=DataAccessKind.Read, FillRowMethodName:="my_FillRow", TableDefinition:="Name nchar(27)")>
Public Shared Function getNames() As IEnumerable
Dim strConn As String
Dim cmd As SqlCommand = Nothing
Dim reader As SqlDataReader = Nothing
Dim Name As SqlString
Dim resultCollection As New ArrayList()
strConn = "Server=localhost\myserver;" +
"Database=Test;" +
"User ID=user;" +
"Password=pwd;"
cmd = New SqlCommand("select top 10 Name from tblNames", New SqlConnection(strConn))
cmd.CommandType = CommandType.Text
cmd.CommandTimeout = 240
cmd.Connection.Open()
reader = cmd.ExecuteReader()
While reader.Read()
Name = reader.GetSqlString(1)
resultCollection.Add(New DataRec(Name))
End While
Return resultCollection
End Function
Private Class DataRec
Public Name As SqlString
Public Sub New(Name As SqlString)
Me.Name= Name
End Sub
End Class
Public Shared Sub my_FillRow(dataObj As Object, ByRef Name As SqlString)
Dim rec As DataRec = DirectCast(dataObj, DataRec)
Name = rec.Name
End Sub
End Class
after creating assembly and function
CREATE ASSEMBLY MyTot
FROM 'C:\source\repos\udf-sql-01\udf-sql-01\bin\Debug\udf-sql-01.dll'
WITH PERMISSION_SET = SAFE;
GO
CREATE FUNCTION getNames()
RETURNS TABLE (
Name nchar(27)
)
AS EXTERNAL NAME MyTot.UserDefinedFunctions.getNames;
go
and try function:
SELECT * FROM dbo.getNames();
i get this error:
Messaggio 6522, livello 16, stato 1, riga 28
A .NET Framework error occurred during execution of user-defined routine or aggregate "getNames":
System.Security.SecurityException: Richiesta di autorizzazione di tipo 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' non soddisfatta.
System.Security.SecurityException:
in System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
in System.Security.PermissionSet.Demand()
in System.Data.Common.DbConnectionOptions.DemandPermission()
in System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
in System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
in System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
in System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
in System.Data.SqlClient.SqlConnection.Open()
in UserDefinedFunctions.FindInvalidEmails()
The sql instance and visual studio are on the same pc.
I have tried with a sql user and with a windows user (both user are correctly configured on sql). The sql instance is configured for mixed authentication (windows and sql).
Any idea?
Thanks

Making a non-context connection requires EXTERNAL_ACCESS permission for the stored procedure.
So change
WITH PERMISSION_SET = SAFE;
to
WITH PERMISSION_SET = EXTERNAL_ACCESS;
Or if that is the same instance that hosts the CLR, use a Context Connection instead of opening a regular SqlConnection.

Related

Image not inserted into the SQL Server database

I am a beginner here may I know how to resolve my problem?
I create a program to save images in SQL Server, but this is not working.
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Thank you and hopefully for your response guys!
Here is the code:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form5
Dim connection As New SqlConnection("Server=kohyoung-aoi\sa; Database = testDB; Integrated Security = true")
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim command As New SqlCommand("insert into Table_Image1 (Name, Description, Barrowed, Returned, Picture) values (#Name, #Description, #Barrowed, #Returned, #Picture)", connection)
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = Txt1.Text
command.Parameters.Add("#Description", SqlDbType.VarChar).Value = Txt2.Text
command.Parameters.Add("#Barrowed", SqlDbType.VarChar).Value = txt3.Text
command.Parameters.Add("#Returned", SqlDbType.VarChar).Value = txt4.Text
command.Parameters.Add("#Picture", SqlDbType.Image).Value = ms.ToArray()
connection.Open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Image Inserted")
Else
MessageBox.Show("Image not Inserted")
End If
End Sub
I expected to run in normal condition and the output is to save all images into SQL Server.

My Question Is About Implementing Login Page To SQL Server, Error In "Adapter.Fill(Table)"

Sorry if i am posting this in the wrong section, i have no idea how any of this works and am a total noob to coding. I am however passionate and would like some help. I will respond quickly to any questions you guys may have so i can provide further information. Without further ado, here is my code. I will explain the issue below.
Imports System.Data.SqlClient
Imports System.Data
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server = M's PC; Database = tyre_stocks_database_plain1.accdb; Integrated Security = true")
Dim command As New SqlCommand("select * from Login_info where Username = #Username and Password = #Password", connection)
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = TextBoxUsername.Text.ToString()
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = TextBoxPassword.Text.ToString()
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("Username Or Password Is Invalid")
Else
MessageBox.Show("Login Successful")
End If
End Sub
End Class
I am getting an error to do with "adapter.Fill(table)". The program states:
"System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'"
If it is still a bit unclear, i am trying to create a login page that "allows entry" to the user, provided they have the correct username and password that is stored in the database.
I have made sure that the connection to my Microsoft Access database is active by checking for the green plug sign next to the database name. If anyone could provide any information on how to help whatsoever i would be very grateful. Please bare in mind i am extremely new to coding and thus a total noob (as previously mentioned :P) i will respond promptly to any questions as to provide further information. Thank you fellow coders !
You didn't give the adapter the connection needed.
Dim adapter As New SqlDataAdapter(command, connection)
your code was missing Connection parameter. check line 15 where you need to supply the connection. Second thing is to check your connection string , it should have valid server and database names.
Imports System.Data.SqlClient
Imports System.Data
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("Server = M's PC; Database = tyre_stocks_database_plain1.accdb; Integrated Security = true")
Dim command As New SqlCommand("select * from Login_info where Username = #Username and Password = #Password", connection)
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = TextBoxUsername.Text.ToString()
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = TextBoxPassword.Text.ToString()
Dim adapter As New SqlDataAdapter(command, connection)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show("Username Or Password Is Invalid")
Else
MessageBox.Show("Login Successful")
End If
End Sub
End Class

Error connecting to SQL Server 2012 with VB.NET 2010

I have been trying to fix a project which already use a 100% connections to Oracle. They are trying to upgrade the project to start using SQL Server 2012 Management Studio. But I'm having issues connecting to the database. We use Windows authentication.
I can login fine directly to SQL Server 2012 using Management Studio and Windows authentication. If I create a fresh new WindowsApplication1 project to test the connection code it works fine, I'm using this code (and get an error is at conn.Open()):
Imports System.Data.SqlClient
Public Class Open_Filing_Image
'Create ADO.NET objects.
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private results As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Create a Connection object.
Dim connStr As [String] = "Server=servername; Database=dbname; Integrated Security=True"
myConn = New SqlConnection(connStr)
'Create a Command object.
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT DdocName FROM dbo.Document WHERE XAlaskaID = '72010' and DdocType = 'Filings'"
'Open the connection.
Try
myConn.Open()
MsgBox("Connection Open ! ")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
myReader = myCmd.ExecuteReader()
'Concatenate the query result into a string.
Do While myReader.Read()
results = myReader.GetValue(0)
Loop
'Display results.
Dim documentID As String = results
Dim outPath As String = "http://address.internet`enter code here`/" + documentID + (".pdf")
System.Diagnostics.Process.Start(outPath)
'Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
Error message:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The specified data could not be decrypted.
Thank you.
Fix it doing some research and some assistance by another programmer:
The project had a Bcrypt reference that block the connections to SQL. I delete all Bcrypt and add transport credentials to Windows in the app.config. any way thanks guys.

Visual Studio 2010 - cannot reconnect to SQL Server instance after project is saved

Using Visual Studio 2010 I am able to start a new project using ADODB (Microsoft ActiveX Data Objects 6.1 Library COM 6.1.0.0) to connect to MS Access and SQL Server, save the project, re-open the project and it all works as expected. BUT when I do this trying to connect to a SQL Server Instance it will work until I save the project after which I always get the error: "SQL Server does not exist or access denied".
Here is the code for my test console application;
Module Module1
Sub Main()
Dim cn As New ADODB.Connection()
Dim rs As New ADODB.Recordset()
Dim cnStr As String
' Modify this connection string to reflect your server and logon information.
' Store the connection to a variable to be used throughout this example.
cnStr = "Provider=SQLOLEDB;Initial Catalog=Firehouse;Data Source=devclstr\devclstr;" & _
"User ID=xxx;Password=xxx;"
' 1. Connect through the Connectionstring property.
cn.ConnectionString = cnStr
cn.Open()
rs.Open("select * from usr_sec", cn)
Dim da As New System.Data.OleDb.OleDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write("There are " & ds.Tables(0).Rows.Count.ToString & " total users.")
Console.ReadLine()
rs = Nothing
cn.Close()
cn = Nothing
End Sub
End Module
This will work only in the following scenario: start new console project, enter the code, add the "ActiveX Data Objects 6.1 Library" reference, and it runs as expected. As soon as I save it each subsequent execution gives me the following error:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2147467259
HResult=-2147467259
Message=[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
Source=Microsoft OLE DB Provider for SQL Server
StackTrace: at ADODB._Connection.Open(String ConnectionString, String UserID, String Password, Int32 Options)
Please share any insight in how to resolve this problem
Normally, I'd advise against using the COM approach, when there are built in connectors, so instead, something like:
Imports System.Data.SqlClient;
Module Module1
Sub Main()
' Modify this connection string to reflect your server and logon information.
Dim cnStr As String = "Initial Catalog=Firehouse;Data Source=devclstr\devclstr;User ID=xxx;Password=xxx;"
Using con as New SqlConnection(cnStr)
con.Open()
Using cmd as New SqlCommand("select * from usr_sec", con)
Using da As New SqlDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write(String.Format("There are {0} total users.", ds.Tables(0).Rows.Count))
Console.ReadLine()
End Using
End Using
End Using
End Sub
End Module

retrieving data in VB from SQL

I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class
1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()

Resources