The Microsoft Access database engine cannot open or write to the file - vb.net

I have the following function:
Public Function OleDBCSVToDataTable(directory As String, tableName As String, fileName As String, Optional start As Long = 0) As DataTable
Dim CnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & directory & ";Extended Properties='Excel 8.0;HDR=YES'"
Dim dt As DataTable = GetTableSchema(tableName)
Using Adp As New OleDbDataAdapter("select * from [" & fileName & "]", CnStr)
Adp.Fill(start, 1000, dt)
End Using
Return dt
End Function
The function is designed to read a CSV into a data table using OLEDB for import into SQL, however I am receiving this error:
"The Microsoft Access database engine cannot open or write to the file
'C:\TEST'. It is already opened exclusively by another user, or you
need permission to view and write its data."
I have attempted this solution. All permissions have been granted (permissions are Full Control across users):
I have seen this solution as well, however, the proposed options other than OLEDB are solutions that don't seem to work with CSV. Besides, I imagine there are native libraries.
I am open to suggestions for better ways to accomplish this, however, based on requirements - large CSVs, data validation - this appears to be the best, assuming I am able to get it working.

How about importing the CSV file into a DataGridView, and then exporting from that object into MS Access?
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 System.IO;
using System.Globalization;
using System.Configuration;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string delimiter = ",";
string tablename = "medTable";
DataSet dataset = new DataSet();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
filename = openFileDialog1.FileName;
StreamReader sr = new StreamReader(filename);
string csv = File.ReadAllText(openFileDialog1.FileName);
dataset.Tables.Add(tablename);
dataset.Tables[tablename].Columns.Add("Order ID");
dataset.Tables[tablename].Columns.Add("Product");
dataset.Tables[tablename].Columns.Add("Unit Price");
dataset.Tables[tablename].Columns.Add("Quantity");
dataset.Tables[tablename].Columns.Add("Discount");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tablename].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
}
else
{
this.Close();
}
}
}
public string filename { get; set; }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Import_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
//remove the semicolon, and add brackets below after line
{
//create the connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Ryan\\Desktop\\Coding\\Microsoft Access\\Northwind_2012.mdb";
//create the database query
string query = "SELECT * FROM [OrderDetailsTest]";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
DataGridView dataGridView1 = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// An update function to get the changes back into the database.
dAdapter.Update(dTable);
}
}
}

Related

How do I define a data source for a panel?

I was trying to display a table that is being saved in my sql server and I wanted it to be displayed in my panal but it kept showing this error saying 'panel' doesnot contain a definition for 'Datasource' and no extension method 'datasource' accepting a first argument of type 'panel' could be found (are you missing a using directive or an assembly reference?) please help..
public partial class Form17 : Form
{
public Form17()
{
InitializeComponent();
ShowTGBtbl();
}
private void button5_Click(object sender, EventArgs e)
{
}
private void Form17_Load(object sender, EventArgs e)
{
int w = Screen.PrimaryScreen.Bounds.Width;
int h = Screen.PrimaryScreen.Bounds.Height;
this.Location = new Point(0, 0);
this.Size = new Size(w, h);
}
SqlConnection Con = new SqlConnection(#"Data Source=LAPTOP-9514GUKU\SQLEXPRESS;Initial Catalog=Mydatabase.com;Integrated Security=True");
private void ShowTGBtbl()
{
Con.Open();
string Query = "select * from TGBtbl";
SqlDataAdapter sda = new SqlDataAdapter(Query, Con);
SqlCommandBuilder Builder = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
TGBoverall.Datasource = ds.Tables[0];
Con.Close();
}

export table sql to .txt with c#

I think I have a fairly simple question. I just need to know how to export fields from a table in an sql database using either asp.net or C#? Anyway to do this would be good.
I suppose I am looking for something like this, but perhaps simpler:
Export values from SQL Server to txt file
Whatever the case, I am trying to get values from a database to a .txt, like by pressing a button in asp.net or C#, based on criteria (like between certain dates, from a date field, or starting at a certain date with a certain user, and exporting a certain number of them). Any suggestions would help.
If I used the following code, what would I need to change so that if I wanted to select a certain column, like Note, in the database, and Date column, what would I need to do?
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.SqlClient;
public partial class ExportText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYLearningConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tblUsers", conn);
DataSet ds = new DataSet();
da.Fill(ds);
ExportToText(ds.Tables[0], "DataTable");
}
protected void ExportToText(DataTable dataTable, string fileName)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dataTable.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
context.Response.End();
}
}

I get an error in my code

I got an error
Incorrect syntax near '.'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Threading;
namespace Cloths_Inventory
{
public partial class frmBackup : Form
{
//DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);
//private static Server srvr;
//private string DBpath = Application.StartupPath;
public frmBackup()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;
if (Directory.Exists(#"D:\SQLBackup"))
{
if (File.Exists(#"D:\SQLBackup\wcBackUp1.bak"))
{
if (MessageBox.Show(#"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Delete(#"D:\SQLBackup\wcBackUp1.bak");
}
else
bBackUpStatus = false;
}
}
else
Directory.CreateDirectory(#"D:\SQLBackup");
if (bBackUpStatus)
{
//Connect to DB
SqlConnection connect;
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Garment.mdf;Integrated Security=True;Asynchronous Processing= True ;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
//Execute SQL---------------
SqlCommand command;
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:Garment.bak' with init,stats=10", connect);
command.ExecuteNonQuery();
//--------------
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
You cannot use the AttachDbFileName= approach and then use a server-based command like backup database....
If you want to back up your SQL Server database, it has to be attached to the server, and you need to connect to the server and issue that command:
// Connect to "master" database
string con = #"server=.\SQLEXPRESS;database=master;Integrated Security=True;";
SqlConnection connect = new SqlConnection(con);
SqlCommand ommand = new SqlCommand(#"backup database Garment to disk = N'E:\Garment.bak' with init,stats=10", connect);
connect.Open();
command.ExecuteNonQuery();
connect.Close();
You are missing a backslash E:Garment.bak should be E:\Garment.bak
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:\Garment.bak' with init,stats=10", connect);

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection

Web Crystal reports produce Database logon failed

I developed a Crystal report on my local machine and I can render the report on my local website using .ExportToHttpResponse but as soon as I move my code to the production server I get a "Database logon failed" error. I basically used a .XML dataset file as the source to develop the report locally. This was my code:
I call a method to render the report:
private void RenderCrystalReports(string rptName, string pdfReportName, DataSet dataForReport)
{
string reportPath = Server.MapPath(#"\App_Data\Reports\" + rptName);
ReportDocument report = new ReportDocument();
report.Load(reportPath, OpenReportMethod.OpenReportByTempCopy);
SetDBLogonForReport(ref report);
report.SetDataSource(dataForReport);
SetDBLogonForReport(ref report);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, true, pdfReportName);
}
and to get the dataset I have:
private DataSet GetReportData(DateTime from, DateTime to, int userID, bool totalsOnly)
{
DataTable Job = _reportRepository.GetAccountHistoryJob(from, to, userID, totalsOnly);
Job.TableName = "Accounts";
DataSet ds = new DataSet("AccountsDS");
ds.Tables.AddRange(new DataTable[] { Job });
return ds;
}
and as far as I am concerned the method below is what is supposed to help me to connect to the remote SQL server:
private void SetDBLogonForReport(ref ReportDocument reportDocument)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString());
ConnectionInfo connectionInfo = new ConnectionInfo();
connectionInfo.DatabaseName = builder.InitialCatalog;
connectionInfo.UserID = builder.UserID;
connectionInfo.Password = builder.Password;
connectionInfo.ServerName = builder.DataSource;
Tables tables = reportDocument.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table table in tables)
{
TableLogOnInfo tableLogonInfo = table.LogOnInfo;
tableLogonInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(tableLogonInfo);
}
}
Why does this not work? I just figured out that even locally the .xml dataset is used so how do I use the sql dataset that I get?
This is the code that worked for me:
public ActionResult TestReport() {
RenderCrystalReports("demoRPT.rpt", "Some Report", GetReportDs());
return View();
}
#region Private methods
private void RenderCrystalReports(string rptName, string pdfReportName, DataSet dataForReport)
{
string reportPath = Server.MapPath(#"\Reports\" + rptName);
ReportDocument report = new ReportDocument();
report.Load(reportPath, OpenReportMethod.OpenReportByTempCopy);
DataTable jobTable = GetReportTable();
report.Database.Tables[0].SetDataSource(jobTable);
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, System.Web.HttpContext.Current.Response, true, pdfReportName);
}
private DataTable GetReportTable()
{
DataTable Job = GetReportData();
Job.TableName = "Accounts";
return Job;
}
private DataSet GetReportDs()
{
DataTable Job = GetReportData();
Job.TableName = "Accounts";
DataSet ds = new DataSet("AccountsDS");
ds.Tables.AddRange(new DataTable[] { Job });
return ds;
}
private DataTable GetReportData()
{
DataTable table = new DataTable();
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(DateTime.Now);
return table;
}
#endregion