Ejemplo n.º 1
0
 public static void Stop()
 {
     Utils.RunOnWindowsUIThread(async() =>
     {
         try
         {
             if (speechRecognizer != null)
             {
                 try
                 {
                     if (isListening)
                     {
                         await speechRecognizer.ContinuousRecognitionSession.StopAsync();
                         isListening = false;
                     }
                 }
                 catch (Exception)
                 {
                     speechRecognizer.Dispose();
                     speechRecognizer = null;
                     isListening      = false;
                 }
             }
         }
         catch (Exception ex)
         {
             // If stoping diction crashes, the assumption is that it is ok to ignore it since the scenario is anyways done
             DebugLog.Log(LogLevel.Error, "Hit an exception in Speech::Stop and ignoring it.." + ex.ToString());
             return;
         }
     });
 }
Ejemplo n.º 2
0
        public static void RequestAppPurchase(bool requireReceipt, Action <CallbackResponse <string> > OnAppPurchaseFinished)
        {
            string result             = String.Empty;
            bool   didPurchaseSucceed = false;

            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    if (_isLicenseSimulationOn)
                    {
                        result = await CurrentAppSimulator.RequestAppPurchaseAsync(requireReceipt);
                        if (CurrentAppSimulator.LicenseInformation.IsActive && !CurrentAppSimulator.LicenseInformation.IsTrial)
                        {
                            didPurchaseSucceed = true;
                        }
                    }
                    else
                    {
                        result = await CurrentApp.RequestAppPurchaseAsync(requireReceipt);
                        if (CurrentApp.LicenseInformation.IsActive && !CurrentApp.LicenseInformation.IsTrial)
                        {
                            didPurchaseSucceed = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error purchasing the app " + ex.ToString());
                    Utils.RunOnUnityAppThread(() =>
                    {
                        if (OnAppPurchaseFinished != null)
                        {
                            OnAppPurchaseFinished(
                                new CallbackResponse <string>
                            {
                                Status    = CallbackStatus.Failure,
                                Result    = null,
                                Exception = ex
                            });
                        }
                    });

                    return;
                }

                Utils.RunOnUnityAppThread(() =>
                {
                    if (OnAppPurchaseFinished != null)
                    {
                        OnAppPurchaseFinished(new CallbackResponse <string>
                        {
                            Status    = didPurchaseSucceed ? CallbackStatus.Success : CallbackStatus.Failure,
                            Result    = result,
                            Exception = null
                        });
                    }
                });
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Put an event handler for notifications.
        /// </summary>
        /// <param name="OnPushNotification"></param>
        /// <param name="cancelDefaultBehavior"></param>
        public static void RegisterForNotifications(Action <CallbackResponse <object> > OnPushNotification, bool cancelDefaultBehavior)
        {
            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
                    channel.PushNotificationReceived += (s, e) =>
                    {
                        String notificationContent = String.Empty;

                        switch (e.NotificationType)
                        {
                        case Windows.Networking.PushNotifications.PushNotificationType.Badge:
                            notificationContent = e.BadgeNotification.Content.GetXml();
                            break;

                        case Windows.Networking.PushNotifications.PushNotificationType.Tile:
                            notificationContent = e.TileNotification.Content.GetXml();
                            break;

                        case Windows.Networking.PushNotifications.PushNotificationType.Toast:
                            notificationContent = e.ToastNotification.Content.GetXml();
                            break;

                        case Windows.Networking.PushNotifications.PushNotificationType.Raw:
                            notificationContent = e.RawNotification.Content;
                            break;
                        }

                        if (cancelDefaultBehavior)
                        {
                            e.Cancel = true;
                        }

                        Utils.RunOnUnityAppThread(() =>
                        {
                            if (OnPushNotification != null)
                            {
                                OnPushNotification(new CallbackResponse <object> {
                                    Result = notificationContent, Status = CallbackStatus.Success, Exception = null
                                });
                            }
                        });
                    };
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error registering for notifications");
                    if (OnPushNotification != null)
                    {
                        OnPushNotification(new CallbackResponse <object> {
                            Result = null, Status = CallbackStatus.Failure, Exception = ex
                        });
                    }

                    return;
                }
            });
        }
Ejemplo n.º 4
0
        //public delegate void SetInputFocusOnUnity(bool enabled);
        //public static SetInputFocusOnUnity handler;

        /// <summary>
        /// A bit of primer on how executing delegates on different threads works. When one thread wants to execute something
        /// on the other thread, it takes the work item and inserts it in the "dispatch" queue for the other thread. The other
        /// thread picks whatever is in its work queue and runs/dispatches it. So, we can keep bouncing between threads as much
        /// as we want.
        /// </summary>
        /// <param name="delegateToExecute"></param>
        public static void RunOnUnityAppThread(Action delegateToExecute)
        {
            if (delegateToExecute == null)
            {
                throw new ArgumentNullException("delegateToExecute", "You must pass a non-null delegate to execute on the Unity thread when invoking RunOnUnityAppThread");
            }

            try
            {
                _unityAppThreadInvokerDelegate(delegateToExecute);
            }
            catch (Exception ex)
            {
                DebugLog.Log(LogLevel.Error, "Error running task on the Unity thread " + ex.ToString());
            }
        }
Ejemplo n.º 5
0
        public static void ReportConsumableFulfillment(string productId, Guid transactionId,
                                                       Action <CallbackResponse <FulfillmentResult> > OnReportConsumableFulfillmentFinished)
        {
            Utils.RunOnWindowsUIThread(async() =>
            {
                Windows.ApplicationModel.Store.FulfillmentResult result = Windows.ApplicationModel.Store.FulfillmentResult.ServerError;
                try
                {
                    if (_isLicenseSimulationOn)
                    {
                        result = await CurrentAppSimulator.ReportConsumableFulfillmentAsync(productId, transactionId);
                    }
                    else
                    {
                        result = await CurrentApp.ReportConsumableFulfillmentAsync(productId, transactionId);
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error while reporting consumable fulfillment " + ex.ToString());
                    Utils.RunOnUnityAppThread(() => { if (OnReportConsumableFulfillmentFinished != null)
                                                      {
                                                          OnReportConsumableFulfillmentFinished(new CallbackResponse <FulfillmentResult> {
                                Status = CallbackStatus.Failure, Exception = ex, Result = FulfillmentResult.ServerError
                            });
                                                      }
                                              });
                    return;
                }

                // This should not really be throwing exceptions.. If it does, they will be raised on the Unity thread anyways, so game should handle it
                Utils.RunOnUnityAppThread(() =>
                {
                    if (OnReportConsumableFulfillmentFinished != null)
                    {
                        OnReportConsumableFulfillmentFinished(
                            new CallbackResponse <FulfillmentResult>
                        {
                            Result    = (Microsoft.UnityPlugins.FulfillmentResult)result,
                            Exception = null,
                            Status    = CallbackStatus.Success
                        });
                    }
                });
            });
        }
Ejemplo n.º 6
0
 private static void InterstitialAd_Completed(object sender, object e)
 {
     DebugLog.Log(LogLevel.Info, "Completed");
     // request the next ad
     lastPlayed = DateTime.Now;
     Utils.RunOnWindowsUIThread(() =>
     {
         try
         {
             interstitialAd.RequestAd(AdType.Video, adAppId, adUnitId);
         }
         catch (Exception x)
         {
             DebugLog.Log(LogLevel.Error, x.ToString());
         }
     });
     isShowRequested = false;
 }
Ejemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="callback"></param> It is best not to set the callback parameter to null. The reason being  you don't know
        /// when the license loading is finished. Best set it properly to avoid tricky race conditions
        /// <param name="licenseFilePath"></param>
        ///
        public static void LoadLicenseXMLFile(Action <CallbackResponse> callback, string licenseFilePath = null)
        {
            DebugLog.Log(LogLevel.Info, "entered LoadLicenseXmlFile");

            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    licenseFilePath = (licenseFilePath == null) ? "WindowsStoreProxy.xml" : licenseFilePath;

                    StorageFile licenseFile;
                    if (System.IO.Path.IsPathRooted(licenseFilePath))
                    {
                        licenseFile = await StorageFile.GetFileFromPathAsync(licenseFilePath);
                    }
                    else
                    {
                        licenseFile = await Package.Current.InstalledLocation.GetFileAsync(licenseFilePath);
                    }
                    await CurrentAppSimulator.ReloadSimulatorAsync(licenseFile);

                    // switch on the license simulation
                    _isLicenseSimulationOn = true;

                    if (callback != null)
                    {
                        Utils.RunOnUnityAppThread(() =>
                        {
                            callback(new CallbackResponse {
                                Exception = null, Status = CallbackStatus.Success
                            });
                        });
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Fatal, "Error loading license file. License simulator will give incorrect results!" + ex.ToString());
                    callback(new CallbackResponse {
                        Exception = ex, Status = CallbackStatus.Failure
                    });
                    return;
                }
            });
        }
Ejemplo n.º 8
0
 private static void InterstitialAd_AdReady(object sender, object e)
 {
     DebugLog.Log(LogLevel.Info, "AdReady");
     // wait until canPlay == true
     Utils.RunOnWindowsUIThread(() =>
     {
         if (interstitialAd.State == InterstitialAdState.Ready && isShowRequested)
         {
             isShowRequested = false;
             try
             {
                 interstitialAd.Show();
             }
             catch (Exception x) {
                 DebugLog.Log(LogLevel.Error, x.ToString());
             }
         }
     });
 }
Ejemplo n.º 9
0
        public static void LoadUnfulfilledConsumables(Action <CallbackResponse <List <UnfulfilledConsumable> > > OnLoadUnfulfilledConsumablesFinished)
        {
            Utils.RunOnWindowsUIThread(async() =>
            {
                IReadOnlyList <Windows.ApplicationModel.Store.UnfulfilledConsumable> unfulfilledConsumables = null;
                List <UnfulfilledConsumable> deliveryFormatUnfulfilledConsumables = new List <UnfulfilledConsumable>();
                try
                {
                    if (_isLicenseSimulationOn)
                    {
                        unfulfilledConsumables = await CurrentAppSimulator.GetUnfulfilledConsumablesAsync();
                    }
                    else
                    {
                        unfulfilledConsumables = await CurrentApp.GetUnfulfilledConsumablesAsync();
                    }


                    foreach (var oneUnfConsumable in unfulfilledConsumables)
                    {
                        deliveryFormatUnfulfilledConsumables.Add(new UnfulfilledConsumable(oneUnfConsumable));
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error while reporting consumable fulfillment " + ex.ToString());
                    Utils.RunOnUnityAppThread(() => { OnLoadUnfulfilledConsumablesFinished(new CallbackResponse <List <UnfulfilledConsumable> > {
                            Status = CallbackStatus.Failure, Exception = ex, Result = null
                        }); });
                    return;
                }

                // deliver all the unfulfilled consumables at once
                Utils.RunOnUnityAppThread(() => { if (OnLoadUnfulfilledConsumablesFinished != null)
                                                  {
                                                      OnLoadUnfulfilledConsumablesFinished(new CallbackResponse <List <UnfulfilledConsumable> > {
                            Status = CallbackStatus.Success, Result = deliveryFormatUnfulfilledConsumables, Exception = null
                        });
                                                  }
                                          });
            });
        }
Ejemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="delegateToExecute"></param>
        public static void RunOnWindowsUIThread(Action delegateToExecute)
        {
            if (delegateToExecute == null)
            {
                throw new ArgumentNullException("delegateToExecute", "You must pass a non-null delegate to execute on the Unity thread when invoking RunOnWindowsUIThread");
            }

            Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                                                  () =>
            {
                try
                {
                    delegateToExecute(); // run the action now
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error running task on the Windows UI thread " + ex.ToString());
                }
            });
        }
Ejemplo n.º 11
0
        public static void VerifyReceipt(string receiptWebserviceUrl, string receipt, Action <CallbackResponse <ReceiptResponse> > OnReceiptVerified)
        {
            Task.Run(async() =>
            {
                try
                {
                    var httpClient = new HttpClient();
                    var content    = new StringContent(receipt, Encoding.UTF8, "application/xml");

                    DebugLog.Log(LogLevel.Info, "Sending out receipt for verification");


                    var response = await httpClient.PostAsync(new Uri(receiptWebserviceUrl, UriKind.RelativeOrAbsolute), content);

                    var responseString = await response.Content.ReadAsStringAsync();
                    DebugLog.Log(LogLevel.Info, "received response: " + responseString);
                    var responseObject = JsonConvert.DeserializeObject <ReceiptResponse>(responseString);

                    // TODO: Is this right? We created a new thread to accommodate the async/await.. Then we marshal the callback back to the app thread
                    if (OnReceiptVerified != null)
                    {
                        Utils.RunOnUnityAppThread(() => OnReceiptVerified(new CallbackResponse <ReceiptResponse> {
                            Result = responseObject, Exception = null, Status = CallbackStatus.Success
                        }));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    if (OnReceiptVerified != null)
                    {
                        // return the results back on the Unity app thread
                        Utils.RunOnUnityAppThread(() => OnReceiptVerified(new CallbackResponse <ReceiptResponse> {
                            Result = null, Exception = ex, Status = CallbackStatus.Failure
                        }));
                        return;
                    }
                }
            });
        }
Ejemplo n.º 12
0
        public static void RequestProductPurchase(string productId, Action <CallbackResponse <PurchaseResults> > OnProductPurchaseFinished)
        {
            PurchaseResults result = null;

            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    if (_isLicenseSimulationOn)
                    {
                        result = new PurchaseResults(await CurrentAppSimulator.RequestProductPurchaseAsync(productId));
                    }
                    else
                    {
                        result = new PurchaseResults(await CurrentApp.RequestProductPurchaseAsync(productId));
                    }
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Error purchasing the product " + ex.ToString());
                    Utils.RunOnUnityAppThread(() => { if (OnProductPurchaseFinished != null)
                                                      {
                                                          OnProductPurchaseFinished(new CallbackResponse <PurchaseResults> {
                                Exception = ex, Status = CallbackStatus.Failure, Result = null
                            });
                                                      }
                                              });
                    return;
                }

                Utils.RunOnUnityAppThread(() => { if (OnProductPurchaseFinished != null)
                                                  {
                                                      OnProductPurchaseFinished(new CallbackResponse <PurchaseResults> {
                            Exception = null, Status = CallbackStatus.Success, Result = result
                        });
                                                  }
                                          });
            });
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initialize the interstitial ad and request the first ad
        /// </summary>
        /// <param name="appId">Microsoft Advertising application Id (set up in pubcenter)</param>
        /// <param name="unitId">Microsoft Advertising interstitial video ad id (set up in pubcenter)</param>
        public static void Init(string appId, string unitId)
        {
            Utils.RunOnWindowsUIThread(() =>
            {
                DebugLog.Log(LogLevel.Info, "Initializing interstitial ads...");
                interstitialAd                = new InterstitialAd();
                interstitialAd.AdReady       += InterstitialAd_AdReady;
                interstitialAd.ErrorOccurred += InterstitialAd_ErrorOccurred;
                interstitialAd.Completed     += InterstitialAd_Completed;
                interstitialAd.Cancelled     += InterstitialAd_Cancelled;

                if (interstitialAd != null)
                {
                    adAppId  = appId;
                    adUnitId = unitId;
                    // automatically request the first ad
                    DebugLog.Log(LogLevel.Info, "Requesting interstitial ads...");
                    interstitialAd.RequestAd(AdType.Video, adAppId, adUnitId);
                    isAdRequested = true;
                }
            });
        }
Ejemplo n.º 14
0
 /// <summary>
 /// You can call show, when the ad is ready it will be started automatically
 /// Interstitial documentation recommends at least 60 seconds between ads
 /// </summary>
 public static void Show()
 {
     DebugLog.Log(LogLevel.Info, "Show");
     Utils.RunOnWindowsUIThread(() =>
     {
         if (interstitialAd.State == InterstitialAdState.Ready)
         {
             isShowRequested = false;
             try
             {
                 interstitialAd.Show();
             }
             catch (Exception x) {
                 DebugLog.Log(LogLevel.Error, x.ToString());
             }
         }
         else
         {
             isShowRequested = true;
         }
     });
 }
Ejemplo n.º 15
0
        public static void ListenForCommands(IEnumerable <string> commands, Action <CallbackResponse <SpeechArguments> > OnSpeechResults)
        {
            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    Stop();
                    speechRecognizer = new SpeechRecognizer();
                    speechRecognizer.Constraints.Add(new SpeechRecognitionListConstraint(commands, "Commands"));
                    var compilationResult = await speechRecognizer.CompileConstraintsAsync();
                    if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
                    {
                        throw new Exception();
                    }

                    DebugLog.Log(LogLevel.Info, "ListenForCommands");

                    speechRecognizer.ContinuousRecognitionSession.Completed += (sender, args) =>
                    {
                        DebugLog.Log(LogLevel.Info, "ListenForCommands " + args.Status.ToString());
                        if (args.Status != SpeechRecognitionResultStatus.Success)
                        {
                            if (OnSpeechResults != null)
                            {
                                Utils.RunOnUnityAppThread(
                                    () =>
                                {
                                    OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                        Result = new SpeechArguments {
                                            Status = SpeechResultStatus.Complete
                                        }, Status = CallbackStatus.Success, Exception = null
                                    });
                                });
                            }
                            isListening = false;
                        }
                    };

                    speechRecognizer.ContinuousRecognitionSession.ResultGenerated += (sender, args) =>
                    {
                        DebugLog.Log(LogLevel.Info, "ListenForCommands " + args.Result.Text);

                        var command = args.Result.Text;
                        if (!String.IsNullOrEmpty(command))
                        {
                            command = command.ToLower();
                        }

                        if (commands != null && commands.Count() > 0)
                        {
                            foreach (var c in commands)
                            {
                                if (args != null && args.Result != null && args.Result.Text != null && c.ToLower() == command)
                                {
                                    DebugLog.Log(LogLevel.Info, "ListenForCommands command " + command);
                                    if (OnSpeechResults != null)
                                    {
                                        Utils.RunOnUnityAppThread(
                                            () =>
                                        {
                                            OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                                Result = new SpeechArguments {
                                                    Status = SpeechResultStatus.Command, Text = command
                                                }, Status = CallbackStatus.Success, Exception = null
                                            });
                                        });
                                    }
                                    break;
                                }
                            }
                        }
                    };

                    await speechRecognizer.ContinuousRecognitionSession.StartAsync();
                    isListening = true;
                }
                catch (Exception ex)
                {
                    DebugLog.Log(LogLevel.Error, "Hit Exception in Speech::ListenForCommands..." + ex.ToString());
                    if (OnSpeechResults != null)
                    {
                        Utils.RunOnUnityAppThread(
                            () =>
                        {
                            OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                Result = null, Status = CallbackStatus.Failure, Exception = ex
                            });
                        });
                    }

                    return;
                }
            });
        }
Ejemplo n.º 16
0
        public static void ListenForDictation(Action <CallbackResponse <SpeechArguments> > OnSpeechResults)
        {
            Utils.RunOnWindowsUIThread(async() =>
            {
                try
                {
                    Stop();
                    speechRecognizer = new SpeechRecognizer();
                    speechRecognizer.Constraints.Add(new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.Dictation, "Dictation"));
                    var compilationResult = await speechRecognizer.CompileConstraintsAsync();
                    if (compilationResult.Status != SpeechRecognitionResultStatus.Success)
                    {
                        throw new Exception();
                    }

                    DebugLog.Log(LogLevel.Info, "ListenForDictation");

                    speechRecognizer.HypothesisGenerated += (sender, args) =>
                    {
                        string hypothesis = args.Hypothesis.Text;
                        DebugLog.Log(LogLevel.Info, "ListenForDictation Hypothesis " + hypothesis + "...");
                        if (OnSpeechResults != null)
                        {
                            Utils.RunOnUnityAppThread(
                                () =>
                            {
                                OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                    Result = new SpeechArguments {
                                        Status = SpeechResultStatus.Hypothesis, Text = hypothesis
                                    }, Status = CallbackStatus.Success, Exception = null
                                });
                            });
                        }
                    };

                    speechRecognizer.ContinuousRecognitionSession.Completed += (sender, args) =>
                    {
                        DebugLog.Log(LogLevel.Info, "ListenForDictation " + args.Status.ToString());
                        if (args.Status != SpeechRecognitionResultStatus.Success)
                        {
                            if (OnSpeechResults != null)
                            {
                                Utils.RunOnUnityAppThread(
                                    () =>
                                {
                                    OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                        Result = new SpeechArguments {
                                            Status = SpeechResultStatus.Complete
                                        }, Status = CallbackStatus.Success, Exception = null
                                    });
                                });
                            }
                            isListening = false;
                        }
                    };


                    speechRecognizer.ContinuousRecognitionSession.ResultGenerated += (sender, args) =>
                    {
                        DebugLog.Log(LogLevel.Info, args.Result.Text);

                        DebugLog.Log(LogLevel.Info, "ListenForDictation " + args.Result.Text);
                        if (OnSpeechResults != null)
                        {
                            Utils.RunOnUnityAppThread(
                                () =>
                            {
                                OnSpeechResults(new CallbackResponse <SpeechArguments> {
                                    Result = new SpeechArguments {
                                        Status = SpeechResultStatus.Dictation, Text = args.Result.Text
                                    }, Status = CallbackStatus.Success, Exception = null
                                });
                            });
                        }
                    };

                    await speechRecognizer.ContinuousRecognitionSession.StartAsync();
                    isListening = true;
                }
                catch (Exception ex)
                {
                    OnSpeechResults(new CallbackResponse <SpeechArguments> {
                        Result = null, Status = CallbackStatus.Failure, Exception = ex
                    });
                    return;
                }
            });
        }
Ejemplo n.º 17
0
 private static void InterstitialAd_ErrorOccurred(object sender, AdErrorEventArgs e)
 {
     DebugLog.Log(LogLevel.Info, "ErrorOccurred " + e.ErrorMessage);
     isShowRequested = false;
 }
Ejemplo n.º 18
0
 private static void InterstitialAd_Cancelled(object sender, object e)
 {
     DebugLog.Log(LogLevel.Info, "Cancelled");
     isShowRequested = false;
 }