Using licenses to restore purchase after reinstallation - c#

My app needs a button to 'restore previous purchases'
Here's my code which is triggered when button is pressed
#if DEBUG
var receipt = await CurrentAppSimulator.GetAppReceiptAsync();
#else
var receipt = await CurrentApp.GetAppReceiptAsync();
#endif
var xmlRcpt = new XmlDocument();
xmlRcpt.LoadXml(receipt);
XmlNodeList xmlProductIdNodes = xmlRcpt.SelectNodes("/Receipt/ProductReceipt/#ProductId");
if (xmlProductIdNodes.Count == 0)
{
try
{
var md = new MessageDialog("Unable to verify purchase");
await md.ShowAsync();
}
catch { }
return;
}
foreach (var node in xmlProductIdNodes)
{
if (node.InnerText == "Product1")
{
//Enable feature 1
}
else if (node.InnerText == "Product2")
{
//Enable feature 2
}
}
The problem is after publishing the app, "unable to verify purchase" is being hit. So is there something wrong with the xml parsing (this is my first time with xml) Or something else?
App targets windows phone 8.1 xaml
UPDATE 1: Somehow I feel, the problem is with the understanding of how store updates licenses. I tried a different approach since my only aim is to check whether a product is purchased or not. I submitted a beta app with this code using a button:
var receipt = CurrentApp.LicenseInformation.ProductLicenses;
if (receipt["Product1"].IsActive)
{
try
{
var md = new MessageDialog("Product 1 enabled", "Success!");
await md.ShowAsync();
}
catch { }
return;
}
else
{
try
{
var md = new MessageDialog("Could not verify purchase");
await md.ShowAsync();
}
catch { }
}
Now the problem is, first time "could not verify" is hit. Then, I make the free purchase of Product1. Product1 verifies successfully. This is as expected. Now if I uninstall the app and reinstall, again the same behaviour i.e. the could not verify purchase.
How can I make sure that the licenseinformation gets the most recent information even after reinstall? Or anyway to trigger a refresh?
Will LoadListingInformationAsync() refresh the license?

Related

Problems with removable storage Hololens 2, unity and xamarin uwp

I'm relatively new to software development for the Hololens 2 and have a pretty big problem I've been messing around with for a long time and I'm slowly running out of ideas.
My project looks like this. I've written a Unity application to capture data and store it in a database (sqlite). A Xamarin.Forms UWP application is supposed to take the data from the database and use it to paint charts for better visualisation. The big problem is, both apps need to be able to access the same database on the Hololens 2. I thought that I could be the database on a usb stick and both apps could access the usb stick. In the Xamarin app and in the Unity app "removable storage" is enabled. In the Xamarin App I have made the file extension known under Appmanifest declaration. I am trying to get the connection with the following commands:
namespace ARScoliosis.XamarinApp.UWP.Services
{
public class DatabasePath : IDatabasePath
{
public async Task<string> GetLocalFilePath()
{
var messageDialog = new MessageDialog("No Usb connection has been found.");
StorageFolder externalDevices = KnownFolders.RemovableDevices;
if(externalDevices == null)
{
messageDialog.Commands.Add(new UICommand("No Devices", null));
}
StorageFolder usbStick = (await externalDevices.GetFoldersAsync()).FirstOrDefault(); <---According to debugging it stops here and jumps to optionsBuilder.UseSqlite($"Filename={databasePath}");
if (usbStick == null)
{
messageDialog.Commands.Add(new UICommand("No UsbStick", null));
}
var usbStickFolder = await usbStick.CreateFolderAsync("DB", CreationCollisionOption.OpenIfExists);
if (usbStickFolder == null)
{
messageDialog.Commands.Add(new UICommand("No Folder", null));
}
var file = await usbStickFolder.CreateFileAsync("Database.db", CreationCollisionOption.OpenIfExists);
if(file == null)
{
messageDialog.Commands.Add(new UICommand("No File", null));
}
//var success = await Launcher.LaunchFileAsync(file);
return file.ToString();
}
My dbcontext file looks something like this:
namespace XamarinApp.Authentication
{
public partial class DBContext : DbContext
{
public DBContext()
{
this.Database.EnsureCreated(); <--- Microsoft.Data.Sqlite.SqliteException: "SQLite Error 14: 'unable to open database file'."
this.Database.Migrate();
}
public virtual DbSet<ItemData> ItemDatas { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var databasePath = DependencyService.Get<IDatabasePath>().GetLocalFilePath();
optionsBuilder.UseSqlite($"Filename={databasePath}");
}
}
namespace XamarinApp.Helpers
{
public interface IDatabasePath
{
Task<string> GetLocalFilePath();
}
}
Unfortunately this code does not find the Usb stick on the Hololens, i think. When I look in file explorer, I see the stick with all its data. In the Unity App, the stick is also not found, although I use the same code here, only slightly modified.
Does anyone know where my error lies, why I can't access the USB stick with either of the two apps? Has anyone tried something similar and knows how to do it?
i would like to thank you in advance for your help.
Thank you very much.
****Hi Hernando - MSFT,
Please excuse my late reply. i had somehow forgotten. I have found a way where I can find my database on the usb stick.
public static async Task<string> GetUsbStick()
{
StorageFolder UsbDrive = (await Windows.Storage.KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault();
if (UsbDrive == null)
{
throw new InvalidOperationException("Usb Drive Not Found");
}
else
{
IReadOnlyList<StorageFile> FileList = await UsbDrive.GetFilesAsync();
var Path = UsbDrive.Path.Replace('\\','/');
foreach (StorageFile File in FileList)
{
var DBFound = File.Name.Contains("test.db");
if (DBFound == true)
{
return Path + File.Name;
}
}
throw new InvalidOperationException("DataBaseNotFound");
}
}
There I get the exact path for the database output. Only that somehow brings nothing. I cannot open it in the next step. "Sqlite cant open database" it says.
public static async Task<int> Init()
{
try
{
DatabasePath = await GetUsbStick();
StrConnDatabase = "Data Source" + "=" + DatabasePath + ";Mode=ReadWrite;";
}
catch (Exception io)
{
IsInit = false;
throw new InvalidOperationException(io.Message);
}
finally
{
//Try to Open Database to Read
using (var db = new Microsoft.Data.Sqlite.SqliteConnection(StrConnDatabase))
{
try
{
db.Open(); //<- here it breaks off
db.Close();
IsInit = true;
}
catch (Exception io)
{
throw new InvalidOperationException(io.Message);
}
}
}
return 1; // Succes
}
What could be the reason that this does not work?
is there a way to create a working copy within the app, which is then written back to the usb stick?
KnownFolders.RemovableDevices doesn't be supported on the HoloLens, for more information please see:Known folders. It is recommended to take a try at File pickers to pick one file manually.

Android Notification Sound Causes Media Volume to Duck (Lower) & It Never Comes Back

I just converted one of my apps to target Android API 9 (was targeting API 8); now when notifications are sent out, the volume of media is lowered and never comes back to full volume.
The app uses WebView to play media files. This was not happening prior to targeting API 9. I had to convert the app into level 9 so that I could upload to the Google Play Store. I am running a Samsung S7 which was originally designed for API level 6 (with the OS upgraded to 8.0), not sure if that has something to do with the issue. Another detail is that I use Xamarin.Android for development, not sure if that matters either.
Additionally, I forced the notifications to play a blank sound (a very short[couple ms] blank mp3) in the same build that I converted the app to target API 9:
var channelSilent = new Android.App.NotificationChannel(CHANNEL_ID, name + " Silent", Android.App.NotificationImportance.High)
{
Description = description
};
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build()
//blank is blank mp3 file with nothing in it, a few ms in duration
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3")
channelSilent.SetSound(uri, alarmAttributes);
...so it could also be the blank sound that is causing the ducking to malfunction, not the API change. Is there something to do with notification sound ducking that could be causing the issue? Is there any other way to mute a notification with Xamarin.Android other than playing a blank sound? That is one route I think would be worth trying to fix this issue.
Here is the code I am using to generate notifications:
private static List<CustomNotification> _sentNotificationList = new List<CustomNotification>();
private static NotificationManagerCompat _notificationManager;
public async void SendNotifications(List<CustomNotification> notificationList)
{
await Task.Run(() =>
{
try
{
var _ctx = Android.App.Application.Context;
if (_notificationManager == null)
{
_notificationManager = Android.Support.V4.App.NotificationManagerCompat.From(_ctx);
}
if (notificationList.Count == 0)
{
return;
}
int notePos = 0;
foreach (var note in notificationList)
{
var resultIntent = new Intent(_ctx, typeof(MainActivity));
var valuesForActivity = new Bundle();
valuesForActivity.PutInt(MainActivity.COUNT_KEY, _count);
valuesForActivity.PutString("URL", note._noteLink);
resultIntent.PutExtras(valuesForActivity);
var resultPendingIntent = PendingIntent.GetActivity(_ctx, MainActivity.NOTIFICATION_ID, resultIntent, PendingIntentFlags.UpdateCurrent);
resultIntent.AddFlags(ActivityFlags.SingleTop);
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build();
//I am playing this blank sound to prevent android from spamming sounds as the notifications get sent out
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3");
//if the notification is the first in our batch then use this
//code block to send the notifications with sound
if (!_sentNotificationList.Contains(note) && notePos == 0)
{
var builder = new Android.Support.V4.App.NotificationCompat.Builder(_ctx, MainActivity.CHANNEL_ID + 1)
.SetAutoCancel(true)
.SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
.SetContentTitle(note._noteText) // Set the title
.SetNumber(1) // Display the count in the Content Info
.SetSmallIcon(Resource.Drawable.bitchute_notification2)
.SetContentText(note._noteType)
.SetPriority(NotificationCompat.PriorityMin);
MainActivity.NOTIFICATION_ID++;
_notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());
_sentNotificationList.Add(note);
notePos++;
}
//if the notification isn't the first in our batch, then use this
//code block to send the notifications without sound
else if (!_sentNotificationList.Contains(note))
{
var builder = new Android.Support.V4.App.NotificationCompat.Builder(_ctx, MainActivity.CHANNEL_ID)
.SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
.SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
.SetContentTitle(note._noteText) // Set the title
.SetNumber(1) // Display the count in the Content Info
.SetSmallIcon(Resource.Drawable.bitchute_notification2)
.SetContentText(note._noteType)
.SetPriority(NotificationCompat.PriorityHigh);
MainActivity.NOTIFICATION_ID++;
_notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());
_sentNotificationList.Add(note);
notePos++;
}
ExtStickyService._notificationsHaveBeenSent = true;
}
}
catch
{
}
});
}
In my MainActivity I've created two different notification channels: one is silent; the other uses default notification setting for the device:
void CreateNotificationChannel()
{
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build();
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3");
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var name = "BitChute";
var description = "BitChute for Android";
var channelSilent = new Android.App.NotificationChannel(CHANNEL_ID, name + " Silent", Android.App.NotificationImportance.High)
{
Description = description
};
var channel = new Android.App.NotificationChannel(CHANNEL_ID + 1, name, Android.App.NotificationImportance.High)
{
Description = description
};
channel.LockscreenVisibility = NotificationVisibility.Private;
//here is where I set the sound for the silent channel... this could be the issue?
var notificationManager = (Android.App.NotificationManager)GetSystemService(NotificationService);
channelSilent.SetSound(uri, alarmAttributes);
notificationManager.CreateNotificationChannel(channel);
notificationManager.CreateNotificationChannel(channelSilent);
}
Full source: https://github.com/hexag0d/BitChute_Mobile_Android_BottomNav/tree/APILevel9
EDIT: something really interesting is that if I pulldown the system ui bar, the volume goes back to normal. Very strange workaround but it might help diagnose the cause.
DOUBLE EDIT: I used .SetSound(null, null) instead of using the blank .mp3 and the ducking works fine now. See comments

how to display custom permission message

I want to display a custom message to the user for app permission. I am using Plugin.Permissions for App permission. When i run the current code and run application this popup message display Allow {App Name} to access this device location?. Below is the function currently i am using.
public static async Task<bool> GetPermissions()
{
bool permissionsGranted = true;
var permissionsStartList = new List<Permission>()
{
Permission.Location,
Permission.Camera
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
try
{
foreach (var permission in permissionsNeededList)
{
var status = PermissionStatus.Unknown;
//Best practice to always check that the key exists
if (results.ContainsKey(permission))
status = results[permission];
if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
{
permissionsGranted = true;
}
else
{
permissionsGranted = false;
break;
}
}
}
catch (Exception ex)
{
}
return permissionsGranted;
}
Thanks for your help and comments
Sadly there is no way to customize the text in the permission dialogs.
These are system dialogs and the app has no control over their content.
Quote from https://developer.android.com/training/permissions/requesting#perm-request
When your app receives PERMISSION_DENIED from checkSelfPermission(), you need to prompt the user for that permission. Android provides several methods you can use to request a permission, such as requestPermissions(), as shown in the code snippet below. Calling these methods brings up a standard Android dialog, which you cannot customize.
How this is displayed to the user depends on the device Android version as well as the target version of your application, as described in the Permissions Overview.

Opening a PDF file using associated application in a Unity App for WindowsPhone 8.0

I am pretty new in WindowsPhone applications development. I am currently developing a Unity application for Windows Phone 8.0. Inside this app I would like to open a PDF using the appropriate application on the phone (Acrobat Reader, Windows Reader, etc...)
First, I tried this :
void PDFButtonToggled(bool i_info)
{
Dispatcher.BeginInvoke(() =>
{
DefaultLaunch();
});
}
async void DefaultLaunch()
{
// Path to the file in the app package to launch
string PDFFilePath = #"Data/StreamingAssets/ImageTest.jpg";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(PDFFilePath);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
throw new Exception("File launch failed");
}
}
else
{
throw new Exception("Could not find file");
}
}
It returned me an exception so I searched why. I found that topic (written in 2013 :/) about async functions / threads : LINK. To sumarize, here the answer of Unity staff :
It will only work on Windows Store Apps, and you'll have to wrap the code in #if NET_FX/#endif. On other platforms, you cannot use async/.NET 4.5 code in scripts. If you want to use it for windows phone, you'll have to write that code in separate visual studio solution and compile it to DLL, so unity can use it as a plugin.
So I decided to create the double DLL solution described in the Unity Manual here : LINK. But when I complete the class of the first DLL with the "async void DefaultLaunch()" function given above I don't have references about Windows.ApplicationModel.etc... and Windows.System.etc... .
And here I am, a little bit lost between WP, Unity, 8.0 apps, StoreApps, etc...
If anyone has advices, questions, anything that can help me, it's welcome. :)
Crèvecoeur
I found a solution by myself but on a WindowsPhone8.1 application.
Here it is :
async void PDFButtonToggled(bool i_info)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
DefaultLaunchFile();
});
}
async void DefaultLaunchFile()
{
StorageFolder dataFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Data");
StorageFolder streamingAssetsFolder = await dataFolder.GetFolderAsync("StreamingAssets");
// Path to the file in the app package to launch
string filePath = "PDFTest.pdf";
var file = await streamingAssetsFolder.GetFileAsync(filePath);
if (file != null)
{
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
throw new Exception("File launch failed");
}
}
else
{
throw new Exception("File not found");
}
}

Recording Audio and Playing sound at the same time - C# - Windows Phone 8.1

I am trying to record audio and play it directly (I want to hear my voice in the headphone without saving it) however the MediaElement and the MediaCapture seems non to work at the same time.
I initialized my MediaCapture so:
_mediaCaptureManager = new MediaCapture();
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Audio;
settings.MediaCategory = MediaCategory.Other;
settings.AudioProcessing = AudioProcessing.Default;
await _mediaCaptureManager.InitializeAsync(settings);
However I don't really know how to proceed; I am wonderign if one of these ways could work (I tryied implement them without success, and I have not found examples):
Is there a way to use StartPreviewAsync() recording Audio, or it only works for Videos? I noticed that I get the following error:"The specified object or value does not exist" while setting my CaptureElement Source; it only happens if I write "settings.StreamingCaptureMode = StreamingCaptureMode.Audio;" while everyting works for .Video.
How can I record to a stream using StartRecordToStreamAsync(); I mean, how have I to initialize the IRandomAccessStream and read from it? Can I write on a stream while I keep reading for it?
I read that changing AudioCathegory of the MediaElement and the MediaCathegory of the MediaCapture to Communication there is a possibility it could work. However, while my code works (it just have to record and save in a file) with the previous setting, it don't works if I wrote "settings.MediaCategory = MediaCategory.Communication;" instead of "settings.MediaCategory = MediaCategory.Other;". Can you tell me why?
Here is my current program that just record, save and play:
private async void CaptureAudio()
{
try
{
_recordStorageFile = await KnownFolders.VideosLibrary.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);
await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);
_recording = true;
}
catch (Exception e)
{
Debug.WriteLine("Failed to capture audio:"+e.Message);
}
}
private async void StopCapture()
{
if (_recording)
{
await _mediaCaptureManager.StopRecordAsync();
_recording = false;
}
}
private async void PlayRecordedCapture()
{
if (!_recording)
{
var stream = await _recordStorageFile.OpenAsync(FileAccessMode.Read);
playbackElement1.AutoPlay = true;
playbackElement1.SetSource(stream, _recordStorageFile.FileType);
playbackElement1.Play();
}
}
If you have any suggestion I'll be gratefull.
Have a good day.
Would you consider targeting Windows 10 instead? The new AudioGraph API allows you to do just this, and the Scenario 2 (Device Capture) in the SDK sample demonstrates it well.
First, the sample populates all output devices into a list:
private async Task PopulateDeviceList()
{
outputDevicesListBox.Items.Clear();
outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector());
outputDevicesListBox.Items.Add("-- Pick output device --");
foreach (var device in outputDevices)
{
outputDevicesListBox.Items.Add(device.Name);
}
}
Then it gets to building the AudioGraph:
AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency;
// Use the selected device from the outputDevicesListBox to preview the recording
settings.PrimaryRenderDevice = outputDevices[outputDevicesListBox.SelectedIndex - 1];
CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
if (result.Status != AudioGraphCreationStatus.Success)
{
// TODO: Cannot create graph, propagate error message
return;
}
AudioGraph graph = result.Graph;
// Create a device output node
CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
// TODO: Cannot create device output node, propagate error message
return;
}
deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode;
// Create a device input node using the default audio input device
CreateAudioDeviceInputNodeResult deviceInputNodeResult = await graph.CreateDeviceInputNodeAsync(MediaCategory.Other);
if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success)
{
// TODO: Cannot create device input node, propagate error message
return;
}
deviceInputNode = deviceInputNodeResult.DeviceInputNode;
// Because we are using lowest latency setting, we need to handle device disconnection errors
graph.UnrecoverableErrorOccurred += Graph_UnrecoverableErrorOccurred;
// Start setting up the output file
FileSavePicker saveFilePicker = new FileSavePicker();
saveFilePicker.FileTypeChoices.Add("Pulse Code Modulation", new List<string>() { ".wav" });
saveFilePicker.FileTypeChoices.Add("Windows Media Audio", new List<string>() { ".wma" });
saveFilePicker.FileTypeChoices.Add("MPEG Audio Layer-3", new List<string>() { ".mp3" });
saveFilePicker.SuggestedFileName = "New Audio Track";
StorageFile file = await saveFilePicker.PickSaveFileAsync();
// File can be null if cancel is hit in the file picker
if (file == null)
{
return;
}
MediaEncodingProfile fileProfile = CreateMediaEncodingProfile(file);
// Operate node at the graph format, but save file at the specified format
CreateAudioFileOutputNodeResult fileOutputNodeResult = await graph.CreateFileOutputNodeAsync(file, fileProfile);
if (fileOutputNodeResult.Status != AudioFileNodeCreationStatus.Success)
{
// TODO: FileOutputNode creation failed, propagate error message
return;
}
fileOutputNode = fileOutputNodeResult.FileOutputNode;
// Connect the input node to both output nodes
deviceInputNode.AddOutgoingConnection(fileOutputNode);
deviceInputNode.AddOutgoingConnection(deviceOutputNode);
Once all of that is done, you can record to a file while at the same time playing the recorded audio like so:
private async Task ToggleRecordStop()
{
if (recordStopButton.Content.Equals("Record"))
{
graph.Start();
recordStopButton.Content = "Stop";
}
else if (recordStopButton.Content.Equals("Stop"))
{
// Good idea to stop the graph to avoid data loss
graph.Stop();
TranscodeFailureReason finalizeResult = await fileOutputNode.FinalizeAsync();
if (finalizeResult != TranscodeFailureReason.None)
{
// TODO: Finalization of file failed. Check result code to see why, propagate error message
return;
}
recordStopButton.Content = "Record";
}
}

Categories

Resources