GetSystemPowerStatus for windows phone 8 - 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

Related

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.

Could not open database file Windows Store App 8.1

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);

How to get the "argument" data from a LaunchApp NFC tag in the application. WP8

I created a LaunchApp Tag, and its working fine, launching my Testapp, but with my LaunchApp tag im giving an argument too ("TestData"). So here comes my problem, how can i easily get this argument in my windows phone application? For example i just want to give the string TestData to a textblock in my app. Is it possible somehow ? My launchapp tag is a basic windows launchApp record type.
it looks like this:
Record type: windows.com/LaunchApp
Arguments: 'testData'
Platform: WIndowsPhone
App ID: {734sd....}
In the OnNavigatedTo function you can access NavigationContext.QueryString to get ms_nfp_launchargs value. This value will be your argument
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string parameter = string.Empty;
if (NavigationContext.QueryString.TryGetValue("ms_nfp_launchargs", out parameter))
{
MessageBox.Show("Congratulation\nYou launch application with a NFC tag.\nParamaters : "+ parameter);
NavigationContext.QueryString.Remove("ms_nfp_launchargs");
}
}
edit
you can find a sample in this article

Can anybody explain the concept of pluggable adapter to me with good example?

Can anybody explain the concept of pluggable adapter to me with good example?
From what I understood from a quick reading of Google results, a pluggable adapter is an adapter that isn't hard-coded against a specific adaptee. On the surface (the adapter's own interface), it's all the same but it can adapt to different adaptees with different interfaces. I found this thread pretty explanatory:
Basically, it allows you to put in an
adapter when the adaptee (receiver)
protocol is not known at compile time
by using reflection. When you create
the adapter instance, you pass it the
name of the adaptee's method to call,
and also any metadata that's necessary
to translate input types. When the
adapter receives a method call of the
target interface, it uses reflection
to call the corresponding method
specified on the adaptee.
And this:
The main responsibility of the Viewer
is to populate a widget from a domain
model without making any assumptions
about domain itself. JFace viewer uses
the Delegating Objects mechanism in
Pluggable Adapter Pattern to implement
the above requirement.
Think of it as a facehugger from Alien; when it hugs a face, all you see is the slimy back of the facehugger. You can poke it with a stick and try to pry off its arms (the adapter interface). But it basically can hug the face of any human (the adaptee), regardless of the face features. Maybe I'm pushing it a bit, but, hey, I love Alien.
You can read this article about adapter/pluggable pattern:
Table of content in this article:
* 1 Design Patterns
* 2 Intent of Adapter
* 3 Motivation
* 4 Structure
* 5 Applicability
* 6 Consequences
* 7 Implementation
o 7.1 Known Uses and Sample Code
o 7.2 Related Patterns
* 8 Conclusions
* 9 Appendix
o 9.1 References
o 9.2 Glossary
Quote:
Smalltalk introduced the concept of a
"pluggable adapter" to describe
classes with built-in interface
adaptation. This interesting concept
allows for classes to be introduced
into existing systems that might
expect different interfaces to the
class. This technique can help promote
class reuse across modules and even
projects.
Here is a small example:
We have two classes - Foo & Boo that outputs some string to console. Adapter class can adapt methods from both classes to provide interface (SaySomething) required by client. Note that there is no dependency on interface name - we can easily adapt both SayHey and Bark methods.
class Foo
{
public static void SayHey() { Console.WriteLine("Hey!"); }
}
class Boo
{
public static void Bark() { Console.WriteLine("Woof!"); }
}
class Adapter
{
public Action SaySomething { get; private set;} // "pluggable" adapter
public Adapter(Action saySomethingAction)
{
SaySomething = saySomethingAction;
}
}
class Program
{
static void Main(string[] args)
{
(new Adapter(Foo.SayHey)).SaySomething();
(new Adapter(Boo.Bark)).SaySomething();
}
}
A distinguish Feature of the Pluggable Adapter is that the method called by the client and the method existing in the interface can be different.
interface Ilegacy
{
float calculate(int a, int b);
}
class Legacy : Ilegacy
{
public float calculate(int a, int b)
{
return a * b;
}
}
class Adapter
{
public Func<int, int, float> legacyCalculator;
public Adapter()
{
this.legacyCalculator = new Legacy().calculate;
}
}
class Client
{
static void Main()
{
float result = new Adapter().legacyCalculator(5, 6);
}
}
This can normally acheived with the use of delegate,Func or Action in C#