How to recover a database to a different page? - c#

I created a database with SQLite-net so:
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db"), true);
await conn.CreateTableAsync<Musei>();
Musei musPref;
if (muss.NumeroTel != null && muss.Descrizione!=null && muss.indirizzoEmail!= null && muss.Immagine!= null)
{
musPref = new Musei
{
DidascaliaLista=muss.DidascaliaLista,
NomeMuseo = muss.NomeMuseo,
Luogopreciso = muss.Luogopreciso,
Descrizione = muss.Descrizione,
NumeroTel = muss.NumeroTel,
IndirizzoEmail = muss.IndirizzoEmail,
Immagine= muss.Immagine,
};
}
await conn.InsertAsync(musPref);
In another project I need to recover the database created and insert objects inside a ListView, But I do not know how to proceed ..
try
{
StorageFile data = await ApplicationData.Current.LocalFolder.GetFileAsync("Database.db");
}
catch(Exception)
{
}
And now??
I would like to retrieve the database created above and use it, inserting objects "Musei" that are in it and display it in a ListView

If you want to read from the database you created earlier, you can do the following:
// Get a connection to the database that is in the local folder.
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database.db");
var con = new SQLiteAsyncConnection(dbPath, true);
// Get all "Musei" in the database stored in the "Musei" table.
var results = await con.QueryAsync<Musei>("SELECT * FROM Musei");
If you only want the Musei that match a certain field value, for example: you only want to read those in the specific location "Rome", you can do that like this:
var searchLocation = "Rome"; // for example entered by the user in your UI.
// Get only the "Musei" in `searchLocation`.
var results = await con.QueryAsync<Musei>("SELECT * FROM Musei WHERE Luogopreciso ='?'", searchLocation);
An alternative, if you are only querying a single table, is to do it like this, using LINQ:
var query = con.Table<Musei>();
// or, if looking for `searchLocation`:
var query = con.Table<Musei>().Where(m => m.Luogopreciso == "Rome");
you can then get this as a list using:
var result = await query.ToListAsync();
To find out which tables are actually present in your opened database files, you can do this:
var nTables = 0;
System.Diagnostics.Debug.WriteLine("Tables in the database");
foreach (var mapping in con.TableMappings)
{
System.Diagnostics.Debug.WriteLine(mapping.TableName);
nTables++;
}
System.Diagnostics.Debug.WriteLine("{0} tables in total", nTables);
and look at the debug output.

Related

DBUP - Run scripts in sequence

I'm trying to run some scripts in sequence to create and seed my database. However it seems like the second script never gets run. Furthermore, I think it's running the first script twice.
public DatabaseFixture()
{
var connectionString = "Server=localhost;User Id = sa;Password=yourStrong(!)Password;Initial Catalog = master";
var createSchemaSqlScriptOptions = new SqlScriptOptions { ScriptType = ScriptType.RunAlways, RunGroupOrder = 1 };
var seedDataSqlScriptOptions = new SqlScriptOptions { ScriptType = ScriptType.RunAlways, RunGroupOrder = 2 };
var upgradeEngineBuilder = DeployChanges.To.SqlDatabase(connectionString, null)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.Contains("0001"), createSchemaSqlScriptOptions)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly(), script => script.Contains("0002"), createSchemaSqlScriptOptions)
.LogToConsole();
var upgrader = upgradeEngineBuilder.Build();
var result = upgrader.PerformUpgrade();
}
Also, all my scripts are embedded sources so I don't think it's that.
Hi, your code shows a object createSchemaSqlScriptOptions duplicate in method WithScriptsEmbeddedInAssembly .
Give it a check.

Consolidating and deleting invoice lines but getting TxnLineID: required field is missing although provided

I have an invoice with multiple lines that I want to consolidate into one line. It takes the and iterates through each . It sums each to a variable. After the loop, it should create a new line on the invoice and delete the others.
I keep getting a "TxnLineID: required field is missing" even though I am providing it as "-1" for a new line:
private static void Main(string[] args)
{
// creates the session manager object using QBFC
var querySessionManager = new QBSessionManager();
// want to know if a session has begun so it can be ended it if an error happens
var booSessionBegun = false;
try
{
// open the connection and begin the session with QB
querySessionManager.OpenConnection("", "Test Connection");
querySessionManager.BeginSession("", ENOpenMode.omDontCare);
// if successful then booSessionBegin = True
booSessionBegun = true;
// Get the RequestMsgSet based on the correct QB Version
var queryRequestSet = GetLatestMsgSetRequest(querySessionManager);
// Initialize the message set request object
queryRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// QUERY RECORDS **********************
// appendInvoiceQuery to request set
// only invoices that start with the consulting invoice prefix
// include all of the line items
// only unpaid invoices
var invoiceQ = queryRequestSet.AppendInvoiceQueryRq();
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.MatchCriterion.SetValue(ENMatchCriterion.mcStartsWith);
invoiceQ.ORInvoiceQuery.InvoiceFilter.ORRefNumberFilter.RefNumberFilter.RefNumber.SetValue("ML-11");
invoiceQ.ORInvoiceQuery.InvoiceFilter.PaidStatus.SetValue(ENPaidStatus.psNotPaidOnly);
invoiceQ.IncludeLineItems.SetValue(true);
// DELETE INVOICE ***********************************
// var deleteI = queryRequestSet.AppendTxnDelRq();
// deleteI.TxnDelType.SetValue(ENTxnDelType.tdtInvoice);
// deleteI.TxnID.SetValue("3B57C-1539729221");
// Do the request and get the response message set object
var queryResponseSet = querySessionManager.DoRequests(queryRequestSet);
// Uncomment the following to view and save the request and response XML
var requestXml = queryRequestSet.ToXMLString();
// Console.WriteLine(requestXml);
SaveXML(requestXml, 1);
var responseXml = queryResponseSet.ToXMLString();
// Console.WriteLine(responseXml);
SaveXML(responseXml, 2);
// Get the statuscode of the response to proceed with
var respList = queryResponseSet.ResponseList;
var ourResp = respList.GetAt(0);
var statusCode = ourResp.StatusCode;
// Test what the status code
if (statusCode == 0)
{
// Parse the string into an XDocument object
var xmlDoc = XDocument.Parse(responseXml);
// Set the xmlDoc root
var xmlDocRoot = xmlDoc.Root.Element("QBXMLMsgsRs")
.Element("InvoiceQueryRs")
.Elements("InvoiceRet");
var i = 1;
// Iterate through the elements to get values and do some logic
foreach (var invoiceElement in xmlDocRoot)
{
// Create connection to update
var updateSessionManager = new QBSessionManager();
updateSessionManager.OpenConnection("", "Test Connection");
updateSessionManager.BeginSession("", ENOpenMode.omDontCare);
// Make the request set for updates
var updateRequestSet = GetLatestMsgSetRequest(updateSessionManager);
updateRequestSet.Attributes.OnError = ENRqOnError.roeStop;
// Set the variables required to edit a file
var txnId = (string) invoiceElement.Element("TxnID");
var editSequence = (string) invoiceElement.Element("EditSequence");
var xmlLineItemRoot = invoiceElement.Elements("InvoiceLineRet");
var feeAmount = 0.0f;
foreach (var invoiceLineItemElement in xmlLineItemRoot)
{
if (invoiceLineItemElement.Element("ItemRef").Element("FullName").Value == "Consulting Fees:Consulting")
{
feeAmount = float.Parse(invoiceLineItemElement.Element("Amount").Value) + (float) feeAmount;
}
}
//// UPDATING RECORDS ******************************
//// TxnID and EditSequence required
var invoiceM = updateRequestSet.AppendInvoiceModRq();
invoiceM.TxnID.SetValue(txnId);
invoiceM.EditSequence.SetValue(editSequence);
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.TxnLineID.SetValue("-1");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod.Amount.SetValue((double)feeAmount);
updateSessionManager.DoRequests(updateRequestSet);
i++;
updateSessionManager.EndSession();
updateSessionManager.CloseConnection();
}
}
// end and disconnect after done
querySessionManager.EndSession();
booSessionBegun = false;
querySessionManager.CloseConnection();
}
catch (Exception e)
{
// if it couldn't connect then display a message saying so and make sure to EndSession/CloseConnection
Console.WriteLine(e.Message.ToString() + "\nStack Trace: \n" + e.StackTrace + "\nExiting the application");
if (booSessionBegun)
{
querySessionManager.EndSession();
querySessionManager.CloseConnection();
}
}
}
Furthermore, I want it to remove the lines from the invoice that were used in the sum. I've read conflicting information on how to do this.
One camp says, don't specify those lines and it will erase them when the updateRequestSet is executed. Another contradicts by saying that not specifying them, it will retain them. Can someone please clear this up. I haven't gotten far enough to test, however.
Oh and here is the entirety of the error:
InvoiceMod
ORInvoiceLineModList:
element(2) - InvoiceLineMod:
TxnLineID: required field is missing
End of InvoiceLineMod
End of ORInvoiceLineModList
End of InvoiceMod
Stack Trace:
at Interop.QBFC13.IQBSessionManager.DoRequests(IMsgSetRequest request)
at ConsolidateInvoiceLineItems.Program.Main(String[] args) in C:\qb\QuickBooks\ConsolidateInvoiceLineItems\ConsolidateInvoiceLineItems\Program.cs:line 226
Exiting the application
Wish I could take credit for this, but actually got help from the Intuit Developers forum.
Need to change the multiple Append() to the following:
var invoiceModLineItems = invoiceM.ORInvoiceLineModList.Append().InvoiceLineMod;
invoiceModLineItems.TxnLineID.SetValue("-1");
invoiceModLineItems.ItemRef.FullName.SetValue("Consulting Fees:Consulting");
invoiceModLineItems.Amount.SetValue((double)feeAmount);

How to recover objects from a database?

I have a database in the Assets folder of the project and I would try to recover the file of the database, but I get an exception. Can not find the file. What should I change?
SQLiteAsyncConnection mussAll = new SQLiteAsyncConnection("ms-appx:///../Assets/Database1.db", true);
Later I would like to fill a List with objects within the database. is correct to do so?
var queryAll = await mussAll.Table<Musei>().ToListAsync();
List<Musei> listAll = new List<Musei>();
foreach(Musei museiAll in queryAll)
{
listAll.Add(museiAll);
}
var qruppim = listAll.OrderBy(x => x.NomeMuseo).GroupBy(x => x.NomeMuseo.Substring(0, 1));
MuseoDettagli.Source = qruppim;

Remove document by id field in mongodb using C#

I am trying to delete the document by id, which is of type ObjectId, I do have converted the string to ObjectId and passed as parameter to remove from collection, but I am not able to delete the record.
I don't know what is the actuall reason behind, Looking for solution, below is my code sample:
public void DeleteRecords(string objectID)
{
try
{
// Create server settings to pass connection string, timeout, etc.
MongoServerSettings settings = new MongoServerSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
// Create server object to communicate with our server
MongoServer server = new MongoServer(settings);
MongoDatabase myDB = server.GetDatabase("DemoMongoDB");
MongoCollection<BsonDocument> records = myDB.GetCollection<BsonDocument>("Records");
//var query = Query<Records>.EQ(fd => fd._id, ObjectId.Parse(name));
var query = Query<Records>.EQ(e => e._id, new BsonObjectId(objectID));
records.Remove(query);
}
catch (Exception ex)
{
}
}
Try below code, and see whether is working?
var query = Query.EQ("_id", new BsonObjectId("objectID"));
Or
var query = Query.EQ("_id", name);
records.Remove(query);
Finally, This worked for me, without converting the string to object id and pass as a parameter as a string itself.
var query = Query.EQ("_id", objectID);
records.Remove(query);

Entity Framework insert produces empty column in SQL Server LocalDB

I am performing an insert operation with Entity Framework 5.
My code inserts a new row from a user input and parsed values in another method. The debug operation shows all object attributes have a value before the insert operation is called, the code executes without any exception, and the row is updated in the LocalDb, but content column value is missing or never saved.
Here is my entity framework code:
public async Task<IHttpActionResult> PostFormData()
{
var profile = db.ProfileRepository.dbSet.Where(m => m.profileId == 1).FirstOrDefaultAsync().Result;
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var research = new Research();
research.profile = profile;
string root = HttpContext.Current.Server.MapPath("~/documentSafe");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
research.title = provider.FormData["title"];
research.researchAbstract = provider.FormData["researchAbstract"];
research.publisher = provider.FormData["publisher"];
var areaList = new List<ResearchArea>();
string areas = provider.FormData["researchArea"];
foreach (var r in areas.Split(','))
{
var area = new ResearchArea()
{
name = r,
departmentId = profile.departmentId
};
areaList.Add(area);
}
research.researchArea = areaList;
research.researchType = new ResearchType()
{
name = provider.FormData["type"]
};
string content = WebUtility.HtmlEncode(parser.convert(provider.FileData[0]));
research.content = content;
using (var context = new AcademicContext())
{
context.Research.Add(research);
await context.SaveChangesAsync();
}
return Ok();
}
catch (System.Exception e)
{
return InternalServerError(e);
}
}
The missing column is a parsed html string encoded using webutility and has an average size of 15,000 characters. I have checked the database column attribute too, and it is set to nvarchar(MAX).
If I insert a sample plain text to the column, the value get saved, but if I pass the encoded html string it does not.
Any suggestions why my column will not be null but still not contain any value.
Solution: The sql server explorer in visual studio seem to display an empty column when the character size is greater than 4000. I ran multiple test to verity this. I could get the content of the empty column by running raw sql select query.

Categories