Unable to read data from data layer - c#

I was doing a basic example of 3 tier architecture in c#.I created two dll's for data and business layer.Also I am using data layer dll in business layer code.And,business dll and data access dll in presentation layer(which is a winform application).Now,when the presentation layer code is being executed,an exception is coming which says :
Database
'D:\11feb\practice\3tier\PresentationLayer\PresentationLayer\bin\Debug\Data.mdf'
do not exists.
I had created my database Data.mdf in data layer.
I copied the database files to the location mentioned in exception and the application successfully got executed.But I want the database to be accessed from my data layer.
Data Layer Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DataAccessLayer
{
public class DataAccess
{
public DataTable dataRead()
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data.mdf;Database=Data;Integrated Security=True;User Instance=True");
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("select ID,Name from datatable", con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}
}
Business Layer Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer;
using System.Data;
namespace BusinessLogicLayer
{
public class BusinessLogic
{
DataAccess dataAccess = new DataAccess();
public DataTable getPersons()
{
try
{
return dataAccess.dataRead();
}
catch { throw; }
}
}
}
Presentation Layer Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessLogicLayer;
namespace PresentationLayer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
BusinessLogic BusinessLogic = new BusinessLogic();
this.dataGridView1.DataSource = BusinessLogic.getPersons();
}
catch
{
MessageBox.Show("Error Occurred");
}
}
}
}

The problem is that you have added Data.mdf in the solution but when the application runs, it tries to find out the mdf file in the bin directory. Click on Data.mdf file in the solution. Go to its properties ( By Pressing F4) and then look out for the property "Copy to the Output Directory" and then change the value to Copy Always.
Also check out your connection string.

Related

C# Connecting to MySql DB through android device

I've just working with c# and mysql and have ran into a problem. I've created a mysql db(remote access) using mysql workbench. I've been using visual studio to write the code(c#), xamarin.forms. The aim is to connect the database on multiple platforms. I'm trying to make it connect through windows(uwp) and android, it works fine on the windows(uwp). However when I try and run it through my android device to test the app I get an error. The error states "SYSTEM.TYPEINITIALIZATIONEXCEPTION......OPERATION IS NOT SUPPORTED ON THIS PLATFORM". Any idea on how to get around this? Thank you.
This is the code:
'''
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using MySql.Data.MySqlClient;
using System.Data;
namespace demo {
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
void Button_Clicked(object sender, EventArgs a)
{
MySqlConnection con = new MySqlConnection(user id; password);
try
{
con.Open();
if (con.State == ConnectionState.Open)
{
((Button)sender).Text = $"Connected";
}
}
catch (Exception ex)
{
((Button)sender).Text = ex.ToString();
}
con.Close();
}
}
}

Error when trying to connect to access database in C# for project

I am trying to create a project that will read, write,and check for duplicates in my access data base file. I am using C# and keep getting "Connection failed error that I have written into the program if the connection state = 0. If anyone can offer any help I would appreciate it. I am using Access 2016 and I am not sure what references I need for my project (if any). Everything I have found online is either outdated or doesn't work.
Thank you!
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.Threading;
using System.Net;
using System.IO;
using System.Data.OleDb;
namespace RHG
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
{
try
{
connection.Open();
MessageBox.Show("connected");
}
catch (Exception ex)
{
MessageBox.Show("connection failed");
}
}
}
`
You have not opened the connection.
connection.Open();
Note: Checking the connection state is not enough. You might get an exception when trying to open the connection. Enclose it in try-catch instead.
It is also a good practice to enclose work on a connection with using
using (var connection = new OleDbConnection()) {
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\...\Used.accdb";
try {
connection.Open();
//TODO: do something with the connection
} catch (Exception ex) {
MessageBox.Show("Connection Failed\r\n\r\n" + ex.Message);
}
}
This ensures that the connection will be closed and the resources be released.
Try following the examples here: https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbconnection(v=vs.110).aspx
You're missing the connection.Open(); statement, which should be wrapped in a try catch.
Additionally, you can specify the connection string within the constructor, like
using (OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\grosales\Documents\rhg\RHG\Used.accdb"))
{
//do DB access here
}
//no need to call connection.Close() - it's automatically done once you leave the using block.

Simple C# connection to .accdb file

All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
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.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated
When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.
label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null

How do I use C# queries on a prexisting database(SQLite database)?

I have run into a problem where my C# code is creating a whole new database instead of using a preexisting one. Then my program runs into errors where the program cannot find the table to insert the information even though the preexisting database has the table because the code itself is looking at the new table. Here 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 Finisar.SQLite;
namespace WestSlope
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SQLiteConnection sqlite_conn;
SQLiteCommand sqlite_cmd;
//SQLiteDataAdapter sqlite_datareader;
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=True;Compress=True;");
//open conection
sqlite_conn.Open();
//create sql commands
sqlite_cmd = sqlite_conn.CreateCommand();
//Let SQLite command know query is known
sqlite_cmd.CommandText = "INSERT INTO ASAM (ASAMone, ASAMtwo, ASAMthree, ASAMfour, ASAMLim, ASAMLimEX) VALUES ('Had to call', 'Reffered', 'Had to call', 'Watched', 1 , 'Injured legs');"
;
//execute query
sqlite_cmd.ExecuteNonQuery();
sqlite_conn.Close();
}
}
}
What the code is supposed to do is when the user presses a button the program will save information to the preexisting database; but, as you can see the program is making a new database instead of using the preexisting one.
Use new=false in your connection string to use existing database file.
Following should be the connection string:
sqlite_conn = new SQLiteConnection("DataSource=ClientLogDB.db;Version=3;New=False;Compress=True;");

C# - Read from excel sheet and pass variables into function

I'm basically looking for some ideas as to the best way of constructing code to read an excel file and create user accounts.
I already have the code to both read the excel file and create the accounts, however I'm unsure as to the best way of passing the data from the excel sheet into the "CreateUser" function.
Any help is appreciated.
Cheers.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
namespace INB201_SAMS.Admin
{
public partial class UploadList : System.Web.UI.Page
{
protected void UploadButton_Click(object sender, EventArgs e)
{
var upload = Path.Combine(Server.MapPath("~/upload"), "myfilename.xlsx");
CSVUpload.SaveAs(upload);
var excelConString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", upload);
using (OleDbConnection con = new OleDbConnection(excelConString))
{
con.Open();
OleDbCommand com = new OleDbCommand("Select * from [UserUpload$]", con);
OleDbDataReader dr = com.ExecuteReader();
}
File.Delete(upload);
Response.Write("Upload Successfull!");
}
protected bool CreateUser(string UsersUsername, string UsersPassword)
{
try
{
MembershipUser newUser = System.Web.Security.Membership.CreateUser(UsersUsername, UsersPassword);
Roles.AddUserToRole(UsersUsername, "student");
return true;
}
catch (Exception ex)
{
MessageYo.Text = ex.ToString();
return false;
}
}
}
}
Here's something real simple:
while(dr.Read()) {
string user = dr[0].ToString();
string pass = dr[1].ToString();
if(!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
CreateUser(user, pass)
}
dr.Close()
I assume that your username and userpassword are in two column. In that case. you can Read a Specific Column of Excel by its specific headers. This is the discussion of this: http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/6506b0b1-be8c-40f9-879f-21715bd2792e. Then you can pass the values to the function.
A workaround for this: go through XML file which means convert Excel to XML, and then get data from xml to function.

Categories

Resources