Check if table exist using SQLite-PCL in a UWP - c#

I'm stuck with how to check if a table already exists.
I have been searching but like many times before I can't find good examples.
The ones I find on SQLite don't work with the PCL version. I can't understand why though, so if anyone has a good site where to go please feel free to add them.
These are the ones I have used:
http://blogs.u2u.be/diederik/post/2015/09/08/Using-SQLite-on-the-Universal-Windows-Platform.aspx
https://code.msdn.microsoft.com/windowsapps/Implement-SQLite-Local-8b13a307#content
This is my code showing how I have tried to check it, but it only checks the path, which always exists. Not a smart solution when I thought about it.
private void LikeItButton_Click(object sender, RoutedEventArgs e)
{
var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Filmdb.sqlite");
using (SQLite.Net.SQLiteConnection conn =
new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
{
if (File.Exists(sqlpath))
{
AdMovieID();
}
else
{
conn.CreateTable<MovieID>();
AdMovieID();
}
}
}

You could execute a query:
SELECT name FROM sqlite_master WHERE type='table' AND name='MovieId';
by doing
var tableExistsQuery = "SELECT name FROM sqlite_master WHERE type='table' AND name='MovieId';"
var result = conn.ExecuteScalar<string>(tableExistsQuery);

Related

Filter Record Set Before Populating ADO.NET Object

I used this tutorial to build a Crystal Report in my application. The tutorial guides the user through developing an ADO.NET object and then populating it with data. I am also using a Parameter in the Crystal Report to limit the data set. The issue I'm having is that loading the report is slow and I wonder if it's because I have to load more data than I actually need before the Crystal Report employs the Parameter filter.
Following is my existing code, which runs on the report viewer form Load event. I'd like to adjust the code below to pass a parameter so I can filter the data as it's loaded rather than loading a bunch of data I know I won't need or use.
private void InspectionReportSerial2_Viewer_Load(object sender, EventArgs e)
{
International_PZD_PRDEntities db = new International_PZD_PRDEntities();
var list = db.vw_Nightly_and_Inspections.Select(p=>new {ID = p.ID,
SerialNumber = p.SerialNumber, ProductionOrder = p.ProductionOrder,
Product=p.Product, Customer=p.Customer, SalesOrder = p.SalesOrder,
LineItem = p.LineItem, Section=p.Section,InspectionPoint=p.InspectionPoint,
Status=p.Status,SectionSignoffBy = p.SectionSignoffBy,
SectionSignoffCheck=p.SectionSignoffCheck,
SectionSignoffDate = p.SectionSignoffDate,HardwareSerial=p.HardwareSerial,
SectionSortString = p.SectionSortString, ItemSortString = p.ItemSortString,
Comment = p.Comment});
InspectionReportSerial21.SetDataSource(list);
}
Add a Where. Since you are not describing the kind of filtering you need, I can only give an example:
private void InspectionReportSerial2_Viewer_Load(object sender, EventArgs e)
{
International_PZD_PRDEntities db = new International_PZD_PRDEntities();
var list = db.vw_Nightly_and_Inspections
.Where(p => p.Customer == "Dekxblock")
.Select(p => new { ID = p.ID, SerialNumber = p.SerialNumber, ... });
InspectionReportSerial21.SetDataSource(list);
}
I don't know what International_PZD_PRDEntities is. If it is some kind of O/R-mapper (e.g., EF or EF Core), then this will filter the records on the database side, which is faster than filtering the data in your application, because less records have to be transmitted. If not, then you should execute a query like SELECT * FROM vw_Nightly_and_Inspections WHERE Customer = 'Dekxblock' including the filter. Make sure to use Command.Parameters

C# SubmitChanges dont work

I'm trying to make a database. I made a form and I want to get the data from that. Everything seems okay, but my database didn't get the update and didn't change. I'm using a local database. I tried to change "Copy to output directory" but nothing happened... The SubmitChanges seems ok: I get the Message, but after the program is closed the database doesn't contain the new data... I saw a lot of posts with similar problems, but I didn't find a solution.
My Code:
private void felvetButton_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (f2.ShowDialog() == DialogResult.OK)
{
Match m = new Match();
try
{
m.datum = f2.datumTextBox.Text;
m.mod_fk = Convert.ToInt32(f2.modTextBox.Text);
m.acc_fk = Convert.ToInt32(f2.accTextBox.Text);
m.champion = f2.champTextBox.Text;
m.szerep_fk = Convert.ToInt32(f2.roleTextBox.Text);
m.kimenet = f2.resultTextBox.Text;
m.mhossz = f2.lengthTextBox.Text;
m.kill = Convert.ToInt32(f2.killTextBox.Text);
m.death = Convert.ToInt32(f2.deathTextBox.Text);
m.assist = Convert.ToInt32(f2.assistTextBox.Text);
m.kda = float.Parse(f2.kdaTextBox.Text);
m.killpart = float.Parse(f2.kpTextBox.Text);
m.farm = Convert.ToInt32(f2.farmTextBox.Text);
m.ward = Convert.ToInt32(f2.wardTextBox.Text);
m.redward = Convert.ToInt32(f2.redwTextBox.Text);
db.SubmitChanges();
MessageBox.Show("New match added to the database!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Don't you have to make the entity layer aware of this new object? I imagine you need to call something like this for new entities:
db.Matches.InsertOnSubmit(match);
Its perfectly fine to load entities from the database via this entity layer, modify them, and then use db.SubmitChanges() because the entity layer already knows about existing objects! How is it supposed to know about this new object if the entity layer doesn't have any reference to it?

An attempt to attach an autonamed database for file failed

The compiler is giving me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists or specified file cannot be open, or it is located on UNC share.
I've been reading around other stackoverflow posts and they mention it might be a connectionstring problem, but I'm coding this in linq, not ado.net code. I don't use a traditional connectionstring. In fact, I had to use a namespace to call the tableAdapter in order for me to access the data source I needed.
The code being used is as follows:
using CustomerInvoices.MMABooksDataSetTableAdapters;
namespace CustomerInvoices
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MMABooksDataSet mmaBooksDataSet = new MMABooksDataSet();
InvoicesTableAdapter invoicesTableAdapter = new InvoicesTableAdapter();
CustomersTableAdapter customersTableAdapter =
new CustomersTableAdapter();
private void Form1_Load(object sender, EventArgs e)
{
invoicesTableAdapter.Fill(mmaBooksDataSet.Invoices);
customersTableAdapter.Fill(mmaBooksDataSet.Customers);
var invoices = from invoice in mmaBooksDataSet.Invoices
join customer in mmaBooksDataSet.Customers
on invoice.CustomerID equals customer.CustomerID
orderby customer.Name, invoice.InvoiceTotal descending
select new
{
customer.Name,
invoice.InvoiceID,
invoice.InvoiceDate,
invoice.InvoiceTotal
};
string customerName = "";
int i = 0;
foreach (var invoice in invoices)
{
if (invoice.Name != customerName)
{
lvInvoices.Items.Add(invoice.Name);
customerName = invoice.Name;
}
else
{
lvInvoices.Items.Add("");
}
lvInvoices.Items[i].SubItems.Add(invoice.InvoiceTotal.ToString());
lvInvoices.Items[i].SubItems.Add(Convert.ToDateTime
(invoice.InvoiceDate).ToShortDateString());
lvInvoices.Items[i].SubItems.Add
(invoice.InvoiceTotal.ToString("c"));
i += 1;
}
}
}
}
I figured it out. Thru the data source, I went into the connection property window and found the connection path file, I changed it to the correct one
Data Source=localhost\sqlexpress;Initial Catalog=MMABooks;Integrated Security=True
And it Worked. It seems the error is because the connectionString was pointing to the wrong path file. Hope this helps others. Thank you.

C# WPF oledb MS Access

I have:
1) C# WPF DataGrid
2) MS Access db that include one table ("Temp")!
I already read a lot of forums and arcticles but I'm not find an answer!
I want to add/edit/delete data in MS Access DB using DataGrid!
I'm tried these code but it's doesnt work!
private void Button_Click_3(object sender, RoutedEventArgs e)
{
if (_dataSet != null && _dataSet.Tables[0] != null && _dataSet.HasChanges(DataRowState.Modified))
{
DataTable dt = _dataSet.Tables[0].GetChanges(DataRowState.Modified);
adapter.Update(dt);
}
adapter.Update(_dataSet.Tables["Temp"]);
}
I'm from Ukraine so translalte u!
I have an error (I'm hope I do it right):
"Dynamic SQL generation for the DeleteCommand is not supported for the SelectCommand, does not return any key column information"
Error like this always return when use update or ad data to DataGrid!
PLEASE, Help me!
Thanks You for a all!
Maybe you will use ORM (object relational mapping) for data access. For .NET exist: Entity Framework, Fluent Nhibernate, Dapper (micro-orm) - maybe beast options for you because it is very simple. Also note MVVM pattern (beast option for WPF). Good article with example: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
A have an answer!
To work this code he need a key cell(column)!
If there is not, commandBuilder can't get a default comands, so you always get an errors! Here are code:
adapter = new OleDbDataAdapter(comand, con);
_dataSet = new DataSet();
adapter.Fill(_dataSet, "TargetAndProbability");
cb = new OleDbCommandBuilder(adapter);
cb.QuotePrefix = "[";// it's need if your cells contains others symbols
cb.QuoteSuffix = "]";
Than all very simple!
adapter.Update(_dataSet, "TargetAndProbability");

Passing user parameters to SSIS package

Here's my problem. I have a SSIS package that takes 1 parameter on input called SegmentID. But I cant pass it from the c# code. I'm searching for2 days so far, and here's a solution I came up with, which should work, but doesn't - SSIS package fails at the stage of getting parameter. What a hell am I doing wrong?
using (SqlConnection con = GetConnection())
{
var integrationServices = new IntegrationServices(con);
if (integrationServices.Catalogs.Contains("SSISDB"))
{
var catalog = integrationServices.Catalogs["SSISDB"];
if (catalog.Folders.Contains("PSO"))
{
var folder = catalog.Folders["PSO"];
if (folder.Projects.Contains("PSO_SSIS"))
{
var project = folder.Projects["PSO_SSIS"];
project.Parameters["SegmentID"].Set(ParameterInfo.ParameterValueType.Literal, segmentID);
if (project.Packages.Contains("Main.dtsx"))
{
var package = project.Packages["Main.dtsx"];
long executionIdentifier = package.Execute(false, null);
return catalog.Executions[executionIdentifier];
}
}
}
}
}
Thanks, guys, but i figured it out. You have to do something like this:
var setValueParameters = new Collection<PackageInfo.ExecutionValueParameterSet>();
setValueParameters.Add(new PackageInfo.ExecutionValueParameterSet
{
ObjectType = 20,
ParameterName = "SegmentID",
ParameterValue = 1
});
and then call:
long executionIdentifier = package.Execute(false, null, setValueParameters);
Why it confused me so much is that I thought that this thing is just for system parameters, like logging level or something, and NOWHERE was mentioned that the code for user parameters is 20, and this construction can be used for assigning them. Hope it'll help somebody to avoid butthurt I had for 2 days.

Categories