Setting Sqlite ThreadingMode when using sqlite-net + async - c#

I'm trying to set Sqlite ThreadMode to Serialized in my Xamarin.iOS project. Using classic Sqlite, one finds this method on the connection class:
SqliteConnection.SetConfig(SQLiteConfig.Serialized);
However I'm using sqlite-net (+async) and can't find a way to set this configuration property.
Any suggestions?

Ok, I had to update SQLite-Net (and SQLite-Net-PCL etc) to 2.5.
Then this option can be accessed through the platform specific implementation:
public Repository(IPlatform platform)
{
_platform = platform;
_platform.SqlitePlatform.SQLiteApi.Config(ConfigOption.Serialized);
_db = new SQLiteAsyncConnection(() =>
new SQLite.Net.SQLiteConnectionWithLock(
_platform.SqlitePlatform,
new SQLite.Net.SQLiteConnectionString(_platform.DatabasePath, true)));
}

Related

Can't upgrade settings when updating a WPF Desktop Bridge Universal app

My app is written in WPF C# and I export it as Universal app using MSIX Application Project straight from Visual Studio.
I just can't get the settings to persist between updates. I'm using the following code in the MainWindow_Loaded event:
Settings.Default.Upgrade();
Settings.Default.Save();
Settings.Default.Reload();
I tried keeping assembly information versions the same and just increment the version in the appx.manifest but it doesn't work.
I've noticed that each time the app updates it creates a new uniquely named parent settings folder (with a new hash every time) and the subfolder name is the version from the assembly. The folder structure is like this:
App.exe_Url_dfvfmfjs1qo33zsag1ay5w1s0rwg0u53/0.2.10.0/user.config
App.exe_Url_tazrvujdga5ujjarnahpkoscv5zbkgl0/0.2.10.0/user.config
I believe it might have to do with the fact that it keeps generating new hashes instead of just placing the new version as a subfolder and that's why Upgrade doesn't do anything.
The only information I've found so far is to use Settings.Default.Upgrade()
How am I supposed to transfer the old version settings to the new version when my universal desktop bridge app updates?
As far as I researched these settings do not transfer to UWP updates using Desktop Bridge. So I started using UWP's native ApplicationData.Settings
As a workaround I created 2 methods to update the newly created WPF settings using LocalSettings which is the UWP equivalent and vice versa. UWP's LocalSettings transfer on update. I call Update() when I save my WPF settings and I call Load() when the application starts. It works.
Here's the code, only caveat I've found so far is you should use the basic types as these methods will fail transferring something like a List<string> or a StringCollection, for that I'm using serialization, although you can always adapt them to do that too:
static class UWPSettings
{
public static void Update()
{
if (Startup.IsUniversalPlatform)
{
foreach (SettingsPropertyValue value in Properties.Settings.Default.PropertyValues)
{
ApplicationData.Current.LocalSettings.Values[value.Name] = value.PropertyValue;
}
}
}
public static void Load()
{
if (Startup.IsUniversalPlatform)
{
foreach (var setting in ApplicationData.Current.LocalSettings.Values)
{
foreach (SettingsPropertyValue s in Properties.Settings.Default.PropertyValues)
{
if (s.Name == setting.Key)
{
s.PropertyValue = setting.Value;
}
}
}
Properties.Settings.Default.Save();
}
}
}

Talking to SQL Integration Services with C#

I want to import and export SSIS packages (.DTSX files) on a SQL Server with a C# program. I found information on an "Integration Services" class, but I'm not seeing any methods related to exporting or importing packages. Is this the correct class? If not, where should I be looking?
https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.integrationservices.integrationservices?view=sqlserver-2017
public ref class IntegrationServices
It turned out to be what user #SMor suggested, the Application class of the Microsoft.SqlServer.Dts.Runtime namespace.
https://learn.microsoft.com/en-us/sql/integration-services/run-manage-packages-programmatically/enumerating-available-packages-programmatically?view=sql-server-2017
These two objects give you most of what you need:
Application ssisApplication;
PackageInfos sqlPackages;
I can get the list of packages with that class. Now I'm just working on how to actually do the imports/exports.
Sample code for Package export from SQL to File.
using Microsoft.SqlServer.Dts.Runtime;
public void pkgExtract()
{
// ...
Application app = new Application();
var events = new PackageEvents();
Package package = app.LoadFromSqlServer(packageName, server, etl.UserName, etl.Password, events);
// ...
string Package_File = #"C:\\Temp\ExportPkg.dtsx"
app.SaveToXml(Package_File, package, null);
}
For reverse directrion - you can use LoadPackage and SaveToSQLServer methods.

EntityFrameworkCore.PostgreSQL Transform point

Is there a way to Transform a point to another SRID using EntityFrameworkCore?
previously I used ST_Transform(ST_GeomFromText(#coord,4326),32661)
My current code looks like this
var postgisGeometry = new PostgisPoint(lon, lat) {SRID = 4326};
The SRID of the coord is 4326 and needs to become 32661
This is done for backwards compatibility reasons and there is no option converting the database to another SRID
Is there a geometry library or a PostGIS EntityFrameworkCore method to transform a point to another SRID
The release version Npgsql.EntityFrameworkCore.PostgreSQL Entity Framework Core provider for PostgreSQL does not support spatial types.
The good news is that spatial types support and support for some spatial operations SQL translations are already available as a pre-release candidate.
If you want to use these libraries, you need to also use the pre-realease candidate version of Entify Framework Core.
First, uninstall your existing entity framework or npgsql packages.
One of the packages needed (GeoAPI) is not available in the standard NuGet source so we are gonna use the myget.org source.
To use it, you need to add a new NuGet source in Visual Studio by going to Tools -> Options -> NuGet Package Manager -> Packages Sources
Create a new source and name it myget.org and use the following URL in the source text field:
https://www.myget.org/F/imageprocessor/api/v3/index.json
Remember to click on update to save the changes, otherwise they are not saved (weird, I know).
To add the required packages, use the Package Manager Console (View -> Other Windows -> Package Manager Console) and select myget.org from the Package Source drop down, then, execute the following commands:
Install-Package Microsoft.EntityFrameworkCore -Version 2.1.0-rc1-final
Install-Package GeoAPI -Version 1.7.5-pre024
Install-Package Npgsql -Version 4.0.0-rc1
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL -Version 2.1.0-rc1
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite -Version 2.1.0-rc1
Once your packages are installed, in your DbContext class, override OnConfiguring to add the UseNetTopologySuite option:
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseNpgsql("Host=localhost;Database=your_database;
Username=your_user;Password=your_password",
o => o.UseNetTopologySuite());
}
To make sure that the extension is supported by your database add the following to your DbContext:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasPostgresExtension("postgis");
}
Now you should be able to use PostgreSql spatial types and translate some operations to SQL, (e.g. ST_Area, ST_Contains, ST_As_Text, etc.).
The whole list of supported operations and how to use them in your EF queries is available here: http://www.npgsql.org/efcore/mapping/nts.html#operation-translation
Unfortunately ST_Transform or ST_Project do not seem to be supported as of now, but there is a link in the Website above where you can contact the developers and request them to be added.
In the meantime, you can use GDAL to transform the projection of your coordinates.
Install the package:
Install-Package Gdal.Core -Version 1.0.0
This package provides a multi-platform wrapper for GDAL for .NET core so you need to install the libraries and they should be accessible by your program.
You can find binaries for Windows and Linux here: https://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries
If you are using Windows you can use the following installer: http://download.osgeo.org/osgeo4w/osgeo4w-setup-x86_64.exe
Just select "Express Desktop Install" and GDAL in the "Select Packages" window.
By default the needed libraries are installed in C:\OSGeo4W64\bin.
You need to add this folder to your system path and restart Visual Studio.
By the way, to convert the coordinates, from all the libraries in C:\OSGeo4W64\bin I think you only need proj.dll so may be you can include this in your project (make sure it is copied to the output of your project) and then it should work and you don't need to install GDAL.
Here is an example of how to use it for the coordinate systems provided in your question:
using System;
using NetTopologySuite.Geometries;
using OSGeo.OSR;
using OSGeo.OGR;
namespace YourNamespace
{
public class SomeLocation
{
public int Id { get; set; }
public string Name { get; set; }
public Point Location { get; } = new Point(40.1234, 1.4321) { SRID = 4326 };
public Point LocationUpsNorth { get { return Wgs84ToWgs84UpsNorth(Location); } }
private static NetTopologySuite.Geometries.Point Wgs84ToWgs84UpsNorth(Point location)
{
if (location.SRID != 4326)
throw new Exception("Unsupported coordinate system: " + location.SRID);
OSGeo.OSR.SpatialReference wgs84Src = new OSGeo.OSR.SpatialReference("");
wgs84Src.ImportFromProj4("+proj=longlat +datum=WGS84 +no_defs");
OSGeo.OSR.SpatialReference stereoNorthPoleDest = new OSGeo.OSR.SpatialReference("");
stereoNorthPoleDest.ImportFromProj4("+proj=stere +lat_0=90 +lat_ts=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs");
OSGeo.OSR.CoordinateTransformation ct = new OSGeo.OSR.CoordinateTransformation(wgs84Src, stereoNorthPoleDest);
double[] point = new double[3];
point[0] = location.X;
point[1] = location.Y;
point[2] = location.Z;
ct.TransformPoint(point);
return new Point(point[0], point[1]);
}
}
}
Result
Input: POINT (40.1234 1.4321)
Output: POINT (9944217.1796359234 -7426244.9918885585)
References:
http://www.npgsql.org/efcore/mapping/nts.html
http://spatialreference.org/ref/epsg/32661/
https://github.com/NetTopologySuite/
https://github.com/NetTopologySuite/ProjNet4GeoAPI/blob/develop/ProjNet.Tests/CoordinateTransformTests.cs
https://gis.stackexchange.com/questions/61541/searching-for-c-code-to-convert-from-utm-to-wgs1984-and-back#61574

Get value of version out of project.json

In a DNX application, which uses a "project.json" file, is there a way to read the value of the "version" property out of the "project.json" file?
I'm writing a library that writes something to the current HTTP response and I would like to show the version of the application in there.
Any help on how this can be done is highly appreciated.
If you set the version attribute during build (or in any other way) you can do this like that:
using System;
using System.Reflection;
[assembly:AssemblyVersionAttribute("1.2.3")]
namespace Test
{
class Program
{
public static void Main()
{
var assembly = typeof(Program).GetTypeInfo().Assembly;
var name = assembly.GetName();
Console.WriteLine($"{name.Name}: {name.Version}");
}
}
}
I did it using the new dotnet cli which is replacing dnx but it should work with dnx dnxcore50 as well.
Are you writing a Class Library or an ASP.NET application?
If a class Library, you could copy the version string to a resource file that you read in during run-time to grab the version. It's kind hard to do this sort of thing with class libraries since you don't get the beauty of a Startup and IoC.
If ASP.NET, then just add a version into your appsettings.json configuration (or a custom json file to store settings) and read it in at startup: http://docs.asp.net/en/latest/fundamentals/configuration.html
Multipe ways of doing this if you are running in a the web application, not a class library.
First way custom attributes data (should check if attribute is available):
this.GetType().Assembly.GetCustomAttributesData()
.First(x => x.AttributeType.FullName == "System.Reflection.AssemblyInformationalVersionAttribute")
.ConstructorArguments[0];
Second way
var name = this.GetType().AssemblyQualifiedName;
name = name.Substring(name.IndexOf("Version=") + 8);
var verion = name.Substring(0, name.IndexOf(", "));

Can't find Foundation.NSJavaScriptExtension class in app extension

I'm developping an app extension for iOS with Xamarin Studio. I tried to use a class that is supposed to be in the Foundation API, but I can't find it. The class is called NSJavaScriptExtension.
I tried to access it by specifying the namespace:
Foundation.NSJavaScriptExtension
I also tried to use the using directive:
using Foundation;
When I tried compiling it, I got the following error message:
Error CS0103: The name 'NSJavaScriptExtension' does not exist in the
current context (CS0103)
This is really strange because the Xamarin documentation says that it exists.
Here's my code :
// Create an extension Item
var extensionItem = new NSExtensionItem ();
// Create a Final value Dictionary
var finalize = new NSMutableDictionary ();
finalize.Add (NSJavaScriptExtension.FinalizeArgumentKey, new NSString ("{bgColor:red}")); // <- here
// Create an item provider and attach it to the extension item
var provider = new NSItemProvider (finalize, MobileCoreServices.UTType.PropertyList);
extensionItem.Attachments = new NSItemProvider[]{ provider };
// Send results to the calling Host App
ExtensionHelper.ExtensionContext.CompleteRequest (new NSExtensionItem[]{ extensionItem },
(completionHandler) => {
return;
});
The type NSJavaScriptExtension was added in XI 9.0. The easiest way to get it is to upgrade to the latest stable release, which can target older iOS versions as well.
If you cannot update then you can load any constant manually at runtime, like:
using Foundation;
using ObjCRuntime;
...
IntPtr foundation = Dlfcn.dlopen (Constants.FoundationLibrary, 0);
NSString FinalizeArgumentKey = Dlfcn.GetStringConstant (foundation.Handle, "NSExtensionJavaScriptFinalizeArgumentKey");

Categories

Resources