Accessing Sqlite Database from Windows Forms Application in C++ - c++

I am new to C++ (was previously into Java) and I am trying to find my way around it for the past few days. I am having a Sqlite DB in my local Machine which I am trying to access in order to display the results of a query on a Windows Application Form using DataGridView.
I was able to locate a good place to start here but later discovered that this was more concentrated towards SQL server and not SQLite and the code failed when I tried to replace this part of code
String^ connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";
with this
String^ connectionString = "Data Source=C:\\data\\test.db"
to point to my local Sqlite DB (test.db).
Upon more digging I found that I was able to find C# examples for linking SQLite DB to Windows Form Application here. Next I tried to convert the C# code provided into a C++ one but failed.
I have been looking all around for simple C++ examples which would help me understand how to link a Sqlite DB to a Windows Form Application but am not able to do so yet.
I would appreciate it greatly if anyone could point me to one such example.

To access SQLite DB from managed code use System.Data.SQLite library. It's a managed library supported by SQLite Development Team and you can use it with managed C++ also. Here is the sample:
using namespace System::Data::SQLite;
using namespace System::Text;
void Test()
{
SQLiteConnection ^db = gcnew SQLiteConnection();
try
{
db->ConnectionString = "Data Source=C:\\data\\test.db";
db->Open();
// Do the job here
db->Close();
}
finally
{
delete (IDisposable^)db;
}
}

Related

Can't open database using SQLite on an UWP written in C++

I am making an UWP in which I need to access a database. To do so I first downloaded and installed the SQL Universal Windows Platform from this link:
https://sqlite.org/download.html
After this was done I added it as a reference and included it in my code with:
#include <sqlite3.h> //Not sure if I need to make any other changes for this to work
To troubleshoot I have just a button and a textbox. This is the code that it's been run when the button is clicked:
int rc;
sqlite3 *testDB;
if (SQLITE_OK == (rc = sqlite3_open("signers.db", &testDB))) {
Message->Text = "It worked!";
}
else {
Message->Text = "Can't open Database";
}
signers.db it's a database that I created using SQLite so I could have some data to read from my program. Everytime I run the program the text "Can't open Database" appears. I've tried every solution that I see online but none seem to work for me thus I think that I overseeing something. I am fairly new at UWP and also at using databases.
If you need any additional information feel free to ask for it.
If you have the database in your package folder, then it is read-only. You need to use sqlite3_open_v2 and pass the SQLITE_OPEN_READONLY flag.
If you want to open the database for read / write then you need to copy it to your local folder first.
(Also make sure you actually have the database set to deploy; in the Properties window make sure it is set to Content and that it will be copied to the output directory).
According to
https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions
you have some limitations to the location where the db file you want to open is located. sqlite itself should work. Try opening a db in a folder specified in the article.
Could also be just a corrupted db file. Did you try to create an empty one?

Enumerate Upgrade Codes of installed products?

I'd like to get list of all Upgrade codes of all installed products on Windows box. The question is: is there a dedicated MSI function to address this request?
There is MsiEnumProducts() that enumerates all installed products and MsiEnumRelatedProducts() to enumerate all products for the given Upgrade code. But I can't find a function to get all Upgrade codes in the system.
The workaround I can imagine is use MsiEnumProducts() to get list of all installed products, open each with MsiOpenProduct() function and read "UpgradeCode" property with MsiGetProductProperty(). But this should be very slow due to multiple MsiOpenProduct() calls.
I believe MsiEnumProducts loop with MsiOpenProduct and then MsiGetProductProperty is the correct official sequence. If you really need faster and are willing to bypass the API's you could read the registry directly at HKCR\Installer\UpgradeCodes. You'll have to reverse the Darwin Descriptors though. This isn't technically supported but the reality is these keys have been there for 16 years and MSFT has been doing ZERO development on The Windows Installer. Ok, maybe they updated the version number and removed ARM support in Windows 10 LOL.
FWIW, I like to use C# not C++ but the concept is the same. The following snippet ran on my developer machine in about 2 seconds.
using System;
using Microsoft.Deployment.WindowsInstaller;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foreach (var productInstallation in ProductInstallation.AllProducts)
{
using(var database = new Database(productInstallation.LocalPackage, DatabaseOpenMode.ReadOnly))
{
Console.WriteLine(database.ExecutePropertyQuery("UpgradeCode"));
}
}
}
}
}
According to the DTF documentation, ProductInstallation.AllProducts uses MsiEnumProducts. The Database class constructor is using MsiOpenDatabase and ExecutePropertyQuery is a higher level call that basically abstracts doing a SELECT Value from Property WHERE Property = '%s'. So it'll be calling APIs to create, execute and fetch results from views. All these classes implement IDisposable to call the correct APIs to free resources also.
Ya... that's why I love managed code. :)

WinRT API WIndows::System::Launcher::LaunchFileAsync() usage from C++

I'm trying to launch an image using WinRT API WIndows::System::Launcher::LaunchFileAsync().
Code snippet is as follows:
RoInitialize(RO_INIT_MULTITHREADED);
String^ imagePath = ref new String(L"C:\\Users\\GoodMan\\Pictures\\wood.png");
auto file = Storage::StorageFile::GetFileFromPathAsync(imagePath);
Windows::System::Launcher::LaunchFileAsync(file);
I'm getting this error from the LaunchFileAsync() API:
error C2665: 'Windows::System::Launcher::LaunchFileAsync' : none of
the 2 overloads could convert all the argument types
Can I please get help how to solve this. I'm very new to WinRT C++ coding .
The method GetFileFromPathAsync does not return a StorageFile, but it returns IAsyncOperation<StorageFile>^. What you have to do is convert the latter to the former, as follows:
using namespace concurrency;
String^ imagePath = ref new String(L"C:\\Users\\GoodMan\\Pictures\\wood.png");
auto task = create_task(Windows::Storage::StorageFile::GetFileFromPathAsync(imagePath));
task.then([this](Windows::Storage::StorageFile^ file)
{
Windows::System::Launcher::LaunchFileAsync(file);
});
Generally all Windows Store app framework methods that end in Async will return either an IAsyncOperation, or a task. These methods are what are known as asynchronous methods, and require some special handling. See this article for more info: Asynchronous programming in C++ .
So now everything is great, correct? Well, not quite. There is another issue with your code. It is that when you run the code above, you will get an access-denied error. The reason is that Windows Store Apps are sandboxed, and you cannot generally access just any file on the filesystem.
You are in luck, though, because you are trying to access a file in your Pictures folder. The Pictures folder is a special folder that Windows Store apps have access to. You can get at it using the KnownFolders class:
using namespace concurrency;
Windows::Storage::StorageFolder^ pictures =
Windows::Storage::KnownFolders::PicturesLibrary;
auto task = create_task(pictures->GetFileAsync("wood.png"));
task.then([this](Windows::Storage::StorageFile^ file)
{
Windows::System::Launcher::LaunchFileAsync(file);
});
Note that in order to access the Pictures folder your application has to declare it in the project manifest. To do so, double click on the Package.appmanifest file in the project "tree" in Visual Studio, and select the Capabilities tab. Then under Capabilities, check Pictures Library.

How to open and read SQLite database from another platform like (iOS to Windows)

I am working on one MFC Application where I have to use sqlite database of iOS application.
The iOS database is encrypted by using SQLite API called sqlite3_key().
But when I am trying to open the same database of iOS in my MFC Application it throws exception saying File is encrypted or not a database and unable to read the data from the database.
The iOS database will be downloaded from Dropbox by MFC application and will replace current database and use it instead of previous
I am using following code for opening the database using CppSqlite3 Wrapper for Sqlite:
CppSQLite3DB db;
try{
db.open("mydb.db");
TRACE(_T("database opened"));
db.key("1234", strlen("1234"));
}catch(CppSQLite3Exception e){
return NULL;
}
As the CppSQLite3DB class does not have a function called key(). I have added that function in the class
void CppSQLite3DB::key(const char* szKey, int nKey)
{
if (mpDB)
{
sqlite3_key(mpDB, szKey, nKey);
}
}
and upgrade my library to SQLiteEncrypt.
Whereas The iOS application is using SQLCipher for Database.
But, the result is same. So,
Can anyone tell me how I can achieve that?
Thank you in Advance.
From http://sqlcipher.net/:
SQLCipher has broad platform support for [..] C/C++ [..] iPhone/iOS [..]
Perhaps using SQLCipher in your Windows application would solve incompatibility problems.

C++\IronPython integration example code?

I'm looking for a simple example code for C++\IronPython integration, i.e. embedding python code inside a C++, or better yet, Visual C++ program.
The example code should include: how to share objects between the languages, how to call functions\methods back and forth etc...
Also, an explicit setup procedure would help too. (How to include the Python runtime dll in Visual Studio etc...)
I've found a nice example for C#\IronPython here, but couldn't find C++\IronPython example code.
UPDATE - I've written a more generic example (plus a link to a zip file containing the entire VS2008 project) as entry on my blog here.
Sorry, I am so late to the game, but here is how I have integrated IronPython into a C++/cli app in Visual Studio 2008 - .net 3.5. (actually mixed mode app with C/C++)
I write add-ons for a map making applicaiton written in Assembly. The API is exposed so that C/C++ add-ons can be written. I mix C/C++ with C++/cli. Some of the elements from this example are from the API (such as XPCALL and CmdEnd() - please just ignore them)
///////////////////////////////////////////////////////////////////////
void XPCALL PythonCmd2(int Result, int Result1, int Result2)
{
if(Result==X_OK)
{
try
{
String^ filename = gcnew String(txtFileName);
String^ path = Assembly::GetExecutingAssembly()->Location;
ScriptEngine^ engine = Python::CreateEngine();
ScriptScope^ scope = engine->CreateScope();
ScriptSource^ source = engine->CreateScriptSourceFromFile(String::Concat(Path::GetDirectoryName(path), "\\scripts\\", filename + ".py"));
scope->SetVariable("DrawingList", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingList::typeid));
scope->SetVariable("DrawingElement", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingElement::typeid));
scope->SetVariable("DrawingPath", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingPath::typeid));
scope->SetVariable("Node", DynamicHelpers::GetPythonTypeFromType(AddIn::Node::typeid));
source->Execute(scope);
}
catch(Exception ^e)
{
Console::WriteLine(e->ToString());
CmdEnd();
}
}
else
{
CmdEnd();
}
}
///////////////////////////////////////////////////////////////////////////////
As you can see, I expose to IronPython some objects (DrawingList, DrawingElement, DrawingPath & Node). These objects are C++/cli objects that I created to expose "things" to IronPython.
When the C++/cli source->Execute(scope) line is called, the only python line
to run is the DrawingList.RequestData.
RequestData takes a delegate and a data type.
When the C++/cli code is done, it calls the delegate pointing to the
function "diamond"
In the function diamond it retrieves the requested data with the call to
DrawingList.RequestedValue() The call to DrawingList.AddElement(dp) adds the
new element to the Applications visual Database.
And lastly the call to DrawingList.EndCommand() tells the FastCAD engine to
clean up and end the running of the plugin.
import clr
def diamond(Result1, Result2, Result3):
if(Result1 == 0):
dp = DrawingPath()
dp.drawingStuff.EntityColor = 2
dp.drawingStuff.SecondEntityColor = 2
n = DrawingList.RequestedValue()
dp.Nodes.Add(Node(n.X-50,n.Y+25))
dp.Nodes.Add(Node(n.X-25,n.Y+50))
dp.Nodes.Add(Node(n.X+25,n.Y+50))
dp.Nodes.Add(Node(n.X+50,n.Y+25))
dp.Nodes.Add(Node(n.X,n.Y-40))
DrawingList.AddElement(dp)
DrawingList.EndCommand()
DrawingList.RequestData(diamond, DrawingList.RequestType.PointType)
I hope this is what you were looking for.
If you don't need .NET functionality, you could rely on embedding Python instead of IronPython. See Python's documentation on Embedding Python in Another Application for more info and an example. If you don't mind being dependent on BOOST, you could try out its Python integration library.