Best WinAppDriver code snippet using AppUIBasics.Common.SuspensionManagerException
SuspensionManager.cs
Source:SuspensionManager.cs  
...78                }79            }80            catch (Exception e)81            {82                throw new SuspensionManagerException(e);83            }84        }85        /// <summary>86        /// Restores previously saved <see cref="SessionState"/>.  Any <see cref="Frame"/> instances87        /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation88        /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its89        /// state.90        /// </summary>91        /// <returns>An asynchronous task that reflects when session state has been read.  The92        /// content of <see cref="SessionState"/> should not be relied upon until this task93        /// completes.</returns>94        public static async Task RestoreAsync()95        {96            _sessionState = new Dictionary<String, Object>();97            try98            {99                // Get the input stream for the SessionState file100                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);101                using (IInputStream inStream = await file.OpenSequentialReadAsync())102                {103                    // Deserialize the Session State104                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);105                    _sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());106                }107                // Restore any registered frames to their saved state108                foreach (var weakFrameReference in _registeredFrames)109                {110                    Frame frame;111                    if (weakFrameReference.TryGetTarget(out frame))112                    {113                        frame.ClearValue(FrameSessionStateProperty);114                        RestoreFrameNavigationState(frame);115                    }116                }117            }118            catch (Exception e)119            {120                throw new SuspensionManagerException(e);121            }122        }123        private static DependencyProperty FrameSessionStateKeyProperty =124            DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);125        private static DependencyProperty FrameSessionStateProperty =126            DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);127        private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();128        /// <summary>129        /// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to130        /// and restored from <see cref="SessionState"/>.  Frames should be registered once131        /// immediately after creation if they will participate in session state management.  Upon132        /// registration if state has already been restored for the specified key133        /// the navigation history will immediately be restored.  Subsequent invocations of134        /// <see cref="RestoreAsync"/> will also restore navigation history.135        /// </summary>136        /// <param name="frame">An instance whose navigation history should be managed by137        /// <see cref="SuspensionManager"/></param>138        /// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to139        /// store navigation-related information.</param>140        public static void RegisterFrame(Frame frame, String sessionStateKey)141        {142            if (frame.GetValue(FrameSessionStateKeyProperty) != null)143            {144                throw new InvalidOperationException("Frames can only be registered to one session state key");145            }146            if (frame.GetValue(FrameSessionStateProperty) != null)147            {148                throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");149            }150            // Use a dependency property to associate the session key with a frame, and keep a list of frames whose151            // navigation state should be managed152            frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);153            _registeredFrames.Add(new WeakReference<Frame>(frame));154            // Check to see if navigation state can be restored155            RestoreFrameNavigationState(frame);156        }157        /// <summary>158        /// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>159        /// from <see cref="SessionState"/>.  Any navigation state previously captured will be160        /// removed.161        /// </summary>162        /// <param name="frame">An instance whose navigation history should no longer be163        /// managed.</param>164        public static void UnregisterFrame(Frame frame)165        {166            // Remove session state and remove the frame from the list of frames whose navigation167            // state will be saved (along with any weak references that are no longer reachable)168            SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));169            _registeredFrames.RemoveAll((weakFrameReference) =>170            {171                Frame testFrame;172                return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;173            });174        }175        /// <summary>176        /// Provides storage for session state associated with the specified <see cref="Frame"/>.177        /// Frames that have been previously registered with <see cref="RegisterFrame"/> have178        /// their session state saved and restored automatically as a part of the global179        /// <see cref="SessionState"/>.  Frames that are not registered have transient state180        /// that can still be useful when restoring pages that have been discarded from the181        /// navigation cache.182        /// </summary>183        /// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage184        /// page-specific state instead of working with frame session state directly.</remarks>185        /// <param name="frame">The instance for which session state is desired.</param>186        /// <returns>A collection of state subject to the same serialization mechanism as187        /// <see cref="SessionState"/>.</returns>188        public static Dictionary<String, Object> SessionStateForFrame(Frame frame)189        {190            var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);191            if (frameState == null)192            {193                var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);194                if (frameSessionKey != null)195                {196                    // Registered frames reflect the corresponding session state197                    if (!_sessionState.ContainsKey(frameSessionKey))198                    {199                        _sessionState[frameSessionKey] = new Dictionary<String, Object>();200                    }201                    frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];202                }203                else204                {205                    // Frames that aren't registered have transient state206                    frameState = new Dictionary<String, Object>();207                }208                frame.SetValue(FrameSessionStateProperty, frameState);209            }210            return frameState;211        }212        private static void RestoreFrameNavigationState(Frame frame)213        {214            var frameState = SessionStateForFrame(frame);215            if (frameState.ContainsKey("Navigation"))216            {217                frame.SetNavigationState((String)frameState["Navigation"]);218            }219        }220        private static void SaveFrameNavigationState(Frame frame)221        {222            var frameState = SessionStateForFrame(frame);223            frameState["Navigation"] = frame.GetNavigationState();224        }225    }226    public class SuspensionManagerException : Exception227    {228        public SuspensionManagerException()229        {230        }231        public SuspensionManagerException(Exception e)232            : base("SuspensionManager failed", e)233        {234        }235    }236}...SuspensionManagerException
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.IO;4using System.Linq;5using System.Runtime.Serialization;6using System.Text;7using System.Threading.Tasks;8using Windows.ApplicationModel;9using Windows.Storage;10{11    {12        private static Dictionary<string, object> sessionState = new Dictionary<string, object>();13        private static List<Type> knownTypes = new List<Type>();14        private const string sessionStateFilename = "_sessionState.xml";15        {16            get { return sessionState; }17        }18        {19            get { return knownTypes; }20        }SuspensionManagerException
Using AI Code Generation
1using AppUIBasics.Common;2using System;3using System.Collections.Generic;4using System.IO;5using System.Linq;6using System.Runtime.Serialization;7using System.Runtime.Serialization.Json;8using System.Text;9using System.Threading.Tasks;10using Windows.Storage;11{12    {13        public SuspensionManagerException() { }14        public SuspensionManagerException(string message) : base(message) { }15        public SuspensionManagerException(string message, Exception innerException) : base(message, innerException) { }16        protected SuspensionManagerException(SerializationInfo info, StreamingContext context) : base(info, context) { }17    }18}19using AppUIBasics.Common;20using System;21using System.Collections.Generic;22using System.IO;23using System.Linq;24using System.Runtime.Serialization;25using System.Runtime.Serialization.Json;26using System.Text;27using System.Threading.Tasks;28using Windows.Storage;29{30    {31        private const string sessionStateFilename = "_sessionState.xml";32        private static Dictionary<string, object> sessionState = new Dictionary<string, object>();33        private static bool sessionStateNeedsSaving = false;34        {35            get { return sessionState; }36        }37        public static async Task SaveAsync()38        {39            if (!sessionStateNeedsSaving) return;40            {41                MemoryStream sessionData = new MemoryStream();42                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>));43                serializer.WriteObject(sessionData, sessionState);44                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);45                using (IOutputStream outStream = await file.OpenSequentialWriteAsync())46                {47                    using (DataWriter dataWriter = new DataWriter(outStream))48                    {49                        dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8;50                        dataWriter.WriteString(Encoding.UTF8.GetString(sessionData.ToArray(), 0, (int)sessionData.Length));51                        await dataWriter.StoreAsync();52                        await outStream.FlushAsync();53                    }54                }55                sessionStateNeedsSaving = false;56            }57            catch (SuspensionSuspensionManagerException
Using AI Code Generation
1using AppUIBasics.Common;2using Windows.UI.Xaml;3using Windows.UI.Xaml.Controls;4using Windows.UI.Xaml.Navigation;5{6    {7        public SuspensionManagerExceptionPage()8        {9            this.InitializeComponent();10        }11        protected override void OnNavigatedTo(NavigationEventArgs e)12        {SuspensionManagerException
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.IO;4using System.Linq;5using System.Runtime.Serialization;6using System.Text;7using System.Threading.Tasks;8using Windows.ApplicationModel;9using Windows.Storage;10using Windows.UI.Xaml;11using Windows.UI.Xaml.Controls;12using Windows.UI.Xaml.Navigation;13{14    {15        private const string sessionStateFilename = "_sessionState.xml";16        private static Dictionary<string, object> sessionState = new Dictionary<string, object>();17        private static List<Type> registeredTypes = new List<Type>();18        private static bool sessionStateReady = false;19        private static Frame frame;20        public static void RegisterFrame(Frame frame, Type sessionBaseKey)21        {22            SuspensionManager.frame = frame;23            frame.RegisterPropertyChangedCallback(Frame.BackStackDepthProperty, BackStackDepthPropertyChanged);24            frame.Navigated += Frame_Navigated;25        }26        private static void Frame_Navigated(object sender, NavigationEventArgs e)27        {28            if (e.NavigationMode == NavigationMode.New)29            {30                frame.ForwardStack.Clear();31            }32        }33        private static void BackStackDepthPropertyChanged(DependencyObject sender, DependencyProperty dp)34        {35            var frame = sender as Frame;36            if (frame != null && frame.BackStackDepth == 0)37            {38                sessionState.Clear();39            }40        }41        public static void RegisterType(Type type)42        {43            lock (registeredTypes)44            {45                if (!registeredTypes.Contains(type))46                {SuspensionManagerException
Using AI Code Generation
1using AppUIBasics.Common;2using Windows.UI.Xaml.Controls;3using Windows.UI.Xaml.Navigation;4{5    {6        public SuspensionManagerExceptionPage()7        {8            this.InitializeComponent();9        }10        protected override void OnNavigatedTo(NavigationEventArgs e)11        {SuspensionManagerException
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Windows.ApplicationModel;7using Windows.ApplicationModel.Activation;8using Windows.ApplicationModel.Core;9using Windows.UI.Core;10using Windows.UI.Xaml;11using Windows.UI.Xaml.Controls;12using Windows.UI.Xaml.Navigation;13using AppUIBasics.Common;14using AppUIBasics.Data;15using AppUIBasics.SamplePages;16{17    {18        public static SuspensionManagerException SuspensionManagerException { get; private set; }19        public static Frame RootFrame { get; private set; }20        public static Frame RootFrameException { get; private set; }21        public App()22        {23            InitializeComponent();24            Suspending += OnSuspending;25            UnhandledException += App_UnhandledException;26        }27        private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)28        {29            e.Handled = true;30            SuspensionManagerException.SessionState["Exception"] = e.Exception;31            RootFrameException.Navigate(typeof(SampleExceptionPage));32        }33        protected override async void OnLaunched(LaunchActivatedEventArgs e)34        {35            RootFrame = Window.Current.Content as Frame;36            RootFrameException = Window.Current.Content as Frame;37            if (RootFrame == null)38            {39                RootFrame = new Frame();40                SuspensionManagerException = new SuspensionManagerException(RootFrame, "AppFrameException");41                SuspensionManagerException.RegisterFrame(RootFrameException, "AppFrameException");42                Window.Current.Content = RootFrame;43            }44            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)45            {46                {47                    await SuspensionManagerException.RestoreAsync();48                }49                catch (SuspensionManagerException)50                {51                }52            }53            Window.Current.Activate();54            if (RootFrame.Content == null)55            {Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
