export in-memory sqlite in C# - c#

My Web Service are going to create in-memory sqlite from sql-server DB.
since i want my data not stored localy due to security restriction
im using in-memory method.
this my DB creator code :
public ActionResult Get()
{
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
{
try
{
var sqlAdapter = new SqlDataAdapter("SELECT ID,Code,Name FROM UserDB", connection);
DataTable table = new DataTable();
sqlAdapter.AcceptChangesDuringFill = false;
sqlAdapter.Fill(table);
var sqlliteconnection = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;");
sqlliteconnection.Open();
string sql = "create table UserDB(ID INTEGER,Code TEXT, Name TEXT)";
SQLiteCommand command = new SQLiteCommand(sql, sqlliteconnection);
command.ExecuteNonQuery();
var sqliteAdapter = new SQLiteDataAdapter("SELECT * FROM Kiosk", sqlliteconnection);
var cmdBuilder = new SQLiteCommandBuilder(sqliteAdapter);
sqliteAdapter.Update(table);
DataTable table_sqlite = new DataTable();
sqliteAdapter.Fill(table_sqlite);
}
catch (Exception ex)
{
}
}
return """My in-memory Database.3db """
}
now i want to to get copy of in-memory db when i call the get() ActionResult.

Related

SqlDataAdapter: Read varbinary max to display image using ASP.NET Core

I have a SQL Server table with a varbinary(max) column. I use it to store images in it.
VariantImage varbinary(MAX) Checked
Then an image is stored in the database using this code:
public async Task<IActionResult> PartVariant(PartVariant model, IFormFile files)
{
if (ModelState.IsValid)
{
DynamicParameters look = new DynamicParameters();
foreach (var file in Request.Form.Files)
{
MemoryStream ms = new MemoryStream();
file.CopyTo(ms);
model.VariantImage = ms.ToArray();
ms.Close();
ms.Dispose();
look.Add("#VariantImage", model.VariantImage);
}
string employee = _db.ExecuteReturnScalar<string>("usp_InsertPartVariant", look);
TempData["Success"] = " Part Variant Added Successfully!";
return RedirectToAction("PartVariant", "MasterViewData");
}
}
It looks like this stored in the database:
0xFFD8FFE000104A46494600010100000100010000FFDB0043000403030403030404040405050405070B07070606070E0A0A080B100E1111100E100F12141A16121318130F10161F171..........................etc
I am unable to load the images back from the datatable.
Controller and model class:
public IActionResult PartVariant()
{
Part_Bind();
viewLookup look = new viewLookup();
var model = look.GetPartVariant(_db, connectionString);
TempData["partVariant"] = model;
return View();
}
public List<PartVariant> GetPartVariant(IDapperORM _db, string connection)
{
SqlConnection conn = new SqlConnection(connection);
List<PartVariant> MasterList = new List<PartVariant>();
SqlCommand com = new SqlCommand("GetPartVariant", conn);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
conn.Close();
foreach (DataRow dr in dt.Rows)
{
MasterList.Add(
new PartVariant
{
VariantImage = (byte[])dr["VariantImage"],
}
);
}
return MasterList;
}
I'm getting this error:

How to copy Access table to SQL table in C#?

As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.

How do I return a table from a SQL query as a List in C#?

I have a Xamarin app that connects to a SQL Server (*), and I want to insert the data from the SQL Server's tables into a local SQLite database. My approach is to execute a query like
select * from Table1
retrieve the results of the query as a List, then insert that List into my SQLite table. That said I'm very new at using SqlClient, so please share if there are better ways to do this. Thanks.
Edit: the smallest number of columns these tables have is 5. Don't know if that disqualifies Lists as the best option.
My code:
private void LoadData()
{
string cs = #"connection string here";
using (SqlConnection sconn = new SqlConnection(cs))
{
sconn.Open();
SqlDataReader reader = null;
SqlCommand aml = new SqlCommand("select * from Table1");
reader = aml.ExecuteReader();
while (reader.Read())
{
// get result of query as List somehow?
}
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<Table1>();
if (conn.Query<Table1>("select * from Table1").Count() <= 0)
{
// insert the list object
}
}
}
}
(*) The app does not use a web service as the app is intended for onsite use only and will not be distributed publicly.
A better alternative way to do it more easier is to use a ORM like dapper
With the help of dapper, all you need to do is
using (var connection = new SqlConnection(_sqlConnectionString))
{
var results = connection.Query<YourTableModel>(query).ToList();
return results;
}
You can get data from the SQL Server as DataTable or convert it to a list as you prefer.
public DataTable GetDataTable(string connectionString, string tableName)
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string query = $'SELECT * FROM [{tableName}]';
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
Then use this table or list returned from the above method to insert in the SQLite table.
string cs = #"Data Source=datasource;Initial Catalog=databasename;User ID=user;Password=password";
DataTable table = GetDataTable(cs, "Table1");
using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
{
conn.CreateTable<Table1>();
if (conn.Query<Table1>("select * from Table1").Count() <= 0)
{
foreach(DataRow row in table.Rows)
{
//Access values of each row column row["columnName"]
// insert the list object
}
}
}
Refer to this one:
Inserting Data from SQL Server to Sqlite

How to get changes to dataset and save changes to database

I have a program that reads data from database and displays it onto spreadsheetcontrol(devexpress).
I would like your help in enabling the program to get changes to the dataset on button_click, and then save it back into the database.
Thanks
here is a snippet of the code
mentwall_DataDataSet ds = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.DATABASETableAdapter databaseAdapter = new mentwall_DataDataSetTableAdapters.DATABASETableAdapter();
databaseAdapter.Fill(ds.DATABASE);
dv = new DataView(ds.DATABASE);
mentwall_DataDataSet ds2 = new mentwall_DataDataSet();
mentwall_DataDataSetTableAdapters.RegsTableAdapter regsAdapter = new mentwall_DataDataSetTableAdapters.RegsTableAdapter();
regsAdapter.Fill(ds2.Regs);
dv2 = new DataView(ds2.Regs);
This binds the data source
Worksheet worksheet = workbook.Worksheets[2];
worksheet.DataBindings.BindToDataSource(dv, 1, 0);
Worksheet worksheet2 = workbook.Worksheets[3];
worksheet2.DataBindings.BindToDataSource(dv2, 1, 0);
I have done exactly the same, an application which shows content of a SQL table in a DevExpress Grid Control ( Windows Forms ) and when i click save button all changes ( including new rows added or deleted rows ) are persisted to the SQL Server database, here is a snippet of my DAL class which handles the database logic of saving:
the main point here is to use the SqlCommandBuilder class, which must be initialized with at least the select command and then all other commands are generated automatically, I have written this code > 5 years ago and i still use this app daily.
public int UpdateSQLDataTable(string connectionString, string TableName, DataTable dtSource)
{
try
{
using (SqlConnection sConn = new SqlConnection(connectionString))
{
sConn.Open();
var transaction = sConn.BeginTransaction();
try
{
var command = sConn.CreateCommand();
command.Transaction = transaction;
command.CommandText = $"SELECT TOP 1 * FROM {TableName} WITH (NOLOCK)";
command.CommandType = CommandType.Text;
// timeoput of 5 minutes
command.CommandTimeout = 300;
SqlDataAdapter sAdp = new SqlDataAdapter(command);
SqlCommandBuilder sCMDB = new SqlCommandBuilder(sAdp);
int affectedRecords = sAdp.Update(dtSource);
transaction.Commit();
return affectedRecords;
}
catch (Exception /* exp */)
{
transaction.Rollback();
throw;
}
}
}
catch (Exception exc)
{
Logger logger = new Logger();
logger.Error(string.Format("connectionString: '{0}', TableName: '{1}'", connectionString, TableName), exc);
return int.MinValue;
}
}

XML data not Complete when reading from SQL Server

I'm executing an sql query through C# to fetch XML data as follows, but in the string getxml_string the XML data is not complete as compared to the data on SQL server, I feel I'm doing something wrong with the getxml_string, but can't figure out:
string getxml = "some query"
DataTable getxml_table = SQLClass.GETSQL(getxml , conn);
var doc = new XmlDocument();
string getxml_string = getxml_table.Rows.OfType<DataRow>().Select(x => x[0].ToString()).First();
doc.LoadXml(getxml_string);
In GETSQL it's nothing fancy just as follows:
public static DataTable GETSQL(string sqller, SqlConnection connection)
{
DataTable data_table = new DataTable();
connection.Open();
using (SqlCommand command = new SqlCommand(sqller, connection))
{
SqlDataAdapter adapter = new SqlDataAdapter(command );
adapter.Fill(data_table);
connection.Close();
return data_table ;
}
}
This worked for me:
List<datarow> list = getxml_table.AsEnumberable().ToList();

Categories