run windows form on another machine c#? - c#

Hi i'm new to this c# coding and i've created an application but it on shows up in task manager on another machine and just won run. I've googled and did all that it says with Net framework version and all.
I am thinking maybe it has something to do with my combo box using a file path to get to the external database.
Here is my code with the comcbox:
private void combox_txt_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=C:\Users\Chavoy\Documents\Dougie Company\Application Files\Douglas.Gas.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=0;READONLY=FALSE'");
using (OleDbConnection cn = new OleDbConnection(connectionString))
{
cn.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM [Cust$] WHERE CustomerName = '" + combox_txt.Text + "' ", cn);
OleDbDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
custid_txt.Text = reader["CustomerID"].ToString();
name_txt.Text = reader["CustomerName"].ToString();
tel_txt.Text = reader["TelephoneNumber"].ToString();
address_txt.Text = reader["Address"].ToString();
sizegas_txt.Text = reader["Size_of_Gas"].ToString();
}
}
}
As you can see my path contains my user name and such... but how can i get it to be the other machine username?

That's probably because Microsoft Access Database Engine is not installed on that machine.

Are you sure you have the right .NET framework installed on the computer?
If you are using Visual Studio, you can find the framework version by right clicking your project>Properties>Target Framework.

Related

OleDB SQL Errors

Probably the worst part about using Microsoft Access and SQL is trying to connect through the OLEDB connection. The code is on the one drive and has been working without issue but this morning it has came up with this error;
"System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'"
Previously I was able to change the CPU from any to x86 which sometimes seemed to fix the problem but now it is not. I am running System.Data.OleDb 7.0.0 which I have not changed since starting this protect.
using System.Data.OleDb;
using System.Data;
using System;
namespace LOGIN_TAKE_FIVE
{
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:/Users/kiera/LOGIN TAKE FIVE/bin/Debug/net6.0-windows/dbNumber2.accdb");
}
private void btnAdd_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
string encryptUser = EncryptString(tbUsername.Text);
string encryptPassword = EncryptString(tbPassword.Text);
string regSQL = "INSERT INTO Users ([Username], [Password]) VALUES ('" + encryptUser + "', '" + encryptPassword + "')";
cmd = new OleDbCommand(regSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
this code was working in full no less than 5 days ago so I am unsure what the problem is. Any help would be greatly appreciated.

Run C# application without SQL Server Management Studio installed

I have create a simple login application using the C#.net.
I have created database test in which I have created table called as login.
Table: Login contains:
create table login
(
name varchar(20),
pass varchar(20)
)
Here is the login button code which I have written in the C#.net:
private void BtnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=ServerName;Initial Catalog=test;Integrated Security=True";
con.Open();
SqlDataReader dr = null;
SqlCommand cmd = new SqlCommand("Select * from login", con);
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
if (textBox1.Text == dr[0].ToString() && textBox2.Text == dr[1].ToString())
{
count = count + 1;
}
else
{
count = count + 0;
}
}
if (count == 1)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Fail");
}
}
Note: The above example works fine for me if I installed the Visual Studio 2010 and SQL Server Management studio in a single machine.
But
I want to run the above application in the machine where only Visual Studio 2010 is installed not SQL Server Management Studio.
Is it possible?
Data Source=ServerName;Initial Catalog=test;Persist Security Info=True;User ID=YourUserId;Password=YourPassword
Also you have to instal .net framework on your local machine
The SqlClient types that you are using (SqlConnection, SqlDataReader, and so on) are defined in System.Data.dll (you can see this by going to the MSDN docs, the assembly is documented just above the big 'Syntax' heading') which is part of the .NET Framework. So as long as you have .NET Framework installed on a machine, you do not need any additional dependencies such as Visual Studio or SSMS.

using Service Based Database in VS2010 Ultimate

I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'

Connecting to Oracle Database through C#?

I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

How to Create an Excel File in C#; Office 2007; Win 7 64bit?

Previously my C# app used this command to create an Excel file:
try
{
//SELECT INTO command
string cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AccfilePath +
";Persist Security Info=False";
ConnOpen(cnStr);
using (connectionToDatabase)
{
//Give the Export Table (destination) a Name
//baseTblName = dt.TableName;
//Generate the SQL string to SELECT * INTO the NEW table in destination
string selectcmd = "SELECT * INTO [Excel 12.0;Database=c:\\"+ExfilePath+"]." + tblName + " FROM " + tblName;
using (OleDbCommand createCmd = new OleDbCommand(selectcmd, connectionToDatabase))
{
createCmd.ExecuteNonQuery();
}
ConnClose();
}
}
I have moved to Win 7 64 bit and the OleDbCommand now gives me a "Failure Creating File". I have gone so far as to make the user an Administrator because I assumed it was a security issue.
There is no problem with this Oledb command. I have been fighting 64bit issues all day and assumed there was. My file path had incorrect syntax; after I fixed that it worked as expected.

Categories