Пример #1
0
        protected async Task <bool> RunFunctionIfOpenAsyncT_MT(Func <Task> funcAsync)
        {
            if (!_isOpen)
            {
                return(false);
            }

            try
            {
                await _isOpenSemaphore.WaitAsync(CancToken); //.ConfigureAwait(false);

                if (_isOpen && funcAsync != null)
                {
                    await Task.Run(funcAsync, CancToken).ConfigureAwait(false);

                    return(true);
                }
            }
            catch (OperationCanceledException) { }
            catch (Exception ex)
            {
                if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);
                }
            }
            finally
            {
                SemaphoreSlimSafeRelease.TryRelease(_isOpenSemaphore);
            }
            return(false);
        }
Пример #2
0
        protected void SetPropertyLockingUpdatingDb <T>(ref T fldValue, T newValue, object locker, bool raise = true, bool onlyIfDifferent = true, [CallerMemberName] string propertyName = "")
        {
            bool isValueChanged = false;

            lock (locker)
            {
                T oldValue = fldValue;
                if (!newValue.Equals(oldValue) || !onlyIfDifferent)
                {
                    fldValue       = newValue;
                    isValueChanged = true;
                }
            }
            // separate to avoid deadlocks
            if (!isValueChanged)
            {
                return;
            }

            if (raise)
            {
                RaisePropertyChanged_UI(propertyName);
            }

            Task db = RunFunctionIfOpenAsyncA_MT(async delegate
            {
                if (UpdateDbMustOverride() == false)
                {
                    //	string attributeName = '_' + propertyName[0].ToString().ToLower() + propertyName.Substring(1); // only works if naming conventions are respected
                    //	GetType().GetField(attributeName)?.SetValue(this, oldValue);
                    //	RaisePropertyChanged_UI(propertyName);
                    await Logger.AddAsync(GetType().ToString() + "." + propertyName + " could not be set", Logger.ForegroundLogFilename).ConfigureAwait(false);
                }
            });
        }
Пример #3
0
        private async Task <bool> SetIsEnabledAsync(bool enable)
        {
            if (!_isOpen || IsEnabled == enable)
            {
                return(false);
            }

            try
            {
                await _isOpenSemaphore.WaitAsync().ConfigureAwait(false);

                if (_isOpen && IsEnabled != enable)
                {
                    IsEnabledAllowed = enable;
                    return(true);
                }
            }
            catch (Exception ex)
            {
                if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);
                }
            }
            finally
            {
                SemaphoreSlimSafeRelease.TryRelease(_isOpenSemaphore);
            }
            return(false);
        }
Пример #4
0
 private async Task LogMessage(string message, LogBotEntryLevel level)
 {
     await Task.Factory.StartNew(() =>
     {
         Logger.AddAsync(
             new LogBotEntry(
                 message,
                 level)
             , _uiDispatcher);
     });
 }
Пример #5
0
        // LOLLO NOTE important! The Mutex can work across AppDomains (ie across main app and background task) but only if you give it a name!
        // Also, if you declare initially owned true, the second thread trying to cross it will stay locked forever. So, declare it false.
        // All this is not well documented.
        public static async Task LoadAsync()
        {
            string errorMessage = string.Empty;

            try
            {
                await _suspensionSemaphore.WaitAsync().ConfigureAwait(false);

                if (_isLoaded)
                {
                    return;
                }
                var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(SessionDataFilename, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);

                //string ssss = null; //this is useful when you debug and want to see the file as a string
                //using (IInputStream inStream = await file.OpenSequentialReadAsync())
                //{
                //    using (StreamReader streamReader = new StreamReader(inStream.AsStreamForRead()))
                //    {
                //      ssss = streamReader.ReadToEnd();
                //    }
                //}

                using (IInputStream inStream = await file.OpenSequentialReadAsync().AsTask().ConfigureAwait(false))
                {
                    using (var iinStream = inStream.AsStreamForRead())
                    {
                        DataContractSerializer serializer = new DataContractSerializer(typeof(PersistentData));
                        iinStream.Position = 0;
                        PersistentData newPersistentData = (PersistentData)(serializer.ReadObject(iinStream));
                        await iinStream.FlushAsync().ConfigureAwait(false);

                        PersistentData.GetInstanceWithProperties(newPersistentData);
                    }
                }
                Debug.WriteLine("ended reading settings");
            }
            catch (System.Xml.XmlException ex)
            {
                errorMessage = "could not restore the settings";
                await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename);
            }
            catch (Exception ex)
            {
                errorMessage = "could not restore the settings";
                await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename);
            }
            finally
            {
                PersistentData.GetInstance().LastMessage = errorMessage;
                IsLoaded = true;
                SemaphoreSlimSafeRelease.TryRelease(_suspensionSemaphore);
            }
        }
Пример #6
0
        public async Task <bool> CloseAsync(object args = null)
        {
            if (!_isOpen)
            {
                return(await RunFunctionIfOpenAsyncA(delegate { IsEnabledAllowed = false; }).ConfigureAwait(false));
            }

            lock (_ctsLocker)
            {
                _cts?.CancelSafe(true);
            }

            try
            {
                await _isOpenSemaphore.WaitAsync().ConfigureAwait(false);

                if (_isOpen)
                {
                    lock (_ctsLocker)
                    {
                        _cts?.Dispose();
                        _cts       = null;
                        _cancToken = new CancellationToken(true); // CancellationToken is not nullable and not disposable
                    }

                    await UnregisterBackEventHandlersAsync();

                    IsEnabledAllowed = false;
                    IsOpen           = false;

                    await CloseMayOverrideAsync(args).ConfigureAwait(false);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);
                }
            }
            finally
            {
                lock (_isOpenSemaphoreLocker)
                {
                    SemaphoreSlimSafeRelease.TryDispose(_isOpenSemaphore);
                    _isOpenSemaphore = null;
                }
            }
            return(false);
        }
Пример #7
0
        public async Task <bool> OpenAsync(object args = null)
        {
            if (_isOpen)
            {
                return(await RunFunctionIfOpenAsyncA(delegate { IsEnabledAllowed = true; }).ConfigureAwait(false));
            }

            lock (_isOpenSemaphoreLocker)
            {
                if (!SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    _isOpenSemaphore = new SemaphoreSlimSafeRelease(1, 1);
                }
            }
            try
            {
                await _isOpenSemaphore.WaitAsync().ConfigureAwait(false);

                if (!_isOpen)
                {
                    lock (_ctsLocker)
                    {
                        _cts?.Dispose();
                        _cts       = new SafeCancellationTokenSource();
                        _cancToken = _cts.Token;
                    }

                    await OpenMayOverrideAsync(args).ConfigureAwait(false);

                    IsOpen           = true;
                    IsEnabledAllowed = true;

                    await RegisterBackEventHandlersAsync().ConfigureAwait(false);

                    //Logger.Add_TPL($"OpenableObservablePage.OpenAsync: {GetType().Name} is now open", Logger.AppEventsLogFilename, Logger.Severity.Info, false);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);
                }
            }
            finally
            {
                SemaphoreSlimSafeRelease.TryRelease(_isOpenSemaphore);
            }

            return(false);
        }
Пример #8
0
        public async Task <bool> OpenAsync(object args = null)
        {
            if (!_isOpen)
            {
                lock (_isOpenSemaphoreLocker)
                {
                    if (!SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                    {
                        _isOpenSemaphore = new SemaphoreSlimSafeRelease(1, 1);
                    }
                }
                try
                {
                    await _isOpenSemaphore.WaitAsync().ConfigureAwait(false);

                    if (!_isOpen)
                    {
                        lock (_ctsLocker)
                        {
                            _cts?.Dispose();
                            _cts       = new SafeCancellationTokenSource();
                            _cancToken = _cts.Token;
                        }

                        await OpenMayOverrideAsync(args).ConfigureAwait(false);

                        IsOpen           = true;
                        IsEnabledAllowed = true;
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                    {
                        await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);
                    }
                }
                finally
                {
                    SemaphoreSlimSafeRelease.TryRelease(_isOpenSemaphore);
                }
            }
            if (_isOpen)
            {
                await SetIsEnabledAsync(true).ConfigureAwait(false);
            }
            return(false);
        }
Пример #9
0
        protected async Task <BoolWhenOpen> RunFunctionIfOpenThreeStateAsyncT(Func <Task> funcAsync)
        {
            if (!_isOpen)
            {
                return(BoolWhenOpen.ObjectClosed);
            }

            try
            {
                await _isOpenSemaphore.WaitAsync(CancToken); //.ConfigureAwait(false);

                if (_isOpen)
                {
                    await funcAsync().ConfigureAwait(false);

                    return(BoolWhenOpen.Yes);
                }
            }
            catch (OperationCanceledException)
            {
                return(BoolWhenOpen.ObjectClosed);
            }
            catch (Exception ex)
            {
                if (SemaphoreSlimSafeRelease.IsAlive(_isOpenSemaphore))
                {
                    await Logger.AddAsync(GetType().Name + ex.ToString(), Logger.ForegroundLogFilename);

                    return(BoolWhenOpen.Error);
                }
            }
            finally
            {
                SemaphoreSlimSafeRelease.TryRelease(_isOpenSemaphore);
            }

            return(BoolWhenOpen.ObjectClosed);
        }
Пример #10
0
 private async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     // this does not always work when the device force-shuts the app
     await Logger.AddAsync("UnhandledException: " + e.Exception.ToString(), Logger.AppExceptionLogFilename);
 }
Пример #11
0
        /// <summary>
        /// Invoked when Navigation to a certain page fails
        /// </summary>
        /// <param name="sender">The Frame which failed navigation</param>
        /// <param name="e">Details about the navigation failure</param>
        private async void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            await Logger.AddAsync(e.Exception.ToString(), Logger.AppEventsLogFilename);

            throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
        }