Connecting to a SQL Server 2012 database in Visual Studio 2008 - c#

I am currently developing a mobile application based on Windows CE for my team to track out assets and store them in our existing database.
I am able to develop and deploy the software successfully however I can't seem to connect to my SQL Server 2012 database from Visual Studio 2008. When I try to connect from Visual Studio 2017, it works just fine.
This is my test code only not my real asset tracker code so it wont have the UI I built for the asset tracker app.
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace test_smart_device
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button_connect);
}
private void button_connect(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=172.16.206.20;Initial Catalog=IBusinessTest;Integrated Security=SSPI;User ID=username;Password=123456";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
When I try to connect to my database, I get this error:
This is from the debugger when I put the breakpoint at the catch statement

Two things stick out to me:
You connection string includes Integrated Security=SSPI;, but you also include User ID=username;Password=123456 - so which is it, are you using Integrated Security (ie. logging in with the Windows user that the program is running as - domain or identical workgroup credentials on both the CE device and SQL Server), or are you trying to use SQL Server auth (by specifying a user ID and password)? You can't use both.
The error SQL Server does not exist or access denied implies that your connection was rejected, but doesn't say why. If it's not credentials then it could be the connection itself. Have you checked that the server is remotely accessible from the device? Are they on the same local network? If using a physical device on WiFi, does it have permission to communicate with other devices on the network (some WiFi routers, especially corporate ones, have the option of only allowing traffic to the gateway, and rejecting requests to local addresses).

I've decided that I won't use direct server connection using sqlClient class. Instead I will host a SOAP service on my server that will take my input in XML format via a HTTP link.
using System.Net;
using System.Xml;
public static void Execute_soap(string l_mat, decimal l_qty, string l_batch)
{
HttpWebRequest request = CreateWebRequest();
request.Credentials = CredentialCache.DefaultCredentials;
XmlDocument soapEnvelopeXml = new XmlDocument();
NewMethod(soapEnvelopeXml, l_mat, l_qty, l_batch);
request.AllowWriteStreamBuffering = true;
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
using (StreamWriter writer = new StreamWriter(#"C:\Users\ikhsan\Desktop\xml_file.txt"))
{
writer.WriteLine(soapResult);
}
Console.WriteLine(soapResult);
Console.WriteLine("Done!");
//Console.ReadKey();
}
}
}
private static void NewMethod(XmlDocument soapEnvelopeXml, string mat, decimal qty, string batch)
{
string xml_str = #"<soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">" +
#"<soap12:Body>" +
#"<PCB_SCAN_EMS xmlns=""http://tempuri.org/"">" +
#"<part_num>" + mat + "</part_num>" +
#"<qty>" + qty.ToString() + "</qty>" +
"<batch>" + batch + "</batch>" +
"<ems_loc>2106</ems_loc>" +
"</PCB_SCAN_EMS>" +
"</soap12:Body>" +
"</soap12:Envelope>";
soapEnvelopeXml.LoadXml(xml_str);
}
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://172.16.206.19/PART_INFO/get_part_quantity_from_bin.asmx");
webRequest.ContentType = #"application/soap+xml;charset=UTF-8";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
This will work in all windows mobile version

Related

Connecting Visual Studio to a SSH Tunneled MySQL Server

I was looking for a workaround for configuring my database connection.
I saw that opening 3306 port is dangerous and we should be using SSH Tunnel instead to connect to the database.
I configured my MySQL server using docker and successfully connected it using MySQL Workbench
Now I have to configure and connect it to Visual Studio 2022 to be able to query to the database.
Visual Studio 2022 is only supported by MySQL Data thru NuGet packages which doesn't have a gui connection setup.
I installed Visual Studio 2019 which is officially supported by MySQL Database and can be configured thru Data Source.
How can I setup MySQL Database connection to my Visual Studio if it's SSH Tunnel configured.
Add Connection window only shows basic information about the connection. I'm not sure how to configure this over a SSH Tunnel.
Thank you in advance.
For security reasons, sometimes the database server can only be accessed through SSH. For example, the MySql service is installed on server A, and machine A can only be accessed by machine B, and the deployment environment may be on machine C. In this case, C The server connects to the A server through the B server. At this time, SSH connection is required, and the SSH.NET class library is required:
code show as below:
using MySql.Data.MySqlClient;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SSHMySql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SSHConnectMySql();
}
public void SSHConnectMySql()
{
string SSHHost = "*.*.*.*"; // SSH address
int SSHPort = ; // SSH port
string SSHUser = "user"; // SSH username
string SSHPassword = "pwd"; // SSH password
string sqlIPA = "127.0.0.1";// Map addresses In fact, it is possible to write other MySql on Linux My.cnf bind-address can be set to 0.0.0.0 or not
string sqlHost = "192.168.1.20"; // The IP address of the machine installed by mysql can also be an intranet IP, for example: 192.168.1.20
uint sqlport = ; // Database port and mapping port
string sqlConn = "Database=mysql;Data Source=" + sqlIPA + ";Port=" + sqlport + ";User Id=user;Password=pwd;CharSet=utf8";
string sqlSELECT = "select * from user";
PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(SSHHost, SSHPort, SSHUser, SSHPassword);
connectionInfo.Timeout = TimeSpan.FromSeconds();
using (var client = new SshClient(connectionInfo))
{
try
{
client.Connect();
if (!client.IsConnected)
{
MessageBox.Show("SSH connect failed");
}
var portFwdL = new ForwardedPortLocal(sqlIPA, sqlport, sqlHost, sqlport); // map to local port
client.AddForwardedPort(portFwdL);
portFwdL.Start();
if (!client.IsConnected)
{
MessageBox.Show("port forwarding failed");
}
MySqlConnection conn = new MySqlConnection(sqlConn);
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.SelectCommand = new MySqlCommand(sqlSELECT, conn);
try
{
conn.Open();
DataSet ds = new DataSet();
myDataAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[];
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
conn.Close();
}
client.Disconnect();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
Note: If an error occurs, you can stop the MySql service on the local (development machine).
Required dll: SSHDLL.rar
You can fill in the following information to configure the connection to the MySql database.
Server name: Enter the IP address of MySQL, which is 127.0.0.1 as seen in your SSL connection information.
User name: Enter the user name of Mysql
Password: Enter the password of Mysql
Database name: Enter a test database
Hope it can help you

SQL Connection fails (timeout) but works in classic VB6

I am converting a VB6 app to .NET
The VB6 app connects to a MS SQL Server fine and always has via an ADODB Connection. I set it up using a connection string.
The SQL Server is on the network, it is not on the local machine.
When I try to connect using the same connection string in .NET (VB or C#) I get a "timeout expired" error. I return to my VB6 app and it connects up just fine.
I am not able to amend the network set up as it is not my network.
The C# code I am using is below:
using System;
using System.Data;
using System.Data.SqlClient;
namespace CommandLineApp
{
public class ConnectionDemo
{
public static void Main(string [] args)
{
SqlConnection myConnection = new SqlConnection
(
#"Data Source=192.168.0.5;" +
"Initial Catalog=mydb;" +
"User Id=myid;" +
"Password=mypass;"
);
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I have tried all sorts of different things in the connection string including using the server name, using "tcp:,port".
Interestingly enough I am not able to ping the server on IPv6 ("ping -6 ")
I remind you that I am unable to make changes to the network as it is not mine however the VB6 code works just fine. Same connection string. So I don't see why I should have to alter the network.
Thanks in advance.
Try
OleDbConnection myConnection = new OleDbConnection("Provider=SQLOLEDB; " +
"Data Source=192.168.0.5; " +
"Initial Catalog=mydb; " +
"User Id=myid; " +
"Password=mypass; ");

C# project on VMWare and the database is outside of VMWare

I have a C# project on VMWare and my database is outside of VMWare. It's on my real PC and the VMWare is on the same PC. My question is how can I access my database on my PC ? I have this class but it does not work.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace EyeCareCenter
{
class DataBase
{
private string connectionstring = #"Data Source =127.0.0.1,1433 ; Network Library=DBMSSOCN ;Initial Catalog=EyeCareCenter ; Trusted_Connection=True ";
private SqlConnection connection = new SqlConnection();
public void OpenConnection()
{
try
{
connection.ConnectionString = connectionstring ;
connection.Open();
// MessageBox.Show (" Connection successfull ... ");
}
catch ( Exception a)
{
MessageBox.Show(a.Message + " ");
}
}
public void CloseConnection()
{
connection.Close();
}
public SqlConnection GetConnection()
{
return connection;
}
}
}
At a minimum, your connection string is trying to connect to database inside your VM, not on host machine:
private string connectionstring = #"Data Source =127.0.0.1,1433 ; Network Library=DBMSSOCN ;Initial Catalog=EyeCareCenter ; Trusted_Connection=True ";
The IP should be changed to that of your host machine to connect to it. And make sure that your VM is configured for networking, and that networking configuration allows for connecting to your host machine.

C#: annoying mistake during making back up of sql database

I am trying to make my application which have aim to make backup of database on disk and also send it through ftp or mail.
So I made a research and finally I wrote project of Windows service and another project in console which is making a backup of database. Both are working well and both are written in the same Visual Studio but when I am trying to put code of making backups in Windows service it doesn't work. I can't understand why. I tried put code instead of example (which is creating a file and writing one line there and this part is working well) and I even tried to make another method to do it and then call this method.
Windows service is completely the same as here and in the SpadesAdminService class instead of
System.Diagnostics.EventLog.WriteEntry("SpadesAdminSvc",
ServiceName + "::Execute()");
I made this code (is working well - making an empty file on my disk every 5 seconds, should be written "text to file" but files are appearing !):
using (FileStream fs = File.OpenWrite("C:\\place\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
{
Byte[] napis = new UTF8Encoding(true).GetBytes("text to files"));
fs.Write(napis, 0, napis.Length);
}
My class of making back up (alone is also working well):
namespace makeBackUpConsole
{
class Program
{
static void Main(string[] args)
{
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
}
}
}
I am copying this class instead of my code to making txt files and Windows Service is not working. Here is a code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace toni.exampleService.Services
{
public class exampleAdminService : exampleServiceBase
{
public exampleAdminService()
{
this.ServiceName = "exampleAdminSvc";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override int Execute()
{
//using (FileStream fs = File.OpenWrite("C:\\development\\toni\\dd\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
//{
// Byte[] napis = new UTF8Encoding(true).GetBytes("DzieƄ i godzina: " + DateTime.Now.ToString("ddMMyyyy_HHmmss"));
// fs.Write(napis, 0, napis.Length);
//}
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
return 0;
}
}
}
Of course all libraries as well linked.
Looking for any advice, please help me.
Thank you in advance and have a nice day.
edit:
Hey, problem solved.
I created a database account (not Windows account) in sql management studio and I putted this account User Id and Password directly into my code in C# in Windows Service.
Anyway maybe somebody will use my code :)
Thanks for reply.
Have you checked that a Windows Service has permissions to write a file in the location you are specifying. Services don't necessarily run as a user, so don't assume that where you can write a file your service can too.
Have you tried writing to a folder underneath c:\ProgramData?
If you don't know precisely what the problem is then you need to find out. Try adding System.Diagnostics.Debugger.Launch(); at service startup and then track the changes inside the debugger.
The Windows Service you have programmed is using "Integrated Security" for your SQL Server.
If you don't want to enter login credentials in your code, you should either set the executing user to your local account or grant the required user (e.g. LocalSystem) access to your database in your SQL Management Studio.
Usually a Windows Service is running as LocalSystem, LocalService or NetworkService. Just change the setting for your Windows Service in services.msc

.NET and sql server database link

I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.

Categories

Resources