Could not open database file Windows Store App 8.1 - windows-store-apps

I'm trying to implement a database in my Windows 8.1 Modern UI application.
I made this for a Windows Phone 8.1 app successfully, but it doesn't work in a new Windows 8.1 app.
I got a SQLiteException with message Could not open database file: MyAppBase.db (CannotOpen) when i instanciate SQLiteConnection
public static DatabaseHelper Instance
{
get
{
if (_instance == null)
{
_instance = new DatabaseHelper();
}
return _instance;
}
}
public DatabaseHelper()
{
_connection = new SQLiteConnection(DATABASE_NAME);
_connection.CreateTable<UserEntity>();
}
I follow this steps :
Added 'sqlite-net' to Nuget reference, Checked 'SQLite for Windows Runtime (Windows 8.1)' and 'Microsoft Visual C++ 2013 Runtime Package for Windows' on project references, Targetted build to x86.
How can i get this working ?

SQLite needs a path to create a DB not just a db name
try something like this
string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, DATABASE_NAME);
_connection = new SQLite.SQLiteConnection(path)
Hope this helps

Use
string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, databasePath);

Related

Specify file provider for RazorViewEngine in ASP.NET Core 6.0

I'm having a solution with an ASP.NET Core 6 MVC application project and a WebJob (console application)
Both applications are using a common library project where I have IRazorViewToStringRenderer service with views. I want to reuse this service in both applications, WebApp and WebJob. My solution is based on this sample https://github.com/aspnet/Entropy/blob/master/samples/Mvc.RenderViewToString/Program.cs
Here is how I use it:
var viewToStringEngine = ServiceProvider.GetService<IRazorViewToStringRenderer>();
string htmlContent = await viewToStringEngine.RenderToStringAsync<MyView>("~/Views/MyView.cshtml", new MyView());
The problem is RazorViewEngineOptions doesn't have anymore the option to specify the file provider ( in ASP.NET Core 6 )
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(fileProvider);
});
IRazorViewToStringRenderer service is working fine when is called from the Web App, but is not working from the WebJob. It is only working if the WebJob services contains an IWebHostEnvironment with the ApplicationName as the name of the project where IRazorViewToStringRenderer is implemented, otherwise the views cannot be found.
How to specify file provider for the RazorViewEngine ? ( github sample )
WebJob service configuration:
private static ServiceCollection ConfigureServices()
{
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(Configuration);
var applicationEnvironment = PlatformServices.Default.Application;
services.AddSingleton(applicationEnvironment);
services.AddSingleton<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>(new WebJobHostEnvironment
{
ApplicationName = Assembly.GetEntryAssembly().GetName().Name,
//ApplicationName = typeof(IRazorViewToStringRenderer).Assembly.GetName().Name,
});
var listener = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticListener>(listener);
services.AddSingleton<DiagnosticSource>(listener);
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.AddSingleton<ILoggerFactory, LoggerFactory>(sp => new LoggerFactory());
services.AddMvcCore().AddRazorViewEngine();
services.AddCommonRazorEngine(Configuration);
return services;
}
RazorServiceCollectionExtension.cs
public static class RazorServiceCollectionExtension
{
public static void AddCommonRazorEngine(this IServiceCollection services, IConfiguration configuration)
{
//var fileProvider = new EmbeddedFileProvider(typeof(RazorViewToStringRenderer).Assembly);
// FileProviders property is not available anymore
services.Configure<RazorViewEngineOptions>(options =>
{
//options.FileProviders.Add(fileProvider);
});
services.AddScoped<IRazorViewToStringRenderer, RazorViewToStringRenderer>();
}
}
Edit
For others searching a similar solution, I updated my github sample
I encountered this problem myself, and it appears that the functionality has been moved to an external package. I was able to work around this by following the instructions located here and then amending them for my purposes:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-compilation?view=aspnetcore-6.0&tabs=visual-studio
I.e. install the package: Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
Then you can change the appropriate file provider by using the code:
services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{
options.FileProviders.Clear();
options.FileProviders.Add(fileProvider);
});

Saving Data locally on a .net Standard app

I want to serialize data on my .net Standard app into a local file and I would like to avoid sqlite if possible.
The standard recommendation for cross plattform app seems to have been PCL Storage, but according to this link, PCL Storage is not maintained anymore, offers no .net Standard support and the alternative PCLExt is not mature.
Can you tell me if it is possible to simply serialize my data e.g. with json?
Tank you very much!
You do not have complete access over the OS's filesystem and platform-specific features like Android's ContentResolver, but for basic file read/write within your app's sandbox (or external filesystem if your app has access to it) .NetStandard 2.0 works fine, and thus works for storing and retrieving text-based files for serializing/deserializing Json.
Example, if you have a Xamarin.Forms based solution and add a .NetStandard 2.0 library project to the solution and also add Newtonsoft.Json to it. You could create these functions in it:
.NetStandard library functions:
public static class Common
{
public static void WriteFile(string fileName, Tuple<string, string> obj)
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
File.WriteAllText(Path.Combine(path, fileName), JsonConvert.SerializeObject(obj));
}
public static Tuple<string, string> ReadFile(string fileName)
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
return JsonConvert.DeserializeObject<Tuple<string, string>>(File.ReadAllText(Path.Combine(path, fileName));
}
}
Now in your Xamarin.Forms project (.NetStandard * Shared project), reference the project/library you created you could do something like this:
ReadWriteCommand = new Command(() =>
{
var someObj = Tuple.Create("Stack", "Overflow");
Common.WriteFile("SushiHangover.txt", someObj);
var readSomeObj = Common.ReadFile("SushiHangover.txt");
if ((someObj.Item1 != readSomeObj.Item1) || (someObj.Item2 != readSomeObj.Item2))
throw new Exception();
});

Xamarin Forms: ModernHttpClient errorhandling in PCL

My app connects to an api which requires an HTTPS-connection.
ModernHttpClients (NativeMessageHandler) works fine until an exception is thrown...
When there is no wifi available, an UnknownHostException is thrown on Android. Is it possible to make a catch that works on both Android and iOS? UnknownHostException is in the Java.Net library which can't be used in the iOS project.
You can use Xam.Plugin.Connectivity NuGet Package to Check Network Connectivity In Xamarin.Forms using following code
if (CrossConnectivity.Current.IsConnected) {
// your logic...
} else {
// write your code if there is no Internet available
}
OR
Refer http://www.c-sharpcorner.com/blogs/how-to-check-network-connectivity-in-xamarinforms
You can use the ConnectivityPlugin in your shared Xamarin Forms code to check for an internet connection before doing your request.
Personally I'm using a cross platform interface to handle network errors. You can for instance have something like (using MvvmCross in this example):
try
{
var client = new HttpClient();
var result = await client.GetAsync("http://some-url.com");
}
catch (Exception e)
{
var platformErrorChecker = Mvx.Resolve<IPlatformNetworkError>();
if (platformErrorChecker.IsNetworkError(e))
{
// Handle network error
}
else
{
// Other exception, just throw
throw;
}
}
And a service defined as:
public interface IPlatformNetworkError
{
bool IsNetworkError(Exception e);
}
Which you implement on each platform specifically, or only where needed. This is a simple example of course, you can have each platform provide more information about their specific network errors.

How to only use IOC container from MVVMCross

I'm working on a existing Windows Phone project and want to use the IOC container from MVVMCross, but not the other extra features (yet).
I installed MVVMCross.Core 4.x and try to use 'ConstructAndRegisterSingleton' from the App() constructor of the Windows app, but it throws an Null ref exception.
Tried to find any bootstrapper, setup or initialization for MVVMCross but can't find any in the new 4.x core.
Anyone any idea?
Found it.... and it seems to work.
Just get MVVMCross.Core from Nuget and create a setup like:
internal static class Setup
{
public static void InitializeIoc()
{
CreateIocProvider();
// Register all services
Mvx.ConstructAndRegisterSingleton<ILoudnessLimitsRegulator, LoudnessLimitsRegulator>();
}
private static void CreateIocProvider()
{
// Ioc options
var options = new MvxIocOptions();
// initialize the IoC registry, then add it to itself
var iocProvider = MvxSimpleIoCContainer.Initialize(options);
Mvx.RegisterSingleton(iocProvider);
}
}

GetSystemPowerStatus for windows phone 8

I saw the winbase.h (WINAPI) file (kernel32.dll) in windows phone 8 sdk which has the function :
GetSystemPowerStatus which will return the battery
status(SYSTEM_POWER_STATUS)
.
Question is this throws and exception on the emulator, not tested on handset (waiting to get one)
I have used
[DllImport("Kernel32")]
private static extern Boolean GetSystemPowerStatus( SystemPowerStatus sps );
the code complies but throws exception at runtime.
any idea will this work on handset, or this is not supported at all for windows phone 8 ?
As AnderZubi has said this is not a supported Win32 API on Windows Phone 8. However there is an equivalent WinRT API you can call from your native C/C++ code. This is very similar to the C# API Martin posted.
If you are already in C/C++ using the WinRT version may save you needing to bridge between C++ and C#. If you are starting out a new app which will just use XAML/C# then Martin's answer will be simpler.
For example:
int WindowsPhoneRuntimeComponent::GetBatteryRemainingPercent()
{
auto battery = Windows::Phone::Devices::Power::Battery::GetDefault();
int remainingPercent = battery->RemainingChargePercent;
return remainingPercent;
}
If you just want to access battery info and the bool property, if phone is on charger or not, you can use this:
using Microsoft.Phone.Info;
using Windows.Phone.Devices.Power;
namespace Core.Helpers
{
public class BatteryHelper
{
public static int BateryLevel
{
get
{
return Battery.GetDefault().RemainingChargePercent;
}
}
public static bool IsCharging
{
get
{
return DeviceStatus.PowerSource == PowerSource.External;
}
}
}
}
GetSystemPowerStatus is not in the list of supported Win32 APIs for Windows Phone 8:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj662956(v=vs.105).aspx