C# Configuration Manager Connection String - c#

So I am trying to do an application that makes a simple transaction from account 1 to account 2
here is the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Transactions;
namespace BankTransactions
{
public class Transactions
{
public bool Transfer(int fromAcno, int toAcno, decimal amt)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
cn.Open();
SqlTransaction trans;
trans = cn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("update PSBank set amount=amount+{0} where accountno={1}", amt, toAcno);
cmd.ExecuteNonQuery();
cmd.CommandText = String.Format("update PSBank set amount=amount-{0} where accountno={1}", amt, fromAcno);
cmd.ExecuteNonQuery();
decimal balance;
balance = (decimal)cmd.ExecuteScalar();
decimal originalBalance;
originalBalance = balance - amt;
bool flag = true;
if (originalBalance >= 5000)
{
trans.Commit();
flag = true;
}
else
{
trans.Rollback();
flag = false;
}
cn.Close();
return flag;
}
catch (Exception ex)
{
return false;
}
}
}
}
and here is the winform code
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;
using BankTransactions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int fromAcno = int.Parse(txtFromAcno.Text);
int toAcno = int.Parse(txtToAcno.Text);
decimal amount = decimal.Parse(txtAmount.Text);
Transactions obj = new Transactions();
if (obj.Transfer(fromAcno, toAcno, amount) ==true)
{
MessageBox.Show("Amount transferred succesfully!", "Confirm");
}
else
{
MessageBox.Show("Error!", "Error");
}
}
}
}
The form has 3 text boxes: txtFromAcno, txtToAcno and txtAmount.
I have the database called NORTHWND with the table PSBank where I have these two accounts.
I am getting the error message, not "amount transferred successfully". I am not sure how to make the connection to the DB in the connection string.
string cs = ConfigurationManager.ConnectionStrings["Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"].ConnectionString;
How do I format it properly?

Put the connection string in app.config like so:
<connectionStrings>
<add name="MyConnection"
connectionString="Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = NORTHWND; Data Source = CRISTI"
providerName="System.Data.SqlClient" >
</connectionStrings>
And then reference it by name in code:
string cs = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

Related

Adding product to table cart with trigger in c# (it wont close automatically )

When I try to enter quantity to add to table cart in my pos form it wont accept or close accepting values after I enter them. the quantity should be updated in the cart table listing all the details but nothing happens after I enter the quantity in the pop up when the barcode is scanned I need your support guys...
`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;
using System.Data.SqlClient;
namespace POSsystem
{
public partial class frmQty : Form
{
//code to connect sql database
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
DBConnection dbcon = new DBConnection();
SqlDataReader dr;
private String pcode;
private double price;
private string transno;
string stitle = "Simple POS System";
frmPOS fpos;
public frmQty(frmPOS frmpos)
{
InitializeComponent();
cn = new SqlConnection(dbcon.MyConnection());
fpos = frmpos;
}
private void frmQty_Load(object sender, EventArgs e)
{
}
public void ProductDetails(String pcode, double price, String transno)
{
this.pcode = pcode;
this.price = price;
this.transno = transno;
}
private void frmQty_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar == 13) && (txtQty.Text != String.Empty))
{
cn.Open();
cm = new SqlCommand("insert into tblcart (transno, pcode, price, qty,
sdate)values(#transno, #pcode, #price, #qty, #sdate", cn);
cm.Parameters.AddWithValue("#transno", transno);
cm.Parameters.AddWithValue("#pcode", pcode);
cm.Parameters.AddWithValue("#price", price);
cm.Parameters.AddWithValue("#qty", int.Parse(txtQty.Text));
cm.Parameters.AddWithValue("#sdate", DateTime.Now);
cm.ExecuteNonQuery();
fpos.txtSearch.Clear();
fpos.txtSearch.Focus();
this.Dispose();
}
}
}
}
`

How to save data to Service-based Database in Visual Studio

I have a local Db named NumLeter.mdf whit two tables: LeterTb and NumberTb. I want to insert in NumberTb new values, when the application is running the new values that I inserted show to me correctly as if they had been inserted, but when close the application and clic in Show Table Data the new data was not added in the table. I have instaled EntityFramework v:6.1.3. This is my code:
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;
using System.Data.SqlClient;
namespace LearningVS
{
public partial class Form1 : Form
{
SqlConnection conexion;
public Form1()
{
InitializeComponent();
conexion = cConexion.getConexion();
}
private void btInsertNum_Click(object sender, EventArgs e)
{
insertNumber();
}
public void insertNumber()
{
SqlCommand command = new SqlCommand();
command.Connection = conexion;
command.CommandText = "INSERT INTO NumberTb(numberA, numberB, numberC) VALUES(#numberA, #numberB, #numberC)";
command.Parameters.Add("numberA", SqlDbType.Int, 3).Value = this.txNumberA.Text;
command.Parameters.Add("numberB", SqlDbType.Int, 3).Value = this.txNumberB.Text;
command.Parameters.Add("numberC", SqlDbType.Int, 3).Value = this.txNumberC.Text;
command.ExecuteNonQuery();
//testing this either
/*SqlDataAdapter datAdapt = new SqlDataAdapter(command);
NumLeterDataSet dtSet = new NumLeterDataSet();
datAdapt.FillSchema(dtSet, SchemaType.Source, "NumberTb");
datAdapt.Fill(dtSet, "NumberTb");
datAdapt.Update(dtSet.NumberTb);*/
}
//Also I tried by creating ADO.NET Entity Data Model whit the same result
private void button1_Click(object sender, EventArgs e)
{
using (var db = new NumDbModel())
{
var numbers = new NumberTb()
{
numberA = 22,
numberB = 33,
numberC = 44,
};
db.NumberTBs.Add(numbers);
db.SaveChanges();
}
}
}}
this is where I handle the connection
namespace LearningVS
{
class cConexion
{
private static SqlConnection conexion;
public static SqlConnection getConexion()
{
if (conexion != null)
{
return conexion;
}
conexion = new SqlConnection(Properties.Settings.Default.NumLetersConnectionString);
try
{
conexion.Open();
return conexion;
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error de conexión" + e.Message);
return null;
}
}
public static void cerrarConexion()
{
if (conexion != null)
{
conexion.Close();
}
}
}}

c# : How to get data from database and pass to another form?

I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
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 EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}

Import All Access Table Data Into SQL Server Table

I am needing to take all of my access tables and create the exact same table in SQL Server 2008 with data and keys/constraints. The below syntax will insert data if the table already exists, but how do I do it if the table does not exist? Or is there a better method programmatic ally in play to already achieve this result?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccessToSQL
{
public partial class Form1 : Form
{
const string databaselocation = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
List<string> tables = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetTableNames();
const string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
const string connectionStringDest = "Data Source = TO\\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=SSPI;";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
foreach (string tbl in tables)
{
var commandSourceData = new OleDbCommand("Select * from "+tbl, sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = "dbo."+tbl;
try { bulkCopy.WriteToServer(reader); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { reader.Close(); }
}
}
}
}
}
public List<string> GetTableNames()
{
try {
using (OleDbConnection con = new OleDbConnection(databaselocation))
{
con.Open();
//DataTable schema = con.GetSchema("Columns");
//foreach (DataRow row in schema.Rows)
//{
// tables.Add(row.Field<string>("TABLE_NAME"));
//}
foreach (DataRow r in con.GetSchema("Tables").Select("TABLE_TYPE = 'TABLE'"))
{
tables.Add(r["TABLE_NAME"].ToString());
}
return tables;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
return tables;
}
}
}

how to add database content to an asp.net page

Hey I'm trying to add database info into my webpage. This is the code I am trying.
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
namespace DatabaseAddDemo
{
public partial class Content : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
try
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=officedev1;Initial Catalog=TestDatabase;User ID=sa;Password=Password11;pooling='true';Connect Timeout=3000; Max Pool Size=200;MultipleActiveResultSets='true'");
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table where #ID = #key", sqlConn);
string key = Request.QueryString["keys"].ToString();
contentLiteral.Text = key;
cmdPreWork.Parameters.Add("#Information", SqlDbType.Char).Value = key;
Console.WriteLine(contentLiteral);
SqlDataAdapter daPreWork = new SqlDataAdapter(cmdPreWork);
DataTable dtPreWork = new DataTable();
daPreWork.Fill(dtPreWork);
Grid.DataSource = dtPreWork;
Grid.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Could not open connection";
}
}
}
}
}
Whenever I try to display the information, I get the lblError text, telling me I could not open the connection. I'm not sure what to do. Please help.
You should be able to DEBUG this as stated in the comments. But in your code your select query expects a [Key] parameter and you are passing a [Information] parameter.
Change it as below:
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table
where #ID = #key", sqlConn);
cmdPreWork.Parameters.Add("#key", SqlDbType.Char).Value = key;

Categories