Accessing math functions with sqlite-net-pcl and Xamarin.Forms - sqlite

When writing a C# console App, and using System.Data.SQLite, I am able to perform SQL commands such as:
string cosfun = string.Format("UPDATE test SET cosColumn = column1*cos(20));
However, when I try using a similar command in Xamarin.Forms, using the sqlite-net-pcl package, I get the followin error: SQLite.SQLiteException: 'no such function: cos'
I have found a similar question on SO (Custom SQLite functions in Xamarin.iOS). However, I didn't fully understand the response. I now have the following questions:
1) Can I make custom SQL functions using sqlite-net-pcl in Xamarin.Forms? If so, could someone please share a simple (but complete) example of how to do this?
2) Is there anyway for me to access the same math functions (pow, cos, sin, etc.) that I can access when writing console Apps in C#?
3) Is there another way to do this? For example, can I read columns from the database into a List, then perform the required math functions, and feed that back into the database? Would this be a terrible idea with a large database?
Thanks in advance,
Dustin

First is OK.
The SQLite-net PCL by Frank Kreuger is the one that Xamarin University uses in their XAM160 - Working with SQLite and Mobile Data class: https://university.xamarin.com/classes/track/cross-platform-design
Second is Ok.
You can find some documentation on how to get started on the Xamarin developer site: http://developer.xamarin.com/recipes/android/data/databases/sqlite/
Third answer is clear.
More Info:
You can refer to official document in here, Another similar discussion may be helpful for you this.

Correct me if I'm wrong, but what you're trying to do is essentially have two columns where one contains a set of data, and the other contains the result of a simple mathematical operation from the first column. From this you have two columns where one is dependent on the other, which means you are occupying double the necessary memory space. For a 100 entries, that's alright. For 1,000,000? Less so.
I personally thing you are better off not having cosColumn, and you should calculate the cosine when you read the data. For example:
// In your C# code...
public class MyData
{
public double Column1 { get; set; } = 0.0;
public double Cosine => Math.Cos(Column1);
}
In the above, the cosine value is never stored or created in neither C# or SQLite, but it is obtained only when needed. This makes it much more memory-friendly to the SQLite table, and it implements a better SQLite structure.
In the code above, the line:
public double Cosine => Math.Cos(Column1);
is exactly equivalent to:
public double Cosine
{
get
{
return Math.Cos(Column1);
}
}
There's no real difference between the two, and you save a lot of line-space. You can find more information on the => notation from this StackOverflow answer by Alex Booker.
Let's go through an example of implementing this structure. Suppose you have a database with 1 column with the name Column1, and you want to apply a Cosine function to this value and display it. Your code might look like:
// Read from database object of type MyData
MyData data = ReadOneValueFromDatabase<MyData>();
// Display values in a label
MyValueLabel.Text = "Database value: " + data.Column1.ToString();
MyCosineLabel.Text = "Cosine value: " + data.Cosine.ToString();
The object data will store the value of Column1 from the database in Column1, but not Cosine. The value of Cosine is only obtained when you call data.Cosine.

Related

Is there any way to get the c# object/data on which NUnit test is failing?

I am writing unit tests for a complex application which has so many rules to be checked into a single flow by using NUnit and Playwright in .Net5. Actually the case is, to save the time for writing the test scripts for Playwright (front-end testing tool), we have used a library named Bogus to create dummy data dynamically based on the rules (because the test cases has numerous rules to be checked and it was much more difficult to write fresh data to every case). I am using Playwright script into the NUnit test and providing the data source by using [TestCaseSource("MethodName")] to provide dynamic data object for different cases.
Now, we are facing a problem that some of the tests cases get passed and some are failed and we are unable to identify that particularly which test case is causing the problem because the testcase data is being provided by the dynamic source and in that source the data is being generated by the Bogus library on the bases of the rules which we have generated. Plus, we cannot look at the tests for a long time that's why we have automated the process.
[Test]
[TestCaseSource("GetDataToSubmit")]
public async Task Test_SubmitAssignmentDynamicFlow(Assignment assignment)
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false,
...
});
....
private static IEnumerable<TestCaseData> GetDataToSubmit()
{
//creating data for simple job
var simpleAssignment = new DummyAssigmentGenerator()
....
.Generate();
yield return new TestCaseData(simpleAssignment);
....
Now, my question is, is there any way so that we can view that what were the actual values in the object in the failed case, when we see the whole report of the testcases? So that we can come to know that which certain values are causing problems and eventually fixed those.
Two approaches...
Assuming that DummyAssignmentGenerator is your own class, override its ToString() method to display whatever you would like to see. That string will become part of the name of the test case generated, like...
Test_SubmitAssignmentDynamicFlow(YOUR_STRING)
Apply a name to each TestCaseData item you yield using the SetName() fluent method. In that case, you are supplying the full display name of the test case, not just the part in parentheses. Use {m}(YOUR_STRING) in order to have it appear the same as in the first approach.
If you can use it, the first approach is clearly the simpler of the two.

Unable to understand extension function in Kotlin Android?

I am not able to understand extension function and use it in my project. Can anyone guide me here please?
From the docs - “Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.”
To understand this in an easy way, let’s consider the below example:
First things first.
Write 10 and then put a dot(.) after it and then try to write addTwoNumbers().
You’ll be getting errors at this stage as there is no property named addTwoNumbers() for an integer.
Now, write this method:
fun Int.addTwoNumbers(y: Int): Int = this.plus(y) //“this” corresponds to the integer number. (In this example, “this” refers to 10).
Notice how we are using Int.addTwoNumbers().
Let’s try to follow the same thing again:
Write 10.
Put a dot(.) after it.
Try to write addTwoNumbers().
And this time you’ll notice, it’s appearing as if this is the property of integer.
Check the below code:
fun main() {
val sum = 10.addTwoNumbers(20) //here “this” will be assigned “10” and “y” will be assigned “20”
println("sum: $sum")
}
This will print sum: 30 in the console.
This phenomena is known as “Extension Function”.

Where should I put a logic for querying extra data in CQRS command flow

I'm trying to implement simple DDD/CQRS architecture without event-sourcing for now.
Currently I need to write some code for adding a notification to a document entity (document can have multiple notifications).
I've already created a command NotificationAddCommand, ICommandService and IRepository.
Before inserting new notification through IRepository I have to query current user_id from db using NotificationAddCommand.User_name property.
I'm not sure how to do it right, because I can
Use IQuery from read-flow.
Pass user_name to domain entity and resolve user_id in the repository.
Code:
public class DocumentsCommandService : ICommandService<NotificationAddCommand>
{
private readonly IRepository<Notification, long> _notificationsRepository;
public DocumentsCommandService(
IRepository<Notification, long> notifsRepo)
{
_notificationsRepository = notifsRepo;
}
public void Handle(NotificationAddCommand command)
{
// command.user_id = Resolve(command.user_name) ??
// command.source_secret_id = Resolve(command.source_id, command.source_type) ??
foreach (var receiverId in command.Receivers)
{
var notificationEntity = _notificationsRepository.Get(0);
notificationEntity.TargetId = receiverId;
notificationEntity.Body = command.Text;
_notificationsRepository.Add(notificationEntity);
}
}
}
What if I need more complex logic before inserting? Is it ok to use IQuery or should I create additional services?
The idea of reusing your IQuery somewhat defeats the purpose of CQRS in the sense that your read-side is supposed to be optimized for pulling data for display/query purposes - meaning that it can be denormalized, distributed etc. in any way you deem necessary without being restricted by - or having implications for - the command side (a key example being that it might not be immediately consistent, while your command side obviously needs to be for integrity/validity purposes).
With that in mind, you should look to implement a contract for your write side that will resolve the necessary information for you. Driving from the consumer, that might look like this:
public DocumentsCommandService(IRepository<Notification, long> notifsRepo,
IUserIdResolver userIdResolver)
public interface IUserIdResolver
{
string ByName(string username);
}
With IUserIdResolver implemented as appropriate.
Of course, if both this and the query-side use the same low-level data access implementation (e.g. an immediately-consistent repository) that's fine - what's important is that your architecture is such that if you need to swap out where your read side gets its data for the purposes of, e.g. facilitating a slow offline process, your read and write sides are sufficiently separated that you can swap out where you're reading from without having to untangle reads from the writes.
Ultimately the most important thing is to know why you are making the architectural decisions you're making in your scenario - then you will find it much easier to make these sorts of decisions one way or another.
In a project i'm working i have similar issues. I see 3 options to solve this problem
1) What i did do is make a UserCommandRepository that has a query option. Then you would inject that repository into your service.
Since the few queries i did need were so simplistic (just returning single values) it seemed like a fine tradeoff in my case.
2) Another way of handling it is by forcing the user to just raise a command with the user_id. Then you can let him do the querying.
3) A third option is ask yourself why you need a user_id. If it's to make some relations when querying the data you could also have this handles when querying the data (or when propagating your writeDB to your readDB)

Adding elements from vector to listBox in c++

Im new programmer, learning C++ nearly 15 weeks so far and I'm doing a small project about student database with GUI ( Windows-forms ). I created GUI with Drag n Drop thing in Visual Studio 2015.
I have class Student with 13 variables including getters and setters (Index, First Name,Last name, etc...). I've successfully opened connection with MySQL database for Adding, Deleting and Update students.
And I also wrote objects String^ to pick text from my TextBoxes and then parse them into normal string with msclr/marshal.
Now, problem is when i create object of Student and after adding it into vector with code below:
vector<Student> vektor;
Student *s = new Student(iIndeks, cIme, cPrezime, cDatumRodjenja, cFakultet, cSmer, cEmail, iBrTelefona, cDrzava, cMesto, cUlicaIBroj, cOpstina, iPostanskibr);
vektor.push_back(*s);
Im unable to add elements of that vector into listBox with:
listBox1->Items->Add(vektor);
It says this error:
Function cannot be called with given argument list,
argument types are:
(std::vector<Student, std::allocator<Student>>) object type is:
System::Windows::Forms::ListBox::ObjectCollection ^.
I guess its pretty self-explaining but I have no idea (should I or not) create my class like the ref class or something like that?
Any suggestion what this newbie can do?
Thanks for help.

How do you run a batch of SQL statements using the SQLite.NET PCL

In the past I have avoided ORM and always handcrafted parameterised queries etc. This is very time consuming and a real pain when first developing an application. Recently I decided to have another look at ORM specifically the Sqlite.NET ORM.
I would like to use SQLite ORM features but also be able to run a batch of native SQL commands to prepopulate a database.
We are using the SqliteNetExtensions-MvvmCross dll to enable one-to-many relationships etc and this all looks fine. My issues comes to when I want to seed the database with configuration data. I was hoping to simply provide a sql file that contained a series of sql statements that it would run one after another.
I have grabbed the SQlite.NET code from GITHub and run the tests. I have then extended the StringQueryTests class that has a simple [Product] table to do the following:-
[Test]
public void AlanTest()
{
StringBuilder sb = new StringBuilder(200);
sb.Append(" DELETE FROM Product;");
sb.Append(" INSERT INTO Product VALUES (1,\"Name1\",1,1);");
sb.Append(" INSERT INTO Product VALUES (2,\"Name2\",2,3);");
db.Execute(sb.ToString());
}
When I run this it does not throw an error and in fact the behaviour seems to be that it will only run the first command. If I paste the contents of sb.ToString() into a sqlite database query window it will work just fine.
Is this the expected behaviour? If so, how do I go about overcoming this so that I can use an approach like above. I don’t really want to have to create objects to manage all SQL statements if possible.
I can see that there are a number of approaches that could be adopted to overcome this issue - anyone got a work around or suggestions that they think can solve this issue?
Kind regards
Alan.
I just ran into this issue too. I found a blog post that explains why.
Here is what the post says in case it goes missing.
All of the code [in sqlite-net] correctly checks the result codes and throws exceptions accordingly.
Although I haven't posted all relevant code here, I did review it, and the real origin of this behavior is elsewhere - in the native sqlite3.dll sqlite3_prepare_v2 method. Here's the relevant part of the documentation:
These routines only compile the first statement in zSql, so *pzTail is left pointing to what remains uncompiled.
Since sqlite-net doesn't do anything with the uncompiled tail, only the first statement in the command is actually executed. The remainder is silently ignored. In most cases you won't notice that when using sqlite-net. You will either use its micro ORM layer or execute individual statements. The only common exception that comes to mind, is trying to execute DDL or migration scripts which are typically multi statement batches.
Can't you do :
[Test]
public void AlanTest()
{
var queries = new List<string> ()
{
" DELETE FROM Product",
" INSERT INTO Product VALUES (1,\"Name1\",1,1)",
" INSERT INTO Product VALUES (2,\"Name2\",2,3)"
};
db.BeginTransaction ();
queries.ForEach (query => db.Execute (query));
db.Commit ();
}
You don't really need the transaction, just faster execution / checkpoint rollback...

Resources