Console Application program to export data from SP - c#

It's my first time to work with c# and I have a task to create a simple Console Application where you simply just click the program button created in the debug file and then export an amount data from the Stored Precedure I created in the database to an Excel file.
My Methode looks like this :
static void Main(string[] args)
{
string path = #"\Users\sa\mydocuments\test.xls";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
//creating the file contents
}
}
using (StreamWriter sw = File.CreateText(path))
{
SqlConnection cn = new SqlConnection("Data Source=server1234;Initial Catalog=MySqlDatabase;Integrated Security=True;Trusted_Connection=True");
SqlCommand cmd = new SqlCommand("MySqlDataBase.dbo.sp_export_data", cn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
sw.WriteLine(dr["name"].ToString() + "\t" + dr["size"].ToString());
}
Console.WriteLine("Database has been exported.");
}
catch (Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
My program runs and creates an excel file, the problem is it's empty and I have no idea if my code is wrong because im not getting any errors. Not sure if im missing anything in my connectionString etc.
Maybe someone could help me out with this or link to how create an export function for Console Application with stored precedures.

In order to write to Excel files, you'll need to use an Excel library (either the Microsoft Library or a 3rd party).
See here - Creating xls/xlsx files in c#

Related

Non-terminating program when trying to read and write from Microsoft Access database with C#

I am trying to read from a Microsoft Access database with C# with the below code.
static void getProducts()
{
string accessDBPath = #"C:\Users\...\dummydb.accdb";
string connectionString = #"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + accessDBPath;
string strSQL = "SELECT * FROM Products";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand(strSQL, connection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("product name = ...");
}
}
}
catch (OleDbException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Finished");
}
}
I'm able to walk through the products table just fine (i.e., the stuff inside the while(reader.Read()){...} prints as expected), and the finally block prints as expected as well.
But after the function is done running, the program just never terminates, and the command line just freezes. When I try to force the program to quit at the end of my Main function with Environment.Exit(0);, I get hit with this error:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
The using clause should have automatically closed the database connection when I'm finished with it, but it seemingly behaves as if I hadn't, so I have no clue what's going on, and would appreciate any help.
EDIT: Copy-paste error, declared a variable twice.

External Table not in expected format open xml

I am trying to upload an excel(.xlsx) file in my application which has been created by the same application via open xml sdk. I am facing the exception 'External table not in expected format'. However if i manually open the file and save it and try again, it is uploaded without any errors.
Is there any way to programatically perform the task of opening the excel file and save ? I cannot ask my user/client to follow this workaround. Any leads would be helpful. Below is the code snippet which is throwing the exception. The line 'con.open()' is throwing the mentioned exception. Please find the connection string used
private readonly string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=Yes;MAXSCANROWS=0;IMEX=1\";";
public DataTable GetSheetData(string sheetName)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.filePath);
DataTable excelData = new DataTable();
excelData.Locale = CultureInfo.InvariantCulture;
using (OleDbConnection con = new OleDbConnection(string.Format(CultureInfo.CurrentCulture, this.connectionString, this.filePath)))
{
con.Open();
if (!string.IsNullOrEmpty(sheetName))
{
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(string.Format(CultureInfo.CurrentCulture, "select * from [{0}$]", sheetName), con))
{
dataAdapter.Fill(excelData);
}
}
}
return excelData;
}
I figured out a workaround by programatically opening the excel file and saving it by Interop. Now I am able to upload the excel file without any errors.
var ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = ExcelApp.Workbooks.Open(filePath);
workbook.Save();
workbook.Close();
ExcelApp.Quit();

SQLite database file corruption in Unity

Hi I am using SQLite as database in my Unity project. For some reason database file got corrupted but luckily I had backup so I didn't lose anything. I think the reason behind corruption was using unity collab to share database file. My question is what can I do not to corrupt the file again? Also can it corrupt after releasing the game in player's local gamefiles?
And here is the static methods i am using to execute commands, maybe something is wrong with it.
public static void Execute(string command, ref DataTable datatable)
{
string dbPath = ("Data Source=" + Application.dataPath + "/database.s3db");
using (SqliteConnection cnt = new SqliteConnection(dbPath))
{
using (SqliteCommand cmd = new SqliteCommand(command, cnt))
{
using (SqliteDataAdapter adapter = new SqliteDataAdapter(cmd))
{
adapter.Fill(datatable);
}
}
}
}
public static void Execute(string command)
{
string dbPath = ("Data Source=" + Application.dataPath + "/database.s3db");
using (SqliteConnection cnt = new SqliteConnection(dbPath))
{
using (SqliteCommand cmd = new SqliteCommand(command, cnt))
{
cnt.Open();
cmd.ExecuteNonQuery();
cnt.Close();
}
}
}
SQLite implements atomic transactions, but those guarantees hold only as long as the database file is accessed only through the SQLite library.
In your case, it's likely that the database file was copied from your friend's computer in the middle of a transaction, i.e., some changes did not end up in the published version. The only way to avoid this is to ensure that no files are currently being modified when doing the publishing.

how to read an excel file which has no path

I've been using this code to read an excel file and it works fine when i am trying to read saved excel files
string con = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\temp\test.xls;" + #"Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]",
connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
var row1Col0 = dr[0];
Console.WriteLine(row1Col0);
}
}
}
theres and application which opens an excel file which updates data every second and here is the pic of the app
here you can see the excel file being opened in the taskbar.when i used the process code to read the path of the excel file using this code i get no data as the file located in that path is empty
Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
if (theprocess.ProcessName == "EXCEL")
{
Console.WriteLine(theprocess.ProcessName, theprocess.Id);
string fullPath = theprocess.MainModule.FileName;
//fullpath = C:\\Program Files (x86)\\Microsoft Office\\Office12\\EXCEL.EXE
}
}
the application might be using the instance of ms excel directly.is there any alternative step to read this excel file by the process id directly instead of the path?
Thanks in advance.
Processes are not meant to be used this way. You can start, stop and kill a Process, but there is no way to gain access to it's memory and read a file (actually, any stream of data) with it. I also don't think that there is a way to access the path of the opened file by the Process class.
However, using the Office Interop COM API, you can get the current file, including it's path with Application.ActiveWorkbook.FullName.
Be advised, that this solution works only if one instance of Excel is opened.
Microsoft.Office.Interop.Excel.Application MyExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
string FullPath = MyExceAppl.ActiveWorkbook.FullName;

Accessing folder in console application

I'm trying to write a function to read csv contents into a datatable.
I'm getting an exception about the file path and wondering what it is that I'm doing wrong.
All I did was create the console app and create a folder in the project called 'Data'.
public DataTable ReadCSV(string filename)
{
DataTable dt = new DataTable();
string sql = "SELECT * FROM " + filename;
string path = "Data\\";
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";" + "Extended Properties='text;FMT=Delimited(;);HDR=YES'";
OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connstring);
System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
try
{
conn.Open();
da.Fill(dt);
}
catch (Exception ex)
{
Console.WriteLine(filename + "not found");
}
finally
{
conn.Close();
}
return dt;
}
}
My connection string in the Text visualizer when I run in debug mode:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\Positions.csv;Extended Properties='text;FMT=Delimited(;);HDR=YES'
I'm getting an exception
base {System.Data.Common.DbException} = {"'Data\Positions.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides."}
Can anyone point me in the right direction? I have limited experience doing console apps so it's probably some formatting mistake that I've made. Thanks
and create a folder in the project called 'Data'.
That doesn't work. Your program is running in the bin\Debug subdirectory of your project. It doesn't have a Data subdirectory. You'd have to use ..\..\Data\Positions.csv to find that file.
Well, that would solve your problem right now but it isn't going to be useful once you copy your program to another machine. There won't be a ..\..\Data directory there. Think about ways that your user is going to tell you where the .csv file is located. A GUI with OpenFileDialog is the friendly way but not very compatible with a console app. The standard way for that is to pass command line arguments. Environment.CommandLine. Not very compatible with the typical user. You'll have to weigh these options by yourself.

Categories