Find SQL Server Instance on other computer on LAN - sql-server

I have the following function to find a SQL Server instance. It works fine on local computer. Would you please tell me how to use this function to check an instance on other computer on a Local Area Network? I am using VS 2008 (.NET Framework 3.5) and SQL Server Express 2005.
Private Function MyInstanceFound(ByVal MyInstanceName As String) As Boolean
Dim InstanceFound As Boolean = False
Dim MC As ManagedComputer = New ManagedComputer()
For Each SI As ServerInstance In MC.ServerInstances
If SI.Name.ToString = MyInstanceName Then
InstanceFound = True
Exit For
End If
Next
Return InstanceFound
End Function
Thank you in advance.
Regards,
SKPaul

You need to use another ManagedComputer constructor, like this one:
public ManagedComputer (
string machineName
)
ManagedComputer Constructor (String)

Public Shared Function GetServerList(ByVal cmbServers As ComboBox)
Dim Server As String = String.Empty
Dim instance As Sql.SqlDataSourceEnumerator = Sql.SqlDataSourceEnumerator.Instance
Dim table As System.Data.DataTable = instance.GetDataSources()
For Each row As System.Data.DataRow In table.Rows
Server = String.Empty
Server = row("ServerName")
If row("InstanceName").ToString.Length > 0 Then
Server = Server & "\" & row("InstanceName")
End If
cmbServers.Items.Add(Server)
Next
cmbServers.SelectedIndex = cmbServers.FindStringExact(Environment.MachineName)
End Function
Add combobox name txtservidores in form. Call function
GetServerList(txtServidores)

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.

Exception with sqlite database "no such table"

First of all I´m developing a database with autosuggest box. I´ve created a database with DB Browser and imported data. I was reading documentation in C# how connect database and retrieve data. The issue is show up an exception error:
enter image description here
I´ve connected the database in properties with content option. I paste the code:
Public NotInheritable Class METARTAF
Inherits Page
Dim dbpath As String = Path.Combine(ApplicationData.Current.LocalFolder.Path, "airportsdb.sqlite3")
Dim conn As SQLite.Net.SQLiteConnection = New SQLite.Net.SQLiteConnection(New WinRT.SQLitePlatformWinRT(), dbpath)
Dim airportinfo As List(Of String) = Nothing
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub AutoSuggestBox_TextChanged(sender As AutoSuggestBox, args As AutoSuggestBoxTextChangedEventArgs)
Dim datairport As New List(Of String)
Dim retrieve = conn.Table(Of flugzeuginfo)().ToList
If args.Reason = AutoSuggestionBoxTextChangeReason.UserInput Then
If sender.Text.Length > 1 Then
For Each item In retrieve
datairport.Add(item.IATA)
datairport.Add(item.ICAO)
datairport.Add(item.Location)
datairport.Add(item.Airport)
datairport.Add(item.Country)
Next
airportinfo = datairport.Where(Function(x) x.StartsWith(sender.Text)).ToList()
sender.ItemsSource = airportinfo
End If
Else
sender.ItemsSource = "No results..."
End If
End Sub
Private Sub AutoSuggestBox_SuggestionChosen(sender As AutoSuggestBox, args As AutoSuggestBoxSuggestionChosenEventArgs)
Dim selectedItem = args.SelectedItem.ToString()
sender.Text = selectedItem
End Sub
Private Sub AutoSuggestBox_QuerySubmitted(sender As AutoSuggestBox, args As AutoSuggestBoxQuerySubmittedEventArgs)
If args.ChosenSuggestion Is Nothing Then
stationidtxt.Text = args.ChosenSuggestion.ToString
End If
End Sub
Anyone could help about this?
Before you query or insert into a table, you should CREATE it. This tells SQLite what columns you have and suggests datatypes (on other rdbms's you get actual data type enforcement but SQLite does not do that). If this is your problem, you will want to spend some time with the SQLite documentation on data types and the ability to hook them into your application.
On the other hand, as you seem to be trying to retrieve data, this suggess one of two things is wrong. Either you care connecting to the wrong db (in which case SQLite will usually helpfully create an empty db for you!) or else you are specifying the wrong table.

public function to create and open a database connection

I have a client/server desktop application that I am having some database connection issues with on some of my clients pc's. When I wrote the app, I didn't know any better so I created and opened 1 database connection on application startup, and used that same connection all throughout the app. I know realize this is a bad idea since shaky network connections and it seems antivirus programs are causing these connection to be dropped at times, leading to some errors. I have hundreds of places in code where I need to go back and create/open/close the connection at the time they are being used.
The question is, is there any way to create a public function in which I can do just that, and then do a global find and replace to replace the connection name with the new function name?
something like:
Dim qry As NpgsqlCommand
sqlUpdateItem = "update table set field = value where id = 1"
qry = New NpgsqlCommand(sqlUpdateItem, con)
qry.ExecuteNonQuery()
to
Dim qry As NpgsqlCommand
sqlUpdateItem = "update table set field = value where id = 1"
qry = New NpgsqlCommand(sqlUpdateItem, newCon())
qry.ExecuteNonQuery()
public function newCon()
Dim con As New NpgsqlConnection(connectionString)
con.Open()
Return tcon
End Function
I tried this but no luck. I'm just looking for any possible solutions that don't involve me updating several lines of code in hundreds of places throughout my app. The nice thing is I would only need to do this for all commands, since I can pass a brand new connection into a data adapter and it will handle the opening/closing.
Here's an example of how I'd recommend you attempt it.
Enable option strict in your project. It's better to have your errors at compile time than at runtime.
Use a using statement to safely dispose of the database classes even if you get an exception.
Private _connectionString As String = "blah"
Public Function GetDbConnection() As NpgsqlConnection
Dim con As New NpgsqlConnection(_connectionString)
con.Open()
Return con
End Function
Public Sub DoMyQuery()
Using conn = GetDbConnection()
Using qry = New NpgsqlCommand("update table set field = value where id = 1", conn)
qry.ExecuteNonQuery()
End Using
End Using
End Sub

snapshotID parameter type mismatch when calling Render method on ReportExecution2005.asmx SSRS service

I am trying to render reports as PDF using the ReportExecution2005.asmx service endpoint on a SSRS 2012 server with MSSQL 2012 backend. When I call the Render method on the web service, I get the following error:
The parameter value provided for 'snapshotID' does not match the parameter type. ---> Microsoft.ReportingServices.Diagnostics.Utilities.ParameterTypeMismatchException: The parameter value provided for 'snapshotID' does not match the parameter type. ---> System.FormatException: String was not recognized as a valid DateTime
This error occurs with any report I try to render, snapshotID is not a parameter on the reports, and checking the configuration of the reports, they are not set up to be cached or use snapshots. We just recently moved from MSSQL 2005 to 2012, using the ReportExecution2005 endpoint with SSRS and SQL 2005 I never saw this error, it worked fine. I've tried adding snapshotID as a parameter with different values such as empty string, current time, etc. but that's apparently not what it's looking for. Below is the code I'm using to set up and call the Render method on the service. pstrExportFormat in my case will be "PDF"
Public Function ExportReport(pstrReportPath As String, plstParams As List(Of ReportParameter), pstrExportFormat As String) As Byte()
Dim lResults() As Byte = Nothing
Dim lstrSessionId As String
Dim execInfo As New reporting.ExecutionInfo
Dim execHeader As New reporting.ExecutionHeader
Dim lstrHistoryId As String = String.Empty
Try
Dim rs As New reporting.ReportExecutionService
Dim deviceInfo As String = "<DeviceInfo><PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth><MarginLeft>0.25in</MarginLeft><MarginRight>0.25in</MarginRight><MarginTop>0.25in</MarginTop><MarginBottom>0.25in</MarginBottom></DeviceInfo>"
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim params As New List(Of reporting.ParameterValue)
Dim param As reporting.ParameterValue
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
For Each lInputParam In plstParams
param = New reporting.ParameterValue
param.Name = lInputParam.Name
param.Value = lInputParam.Value
params.Add(param)
Next
rs.ExecutionHeaderValue = execHeader
execInfo = rs.LoadReport(pstrReportPath, lstrHistoryId)
rs.SetExecutionParameters(params.ToArray, "en-us")
lResults = rs.Render(pstrExportFormat, deviceInfo, "", "", "", Nothing, Nothing)
Catch ex As Exception
Throw
End Try
Return lResults
End Function
Some additional information, this code is from an app built in VS 2012 Pro and targets the .NET 2.0 framework. I have tried targeting a newer framework but that gives me a different ReportExecutionService object altogether and I can't assign credentials in the same way, the Render method is also different in that case.
Any ideas on a workaround, or a better way to render reports programmatically? Thanks.
I had this exact same problem today and figured out that, in the LoadReport method, you want to make sure the HistoryID has a value of Nothing (null in C#). Right now, you're passing it in with an empty string - change the declaration to
Dim lstrHistoryId As String = Nothing
Or change your method call to
rs.LoadReport(pstrReportPath, Nothing)

Set SSIS database package path

I am trying to execute a SSIS package located in a database programatically.
I am using this API:
Imports Microsoft.SqlServer.Dts.Runtime
I have an image describing the path (in database) to package but I cannot figure out how to set the packagePath property properly in the LoadFromSqlServer method.
Here is the image describing my package path in database:
You will need to add a reference to Microsoft.SqlServer.Management.IntegrationServices. For me, it does not show up in the SQL Server folders and I could only find it in the GAC.
C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Management.IntegrationServices\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Management.IntegrationServices.dll
There's also a dependency from that assembly to
C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Management.Sdk.Sfc\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Management.Sdk.Sfc.dll
Sub Main()
'
' Do not fault me for my poor VB skills nor my lack of error handling
' This is bare bones code adapted from
' http://blogs.msdn.com/b/mattm/archive/2011/11/17/ssis-and-powershell-in-sql-server-2012.aspx
Dim folderName As String
Dim projectName As String
Dim serverName As String
Dim packageName As String
Dim connectionString As String
Dim use32BitRuntime As Boolean
Dim executionId As Integer
Dim integrationServices As Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices
Dim catalog As Microsoft.SqlServer.Management.IntegrationServices.Catalog
Dim catalogFolder As Microsoft.SqlServer.Management.IntegrationServices.CatalogFolder
Dim package As Microsoft.SqlServer.Management.IntegrationServices.PackageInfo
' Dimensions in your example
folderName = "SSISHackAndSlash"
' dimCalendar in your example
projectName = "SSISHackAndSlash2012"
serverName = "localhost\dev2012"
' dimCalendar in your example (no file extension)
packageName = "TokenTest.dtsx"
connectionString = String.Format("Data Source={0};Initial Catalog=msdb;Integrated Security=SSPI;", serverName)
integrationServices = New Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices(New System.Data.SqlClient.SqlConnection(connectionString))
' There is only one option for an SSIS catalog name as of this posting
catalog = integrationServices.Catalogs("SSISDB")
' Find the catalog folder. Dimensions in your example
catalogFolder = catalog.Folders(folderName)
' Find the package in the project folder
package = catalogFolder.Projects(projectName).Packages(packageName)
' Run the package. The second parameter is for environment variables
executionId = package.Execute(use32BitRuntime, Nothing)
End Sub
In addition to billinkc answer.
Here is the C# version of the code:
string folderName = "name";
string projectName = "name";
string serverName = "localhost";
string packageName = "name";
string connectionString = string.Format("Data Source={0};Initial Catalog=msdb;Integrated Security=SSPI;", serverName);
var integrationServices = new IntegrationServices(newSystem.Data.SqlClient.SqlConnection(connectionString));
var catalog = integrationServices.Catalogs["SSISDB"];
var catalogFolder = catalog.Folders[folderName];
var package = catalogFolder.Projects[projectName].Packages[packageName];
long execId = package.Execute(false, null);
In my case I had to add 4 dlls:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.IntegrationServices.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
All the dependencies can be found C:\Windows\assembly\GAC_MSIL\
If you want to find the package location deployed in SQL server.
Open SSMS.
Connect to Integration Services.
Go to View and Click "Object Explorer Details".
Now you select your package to know the package path in SQL server.
Take a look at the screenshot below.
Ignore the server name because it will be parameter for the LoadFromSqlServer method.
So package path should be : \Stored Package\MSDB\Data Collector\PerfCountersUpload.
Hope this helps.

Resources