Why is my db not connecting? - sql-server

I am newbie to vb.net and i am trying to connect with a sql server.
my connection string here is:
<add name="ConString" connectionString="Data Source=LV-SC294\SQLEXPRESS;Initial Catalog=master;Persist Security Info=True;User ID=1111;Password=111111" providerName="System.Data.SqlClient"/>
Here is my DBConnection file where i connect to the server,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.Provider
Imports System.Configuration
Imports System.Web.Services
Imports System.Data.Odbc
Namespace CATTool
Public Class DBConnection
Protected con As OdbcConnection
Dim b As Boolean
Protected rs As Object
Public Function Open(Optional ByVal connection As String = "ConString") As Boolean
con = New OdbcConnection(ConfigurationManager.ConnectionStrings("ConString").ConnectionString)
Try
b = True
If (con.State.ToString <> "open") Then
con.Open()
End If
Return b
Catch ex As Exception
Return False
End Try
End Function
and finally here is where i call my DbConnection.. Here i am trying to set up the connection with the server and also execute the query to fetch rows. How ever the connection is not established.It keeps throwing the message "Connection didn't establish"
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports CAT_Tool.CATTool
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Namespace CAT_Tool
Public Class SummaryController
Inherits System.Web.Mvc.Controller
'
' GET: /Summary
Protected DB As DBConnection = New DBConnection()
Private Property Val As Object
Function Index() As ActionResult
Return View()
End Function
Function Summary() As ActionResult
Return View()
End Function
<WebMethod()> _
Public Function Get_Territory()
MsgBox("Filling Territory")
Dim Query As String = "select distinct Territory from dbo.CWS_WEBTOOL_USG"
Dim dbcon As Boolean = DB.Open()
If (dbcon = True) Then
MsgBox("Connection Established")
Val = DB.selectdata(Query)
DB.Close()
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In Val.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In Val.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
MsgBox("Returning values")
MsgBox(rows)
Return serializer.Serialize(rows)
Else
MsgBox("Connection Did'nt Establish")
Return Content(dbcon.ToString)
End If
Return View()
End Function
My sql server details are as follows:
ServerName = LV-SC294\SQLEXPRESS
Authentication : SQLServer Authentication

I agree with #AllanS.Hansen that it is best to use System.Data.SqlClient to access SQL Server from managed code. Your connection string is a proper SqlClient connection string, although one usually specifies an application database rather than the master system database.
If you want to use ODBC (e.g. same code supporting different DBMS systems), you'll need to change the connection string and provider in the config file. For example, using the latest SQL Server ODBC Driver:
<add name="ConString" connectionString="Driver={ODBC Driver 11 for SQL Server},Server=LV-SC294\SQLEXPRESS;Database=YourDatabase;UID=1111;PWD=111111" providerName="System.Data.Odbc"/>

Related

Can you use MS sync framework with sql server always encrypted tables

I'm having following error:
Operandentypkollision: nvarchar(max) ist inkompatibel mit nvarchar(max) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name =
Environment:
Visual Studio 2019 Enterprise
SQL Server 2019 LocalDB (localServer)
SQL Server 2019 Standart (remoteServer)
I've created a table "TestTable" with two columns on the remoteServer, test_id (pk, auto_increment) and test_data (nvarchar(max)). I've enabled sql always encrypted via wizard and testet the encryption, everythings works fine.
Now I've copied the MDF from the remoteServer to a local client with LocalDB installed and attached the MDF. I've copied the encryption-cert to the local machine personal current user store and testet the access, everything works fine as well.
I've added following connectionstrings to my vb winforms .net 4.7.2 application app.config:
<connectionStrings>
<add name="local" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\path\to.mdf;Column Encryption Setting=enabled;Initial Catalog=MyCatalog;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="remote" connectionString="Data Source=myserver.some.where\PRODDB;Initial Catalog=MyCatalog;Column Encryption Setting=enabled;Persist Security Info=True;User ID=xxxx;Password=xxxx"
providerName="System.Data.SqlClient" />
</connectionStrings>
I've bound both connections to a grid and successful the same results.
From my point of view are both connections strings correct and de decryption is working aswell.
The Problem:
I want to use microsoft sync framework to keep those two databases in sync.
I use following code:
Public Class dbSync
Private operations As New ConnectionProtection(Application.ExecutablePath)
Public Sub doSync()
operations.DecryptFile()
Dim localStr As String = ConfigurationManager.ConnectionStrings("localServer").ConnectionString
Dim OnlineStr As String = ConfigurationManager.ConnectionStrings("remoteServer").ConnectionString
sync("TestTable", localStr, OnlineStr)
operations.EncryptFile()
End Sub
Private Sub Init(ByVal table As String, ByVal localStr As String, ByVal OnlineStr As String)
Try
Using servCon As SqlConnection = New SqlConnection(OnlineStr)
Using localCon As SqlConnection = New SqlConnection(localStr)
Dim scopeDesc As DbSyncScopeDescription = New DbSyncScopeDescription(table)
Dim tableDesc As DbSyncTableDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(table, servCon)
scopeDesc.Tables.Add(tableDesc)
Dim servProv As SqlSyncScopeProvisioning = New SqlSyncScopeProvisioning(servCon, scopeDesc)
servProv.SetCreateTrackingTableDefault(DbSyncCreationOption.CreateOrUseExisting)
servProv.Apply()
Dim localProv As SqlSyncScopeProvisioning = New SqlSyncScopeProvisioning(localCon, scopeDesc)
localProv.SetCreateTrackingTableDefault(DbSyncCreationOption.CreateOrUseExisting)
localProv.Apply()
End Using
End Using
Catch ex As Exception
End Try
End Sub
Private Sub sync(ByVal scope As String, ByVal localStr As String, ByVal OnlineStr As String)
Init(scope, localStr, OnlineStr)
Using servCon As SqlConnection = New SqlConnection(OnlineStr)
Using localCon As SqlConnection = New SqlConnection(localStr)
Dim agent As SyncOrchestrator = New SyncOrchestrator
agent.LocalProvider = New SqlSyncProvider(scope, localCon)
agent.RemoteProvider = New SqlSyncProvider(scope, servCon)
agent.Direction = SyncDirectionOrder.DownloadAndUpload
Dim syncRelRemote As RelationalSyncProvider = TryCast(agent.RemoteProvider, RelationalSyncProvider)
AddHandler syncRelRemote.SyncProgress, AddressOf dbProvider_SyncProgress
Dim syncRelLocalFailed As RelationalSyncProvider = TryCast(agent.LocalProvider, RelationalSyncProvider)
AddHandler syncRelLocalFailed.ApplyChangeFailed, AddressOf dbProvider_SyncProcessFailed
Dim syncRelRemoteFailed As RelationalSyncProvider = TryCast(agent.LocalProvider, RelationalSyncProvider)
AddHandler syncRelRemoteFailed.ApplyChangeFailed, AddressOf dbProvider_SyncProcessFailed
agent.Synchronize()
End Using
End Using
CleanUp(scope, localStr, OnlineStr)
End Sub
Private Shared Sub dbProvider_SyncProgress(ByVal sender As Object, ByVal e As DbSyncProgressEventArgs)
End Sub
Private Shared Sub dbProvider_SyncProcessFailed(ByVal sender As Object, ByVal e As DbApplyChangeFailedEventArgs)
End Sub
Public Enum DbConflictType
ErrorsOccured = 0
LocalUpdateRemoteUpdate = 1
LocalUpdateRemoteDelete = 2
LocalDeleteRemoteUpdate = 3
LocalInsertRemoteInsert = 4
LocalDeleteRemoteDelete = 5
End Enum
Private Shared Sub CleanUp(ByVal scope As String, ByVal localStr As String, ByVal OnlineStr As String)
Using servCon As SqlConnection = New SqlConnection(OnlineStr)
Using localCon As SqlConnection = New SqlConnection(localStr)
Dim serverDep As SqlSyncScopeDeprovisioning = New SqlSyncScopeDeprovisioning(servCon)
Dim localDep As SqlSyncScopeDeprovisioning = New SqlSyncScopeDeprovisioning(localCon)
serverDep.DeprovisionScope(scope)
serverDep.DeprovisionStore()
localDep.DeprovisionScope(scope)
localDep.DeprovisionStore()
End Using
End Using
End Sub
End Class
The errors happens in line:
servProv.Apply()
while trying to provision.
When I try everything without using always encrypted, the syncronization works perfectly, the trackingtables are created, everything is fine.
What makes me wondering is that when I watch the var tableDesc
Dim tableDesc As DbSyncTableDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(table, servCon)
is that the attribute tableDesc.columns(1).Type is nvarchar, regardless if I change servCon with localCon. So the type seems to be getting correctly, but while applying the provisioning i get the error.
I have the feeling that I need to adjust tableDesc in some way, but couldn't find what.
I hope I managed to describe my problem properly, this is my first stackOverflow-post (yeah :-) )
Given that Sync Framework is completely out of support and not updated in the last 10 years- no you cannot. And welcome.

Getting the connection string from an imported source

I have added a new datasource from a SQL-server into my project and want to create a SQLConnection (using System.Data.SqlClient).
During the datasource creation I saved the Connectionstring as Dev_DBConnectionString and want to use this now but I have no clue how. I tried
ConsoleApplication1.Properties.Settings.Default.masterConnectionString
(this is how some c# tutorials doing it) but get the error: Properties is not a Member of ConsoleApplication1. I have checked some vb.net tutorials (e.g.) but they are using the descriptive way like
Data Source=MSSQL1;Database=AdventureWorks;" & "Integrated Security=true;
But I guess that the string is already somewhere in my system. Anyone who can help me out here?
FIRST
You have to setup your connection!
Imports System.Data.SqlClient
Imports System.Data
Public Class SQLTools
Inherits System.Windows.Forms.Form
Private Const SqlString As String = Dev_DBConnectionString
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private Sub Conn()
myConn = New SqlConnection(SqlString)
End Sub
Now you can enjoy your DB connection
It's time to do what you want! you just need to call Conn() to setup everything and than you have to open the connection using MyConn.Open()
Dev_DBConnectionString problems
You can always write it again.
e.g.
Private Const SqlString As String = "Server=****;Database=****;User ID=****;Password=****;Integrated Security=SSPI;"

VB.Net Open image from database to picturebox

I'm trying to open an image from my database to a picture box but I just don't how to do it.
I've searched for some answers and I am not familiar with the codes for I am beginner only.
The only codes that I researched about are for connecting the database to the system:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDbConnection
Public acsdr As OleDbDataReader
Public acsda As New OleDbDataAdapter
Public acscmd As New OleDbCommand
Public strsql As String
Public acsds As New DataSet
Public Sub connect()
Try
acsconn.ConnectionString = "provider=microsoft.jet.oledb.4.0; data source=|datadirectory|\database1.mdb;"
acsconn.Open()
If acsconn.State = ConnectionState.Open Then
MsgBox("Connected")
Else
MsgBox("Error")
End If
Catch ex As Exception
End Try
End Sub
End Module
I do not know what is next. BTW, those codes - I used it for saving the image to the database.
I think this is the sort of thing you are looking for:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub

VB.NET/SQL System.Argument Exception

I am brand new to programming, and I have been encountering several errors as I work to build an application. The additional information section of the Visual Studio error box delivers the following message:
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Format of the initialization string does not conform to specification starting at index 0.
This occurs as the application attempts to execute the following line of code:
Dim da As New SqlDataAdapter(sql, cs)
I have been working to troubleshoot this to no avail. Thanks for any help you are kind enough to provide! Please find the additional info/code for the class below:
Imports System.Data
Imports System.Data.SqlClient
Public Class DButil
Public cs As String
Public Function GetDataView(ByVal sql As String) As DataView
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sql, cs)
da.Fill(ds)
Dim dv As New DataView(ds.Tables(0))
Return dv
End Function
Public Sub New()
cs = "Data Source=(LocalDB)\v11.0"
cs += "Data Source=(LocalDB)'C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf';Integrated Security=True;"
cs += "Integrated Security =True;Connect Timeout=30"
End Sub
End Class
Thanks for the reply, Steve. That removed the error from the following line: Dim da As New SqlDataAdapter(sql, cs). An error now appears on the following line: da.Fill(ds). This error says SqlException unhandled, and that an expression of non-boolean type where a condition is expected near ",". Thoughts? –
Your connection string is really wrong.
For Sql Server 2012 with LocalDB instance you need
Public Sub New()
cs = "Server=(LocalDB)\v11.0;"
cs += "Integrated Security=True;"
cs += "AttachDbFileName=C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf;"
End Sub
See examples of connectionstrings for Sql Server at connectionstrings.com
Your connection string is definitely wrong. Have a look at http://www.connectionstrings.com/sqlconnection/localdb-automatic-instance-with-specific-data-file/
Here is an example of how to query your database and return a dataview
Public Function GetDataView(sql As String) As DataView
Dim cs = "Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf;"
Using cnn As New SqlConnection(cs)
Using cmd As New SqlCommand(sql, cnn)
Try
cnn.Open()
Dim t As New DataTable
t.Load(cmd.ExecuteReader)
Return New DataView(t)
Catch ex As Exception
''handle the error
End Try
End Using
End Using
End Function

How to dynamically pass connectionstrings in EF5

I'm struggling with a project, converted to .net 4.5.
I have some functions like this:
Public Shared Function Load(iJaar As Integer, iKwartaal As Integer) As List(Of LoonDetail_121)
Dim oLoonDetails As New List(Of LoonDetail_121)
Try
Dim oDB As New SDWMasterSDWDBEntities(DBConnections.ConnStringPrisma)
Dim dStartDate As New Date(iJaar, ((iKwartaal - 1) * 3) + 1, 1)
Dim dEndDate As New Date(iJaar, ((iKwartaal - 1) * 3) + 4, 1)
oLoonDetails = oDB.LoonDetail_121.Where(Function(x) x.EindPeriode_121 >= dStartDate And
x.EindPeriode_121 < dEndDate).ToList
Catch ex As Exception
Throw New Exception(GetCurrentMethod.Name & " " & ex.Message)
End Try
Return oLoonDetails
End Function
When I convert this function to EF5, I get errors, since my SDCDBLonenEntities is not inherited anymore from ObjectContext, but it is inherited from DbContext.
Before, EF automatically created a constructor where I can pass my Connection String.
This is very easy, because I use different connectionstrings, depending on my Solution Configuration (Debug/Release).
In EF5, the constructor doesn't accept Connectionstrings anymore.
I tried to create a partial class of my Entity, and create my own constructor, but I can't get this working:
Partial Public Class SDWMasterSDWDBEntities
Inherits DbContext
Public Sub New(sConnString As String)
MyBase.New(sConnString)
End Sub
End Class
For another project, I adapted my Project-file to use different app.config files for each solution configuration, but that was a p.i.t.a to maintain and for me not a clean solution.
So my question is: How can I use EF5 with my own personal Connectionstrings?
These are my Connection Strings by the way:
#If DEBUG Then
Friend ConnStringSDW As String = "metadata=res://*/Entities.SDWDB.csdl|res://*/Entities.SDWDB.ssdl|res://*/Entities.SDWDB.msl;provider=System.Data.SqlClient;provider connection string='data source=SDWDB01\SDWSQL;initial catalog=SDWDB_DEV;persist security info=True;user id=usr;password=pwd;multipleactiveresultsets=True;App=EntityFramework'"
#Else
Friend ConnStringSDW As String = "metadata=res://*/Entities.SDWDB.csdl|res://*/Entities.SDWDB.ssdl|res://*/Entities.SDWDB.msl;provider=System.Data.SqlClient;provider connection string='data source=SDWDB01\SDWSQL;initial catalog=SDWDB_PROD;persist security info=True;user id=usr;password=pwd;multipleactiveresultsets=True;App=EntityFramework'"
#End If
And I get the error "The entity type SDW_USERS_MASTER is not part of the model for the current context.", when I execute this function:
Public Shared Function LoadAll() As List(Of SDW_USERS_MASTER)
Dim oUsers As New List(Of SDW_USERS_MASTER)
Try
Using oDB As New SDWMaster.SDWMasterSDWDBEntities(DBConnections.ConnStringSDW)
oUsers = (From tmpUsers In oDB.SDW_USERS_MASTER
Select tmpUsers).ToList.OrderBy(Function(x) x.Login).ToList
End Using
Catch ex As Exception
Debug.Print(ex.Message)
Throw New Exception(GetCurrentMethod.Name & " " & ex.Message)
End Try
Return oUsers
End Function
Create a new partial class with the same name as your context, then overload the constructor. So, if your context class is named "myContext", then you would have:
Imports System
Imports System.Data.Entity
Imports System.Data.Entity.Infrastructure
Imports System.Data.Objects
Imports System.Data.Objects.DataClasses
Imports System.Linq
Partial Public Class myContext
Inherits DbContext
Public Sub New(connectionString As String)
MyBase.New(connectionString)
End Sub
End Class

Resources