Esempio n. 1
0
        void SaveAsync(SaveOptionsVM[] mods)
        {
            AppCulture.InitializeCulture();
            try {
                moduleSaver = new ModuleSaver(mods);
                moduleSaver.OnProgressUpdated += moduleSaver_OnProgressUpdated;
                moduleSaver.OnLogMessage      += moduleSaver_OnLogMessage;
                moduleSaver.OnWritingFile     += moduleSaver_OnWritingFile;
                moduleSaver.SaveAll();
                AsyncAddMessage(dnSpy_AsmEditor_Resources.SaveModules_Log_AllFilesWritten, false, false);
            }
            catch (TaskCanceledException) {
                AsyncAddMessage(dnSpy_AsmEditor_Resources.SaveModules_Log_SaveWasCanceled, true, false);
            }
            catch (UnauthorizedAccessException ex) {
                AsyncAddMessage(string.Format(dnSpy_AsmEditor_Resources.SaveModules_Log_AccessError, ex.Message), true, false);
            }
            catch (IOException ex) {
                AsyncAddMessage(string.Format(dnSpy_AsmEditor_Resources.SaveModules_Log_FileError, ex.Message), true, false);
            }
            catch (Exception ex) {
                AsyncAddMessage(string.Format(dnSpy_AsmEditor_Resources.SaveModules_Log_Exception, ex), true, false);
            }
            moduleSaver = null;

            ExecInOldThread(() => {
                CurrentFileName = string.Empty;
                State           = SaveState.Saved;
            });
        }
Esempio n. 2
0
 public HexEditorAppSettingsVM(HexEditorSettings hexEditorSettings)
 {
     this.hexEditorSettings = hexEditorSettings;
     this.asciiEncodingVM   = new EnumListVM(asciiEncodingList, (a, b) => hexEditorSettings.AsciiEncoding = (AsciiEncoding)AsciiEncodingVM.SelectedItem);
     this.bytesGroupCountVM = new Int32VM(a => { HasErrorUpdated(); hexEditorSettings.BytesGroupCount = BytesGroupCountVM.Value; });
     this.bytesPerLineVM    = new Int32VM(a => { HasErrorUpdated(); hexEditorSettings.BytesPerLine = BytesPerLineVM.Value; })
     {
         Min = 0,
         Max = HexEditorSettings.MAX_BYTES_PER_LINE,
     };
     AsciiEncodingVM.SelectedItem = hexEditorSettings.AsciiEncoding;
     BytesGroupCountVM.Value      = hexEditorSettings.BytesGroupCount;
     BytesPerLineVM.Value         = hexEditorSettings.BytesPerLine;
     FontFamily = hexEditorSettings.FontFamily;
     Task.Factory.StartNew(() => {
         AppCulture.InitializeCulture();
         return(FontUtils.GetMonospacedFonts());
     })
     .ContinueWith(t => {
         var ex = t.Exception;
         if (!t.IsCanceled && !t.IsFaulted)
         {
             FontFamilies = t.Result;
         }
     }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
 }
Esempio n. 3
0
        public DisplayAppSettingsVM(TextEditorSettings textEditorSettings, FileTreeViewSettings fileTreeViewSettings, FileTabManagerSettings fileTabManagerSettings)
        {
            this.textEditorSettings     = textEditorSettings;
            this.fileTreeViewSettings   = fileTreeViewSettings;
            this.fileTabManagerSettings = fileTabManagerSettings;
            this.fontFamilies           = null;
            this.fontFamilyVM           = new FontFamilyVM(textEditorSettings.FontFamily);
            Task.Factory.StartNew(() => {
                AppCulture.InitializeCulture();
                return(Fonts.SystemFontFamilies.Where(a => !FontUtils.IsSymbol(a)).OrderBy(a => a.Source.ToUpperInvariant()).Select(a => new FontFamilyVM(a)).ToArray());
            })
            .ContinueWith(t => {
                var ex = t.Exception;
                if (!t.IsCanceled && !t.IsFaulted)
                {
                    FontFamilies = t.Result;
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

            var defObjs = typeof(MemberKind).GetEnumValues().Cast <MemberKind>().ToArray();

            this.memberKindVMs = new MemberKindVM[defObjs.Length];
            for (int i = 0; i < defObjs.Length; i++)
            {
                this.memberKindVMs[i] = new MemberKindVM(defObjs[i], ToString(defObjs[i]));
            }
            this.memberKindVMs2 = this.memberKindVMs.ToArray();

            this.MemberKind0 = this.memberKindVMs.First(a => a.Object == fileTreeViewSettings.MemberKind0);
            this.MemberKind1 = this.memberKindVMs.First(a => a.Object == fileTreeViewSettings.MemberKind1);
            this.MemberKind2 = this.memberKindVMs.First(a => a.Object == fileTreeViewSettings.MemberKind2);
            this.MemberKind3 = this.memberKindVMs.First(a => a.Object == fileTreeViewSettings.MemberKind3);
            this.MemberKind4 = this.memberKindVMs.First(a => a.Object == fileTreeViewSettings.MemberKind4);
        }
Esempio n. 4
0
        public static CultureInfo ToCultureInfo(this AppCulture culture)
        {
            if (_cultureMapping.TryGetValue(culture, out var value))
            {
                return(new CultureInfo(value.First()));
            }

            return(new CultureInfo(_cultureMapping[default].First()));
Esempio n. 5
0
        void ShowInternal(IFileTabContent tabContent, object serializedUI, Action <ShowTabContentEventArgs> onShownHandler, bool isRefresh)
        {
            Debug.Assert(asyncWorkerContext == null);
            var oldUIContext = UIContext;

            UIContext = tabContent.CreateUIContext(fileTabUIContextLocator);
            var cachedUIContext = UIContext;

            Debug.Assert(cachedUIContext.FileTab == null || cachedUIContext.FileTab == this);
            cachedUIContext.FileTab = this;
            Debug.Assert(cachedUIContext.FileTab == this);
            Debug.Assert(tabContent.FileTab == null || tabContent.FileTab == this);
            tabContent.FileTab = this;
            Debug.Assert(tabContent.FileTab == this);

            UpdateTitleAndToolTip();
            var showCtx = new ShowContext(cachedUIContext, isRefresh);

            tabContent.OnShow(showCtx);
            bool asyncShow       = false;
            var  asyncTabContent = tabContent as IAsyncFileTabContent;

            if (asyncTabContent != null)
            {
                if (asyncTabContent.CanStartAsyncWorker(showCtx))
                {
                    asyncShow = true;
                    var ctx = new AsyncWorkerContext();
                    asyncWorkerContext = ctx;
                    Task.Factory.StartNew(() => {
                        AppCulture.InitializeCulture();
                        asyncTabContent.AsyncWorker(showCtx, ctx.CancellationTokenSource);
                    }, ctx.CancellationTokenSource.Token)
                    .ContinueWith(t => {
                        bool canShowAsyncOutput = ctx == asyncWorkerContext &&
                                                  cachedUIContext.FileTab == this &&
                                                  UIContext == cachedUIContext;
                        if (asyncWorkerContext == ctx)
                        {
                            asyncWorkerContext = null;
                        }
                        ctx.Dispose();
                        asyncTabContent.EndAsyncShow(showCtx, new AsyncShowResult(t, canShowAsyncOutput));
                        bool success = !t.IsFaulted && !t.IsCanceled;
                        OnShown(serializedUI, onShownHandler, showCtx, success);
                    }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
                }
                else
                {
                    asyncTabContent.EndAsyncShow(showCtx, new AsyncShowResult());
                }
            }
            if (!asyncShow)
            {
                OnShown(serializedUI, onShownHandler, showCtx, true);
            }
            fileTabManager.OnNewTabContentShown(this);
        }
Esempio n. 6
0
        void InitializeCulture(CultureInfo info)
        {
            if (info == null)
            {
                return;
            }

            Thread.CurrentThread.CurrentUICulture = info;
            AppCulture.__Initialize(Thread.CurrentThread.CurrentCulture, info);
            Debug.Assert(Thread.CurrentThread.CurrentUICulture.Equals(info));
        }
Esempio n. 7
0
        void InitializeExecutionEngine(bool loadConfig, bool showHelp)
        {
            Debug.Assert(execState == null);
            if (execState != null)
            {
                throw new InvalidOperationException();
            }

            execState = new ExecState(this, new CancellationTokenSource());
            var execStateCache = execState;

            Task.Run(() => {
                AppCulture.InitializeCulture();
                execStateCache.CancellationTokenSource.Token.ThrowIfCancellationRequested();

                var userOpts = new UserScriptOptions();
                if (loadConfig)
                {
                    userOpts.LibPaths.AddRange(GetDefaultLibPaths());
                    userOpts.LoadPaths.AddRange(GetDefaultLoadPaths());
                    InitializeUserScriptOptions(userOpts);
                }
                var opts = ScriptOptions.Default;
                opts     = opts.WithMetadataResolver(ScriptMetadataResolver.Default
                                                     .WithBaseDirectory(AppDirectories.BinDirectory)
                                                     .WithSearchPaths(userOpts.LibPaths.Distinct(StringComparer.OrdinalIgnoreCase)));
                opts = opts.WithSourceResolver(ScriptSourceResolver.Default
                                               .WithBaseDirectory(AppDirectories.BinDirectory)
                                               .WithSearchPaths(userOpts.LoadPaths.Distinct(StringComparer.OrdinalIgnoreCase)));
                opts = opts.WithImports(userOpts.Imports);
                opts = opts.WithReferences(userOpts.References);
                execStateCache.ScriptOptions = opts;

                var script = Create <object>(string.Empty, execStateCache.ScriptOptions, typeof(IScriptGlobals), null);
                execStateCache.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                execStateCache.ScriptState = script.RunAsync(execStateCache.Globals, execStateCache.CancellationTokenSource.Token).Result;
                if (showHelp)
                {
                    this.replEditor.OutputPrintLine(Help);
                }
            }, execStateCache.CancellationTokenSource.Token)
            .ContinueWith(t => {
                execStateCache.IsInitializing = false;
                var ex = t.Exception;
                if (!t.IsCanceled && !t.IsFaulted)
                {
                    CommandExecuted();
                }
                else
                {
                    replEditor.OutputPrintLine(string.Format("Could not create the script:\n\n{0}", ex));
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 8
0
        void SearchNewThread(object o)
        {
            AppCulture.InitializeCulture();
            try {
                var searchMsg = SearchResult.CreateMessage(filterSearcherOptions.Context, dnSpy_Resources.Searching, TextTokenKind.Text, true);
                SearchingResult = searchMsg;
                AddSearchResultNoCheck(searchMsg);
                var opts = new ParallelOptions {
                    CancellationToken      = cancellationTokenSource.Token,
                    MaxDegreeOfParallelism = Environment.ProcessorCount,
                };

                if (o is IDnSpyFileNode[])
                {
                    Parallel.ForEach((IDnSpyFileNode[])o, opts, node => {
                        AppCulture.InitializeCulture();
                        cancellationTokenSource.Token.ThrowIfCancellationRequested();
                        var searcher = new FilterSearcher(filterSearcherOptions);
                        searcher.SearchAssemblies(new IDnSpyFileNode[] { node });
                    });
                }
                else if (o is SearchTypeInfo[])
                {
                    Parallel.ForEach((SearchTypeInfo[])o, opts, info => {
                        AppCulture.InitializeCulture();
                        cancellationTokenSource.Token.ThrowIfCancellationRequested();
                        var searcher = new FilterSearcher(filterSearcherOptions);
                        searcher.SearchTypes(new SearchTypeInfo[] { info });
                    });
                }
                else
                {
                    throw new InvalidOperationException();
                }
            }
            catch (AggregateException ex) {
                if (ex.InnerExceptions.Any(a => a is TooManyResultsException))
                {
                    TooManyResults = true;
                }
                else
                {
                    throw;
                }
            }
            catch (TooManyResultsException) {
                TooManyResults = true;
            }
            finally {
                filterSearcherOptions.Dispatcher.BeginInvoke(DISPATCHER_PRIO, new Action(SearchCompleted));
            }
        }
Esempio n. 9
0
 void ThreadProc()
 {
     AppCulture.InitializeCulture();
     try {
         task.Execute(this);
     }
     catch (OperationCanceledException) {
         QueueAction(new MyAction(() => WasCanceled = true), false);
     }
     catch (Exception ex) {
         errorMessage = ex.Message;
     }
     QueueAction(new MyAction(OnTaskCompleted), false);
 }
Esempio n. 10
0
 void ThreadMethodImpl()
 {
     Debug.Assert(isRunning);
     Debug.Assert(!completedSuccessfully);
     AppCulture.InitializeCulture();
     try {
         ThreadMethod();
         completedSuccessfully = true;
     }
     catch (OperationCanceledException) {
     }
     ExecInUIThread(RemoveMessageNode_UI);
     isRunning = false;
 }
Esempio n. 11
0
        void Refresh()
        {
            if (IsRefreshing)
            {
                return;
            }

            Collection.Clear();
            cancellationToken = new CancellationTokenSource();
            refreshThread     = new Thread(() => {
                AppCulture.InitializeCulture();
                RefreshAsync();
            });
            OnPropertyChanged("IsRefreshing");
            refreshThread.Start();
        }
Esempio n. 12
0
        public OpenFileListVM(bool syntaxHighlight, FileListManager fileListManager, Func <string, string> askUser)
        {
            this.syntaxHighlight           = syntaxHighlight;
            this.fileListManager           = fileListManager;
            this.askUser                   = askUser;
            this.fileListColl              = new ObservableCollection <FileListVM>();
            this.collectionView            = (ListCollectionView)CollectionViewSource.GetDefaultView(fileListColl);
            this.collectionView.CustomSort = new FileListVM_Comparer();
            this.selectedItems             = new FileListVM[0];
            this.removedFileLists          = new HashSet <FileListVM>();
            this.addedFileLists            = new List <FileListVM>();
            this.cancellationTokenSource   = new CancellationTokenSource();
            this.searchingForDefaultLists  = true;

            var hash = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var fileList in fileListManager.FileLists)
            {
                hash.Add(fileList.Name);
                fileListColl.Add(new FileListVM(this, fileList, true, true));
            }
            Refilter();

            Task.Factory.StartNew(() => {
                AppCulture.InitializeCulture();
                return(new DefaultFileListFinder(cancellationTokenSource.Token).Find());
            }, cancellationTokenSource.Token)
            .ContinueWith(t => {
                var ex = t.Exception;
                SearchingForDefaultLists = false;
                if (!t.IsCanceled && !t.IsFaulted)
                {
                    foreach (var defaultList in t.Result)
                    {
                        if (hash.Contains(defaultList.Name))
                        {
                            continue;
                        }
                        var fileList = new FileList(defaultList);
                        fileListColl.Add(new FileListVM(this, fileList, false, false));
                    }
                    Refilter();
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 13
0
        void SearchNewThread(object o)
        {
            AppCulture.InitializeCulture();
            var files = (IDnSpyFileNode[])o;

            try {
                var searchMsg = SearchResult.CreateMessage(filterSearcherOptions.Context, dnSpy_Resources.Searching, TextTokenKind.Text, true);
                SearchingResult = searchMsg;
                AddSearchResultNoCheck(searchMsg);
                var searcher = new FilterSearcher(filterSearcherOptions);
                searcher.SearchAssemblies(files);
            }
            catch (TooManyResultsException) {
                TooManyResults = true;
            }
            finally {
                filterSearcherOptions.Dispatcher.BeginInvoke(DISPATCHER_PRIO, new Action(SearchCompleted));
            }
        }
Esempio n. 14
0
        public void AsyncExec(Action <CancellationTokenSource> preExec, Action asyncAction, Action <IAsyncShowResult> postExec)
        {
            CancelAsyncWorker();

            var ctx = new AsyncWorkerContext();

            asyncWorkerContext = ctx;
            preExec(ctx.CancellationTokenSource);
            Task.Factory.StartNew(() => {
                AppCulture.InitializeCulture();
                asyncAction();
            }, ctx.CancellationTokenSource.Token)
            .ContinueWith(t => {
                if (asyncWorkerContext == ctx)
                {
                    asyncWorkerContext = null;
                }
                ctx.Dispose();
                postExec(new AsyncShowResult(t, false));
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 15
0
        public OpenFromGACVM(bool syntaxHighlight)
        {
            this.syntaxHighlight           = syntaxHighlight;
            this.gacFileList               = new ObservableCollection <GACFileVM>();
            this.collectionView            = (ListCollectionView)CollectionViewSource.GetDefaultView(gacFileList);
            this.collectionView.CustomSort = new GACFileVM_Comparer();
            this.cancellationTokenSource   = new CancellationTokenSource();
            this.searchingGAC              = true;
            this.uniqueFiles               = new HashSet <GACFileVM>(new GACFileVM_EqualityComparer());

            var dispatcher = Dispatcher.CurrentDispatcher;

            Task.Factory.StartNew(() => {
                AppCulture.InitializeCulture();
                new GACFileFinder(this, dispatcher, cancellationTokenSource.Token).Find();
            }, cancellationTokenSource.Token)
            .ContinueWith(t => {
                var ex       = t.Exception;
                SearchingGAC = false;
                Refilter();
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
Esempio n. 16
0
            public void Execute(ExportToProjectVM vm)
            {
                vm.ProgressMinimum = 0;
                vm.ProgressMaximum = 1;
                vm.TotalProgress   = 0;
                vm.IsIndeterminate = false;
                Task.Factory.StartNew(() => {
                    AppCulture.InitializeCulture();
                    var decompilationContext = new DecompilationContext {
                        CancellationToken      = cancellationTokenSource.Token,
                        GetDisableAssemblyLoad = () => owner.fileTreeView.FileManager.DisableAssemblyLoad(),
                    };
                    var options            = new ProjectCreatorOptions(vm.Directory, cancellationTokenSource.Token);
                    options.ProjectVersion = vm.ProjectVersion;
                    if (vm.CreateSolution)
                    {
                        options.SolutionFilename = vm.SolutionFilename;
                    }
                    options.Logger           = this;
                    options.ProgressListener = this;

                    bool hasProjectGuid = vm.ProjectGuid.Value != null;
                    string guidFormat   = null;
                    int guidNum         = 0;
                    if (hasProjectGuid)
                    {
                        string guidStr = vm.ProjectGuid.Value.ToString();
                        guidNum        = int.Parse(guidStr.Substring(36 - 8, 8), NumberStyles.HexNumber);
                        guidFormat     = guidStr.Substring(0, 36 - 8) + "{0:X8}";
                    }
                    foreach (var module in modules.OrderBy(a => a.Location, StringComparer.InvariantCultureIgnoreCase))
                    {
                        var projOpts = new ProjectModuleOptions(module, vm.Language, decompilationContext)
                        {
                            DontReferenceStdLib = vm.DontReferenceStdLib,
                            UnpackResources     = vm.UnpackResources,
                            CreateResX          = vm.CreateResX,
                            DecompileXaml       = vm.DecompileXaml,
                            ProjectGuid         = hasProjectGuid ? new Guid(string.Format(guidFormat, guidNum++)) : Guid.NewGuid(),
                        };
                        if (bamlDecompiler != null)
                        {
                            var o = BamlDecompilerOptions.Create(vm.Language);
                            projOpts.DecompileBaml = (a, b, c, d) => bamlDecompiler.Decompile(a, b, c, o, d);
                        }
                        options.ProjectModules.Add(projOpts);
                    }
                    var creator = new MSBuildProjectCreator(options);

                    creator.Create();
                    if (vm.CreateSolution)
                    {
                        fileToOpen = creator.SolutionFilename;
                    }
                    else
                    {
                        fileToOpen = creator.ProjectFilenames.FirstOrDefault();
                    }
                }, cancellationTokenSource.Token)
                .ContinueWith(t => {
                    var ex = t.Exception;
                    if (ex != null)
                    {
                        Error(string.Format(dnSpy_Resources.ErrorExceptionOccurred, ex));
                    }
                    EmtpyErrorList();
                    vm.OnExportComplete();
                    if (!vm.ExportErrors)
                    {
                        dlg.Close();
                        if (vm.OpenProject)
                        {
                            OpenProject();
                        }
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
            }
Esempio n. 17
0
        bool ExecuteCommandInternal(string input)
        {
            Debug.Assert(execState != null && !execState.IsInitializing);
            if (execState == null || execState.IsInitializing)
            {
                return(true);
            }
            lock (lockObj) {
                Debug.Assert(execState.ExecTask == null && !execState.Executing);
                if (execState.ExecTask != null || execState.Executing)
                {
                    return(true);
                }
                execState.Executing = true;
            }

            try {
                var scState = ParseScriptCommand(input);
                if (scState != null)
                {
                    if (execState != null)
                    {
                        lock (lockObj)
                            execState.Executing = false;
                    }
                    scState.Command.Execute(this, scState.Arguments);
                    bool isReset = scState.Command is ResetCommand;
                    if (!isReset)
                    {
                        CommandExecuted();
                    }
                    return(true);
                }

                var oldState = execState;

                var taskSched = TaskScheduler.FromCurrentSynchronizationContext();
                Task.Run(() => {
                    AppCulture.InitializeCulture();
                    oldState.CancellationTokenSource.Token.ThrowIfCancellationRequested();

                    var opts     = oldState.ScriptOptions.WithReferences(Array.Empty <MetadataReference>()).WithImports(Array.Empty <string>());
                    var execTask = oldState.ScriptState.ContinueWithAsync(input, opts, oldState.CancellationTokenSource.Token);
                    oldState.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                    lock (lockObj) {
                        if (oldState == execState)
                        {
                            oldState.ExecTask = execTask;
                        }
                    }
                    execTask.ContinueWith(t => {
                        var ex = t.Exception;
                        bool isActive;
                        lock (lockObj) {
                            isActive = oldState == execState;
                            if (isActive)
                            {
                                oldState.ExecTask = null;
                            }
                        }
                        if (isActive)
                        {
                            if (ex != null)
                            {
                                replEditor.OutputPrintLine(ex.ToString());
                            }

                            if (!t.IsCanceled && !t.IsFaulted)
                            {
                                oldState.ScriptState = t.Result;
                                var val = t.Result.ReturnValue;
                                if (val != null)
                                {
                                    replEditor.OutputPrintLine(Format(val));
                                }
                            }

                            CommandExecuted();
                        }
                    }, CancellationToken.None, TaskContinuationOptions.None, taskSched);
                })
                .ContinueWith(t => {
                    if (execState != null)
                    {
                        lock (lockObj)
                            execState.Executing = false;
                    }
                    var innerEx = t.Exception?.InnerException;
                    if (innerEx is CompilationErrorException)
                    {
                        var cee = (CompilationErrorException)innerEx;
                        PrintDiagnostics(cee.Diagnostics);
                        CommandExecuted();
                    }
                    else if (innerEx is OperationCanceledException)
                    {
                        CommandExecuted();
                    }
                    else
                    {
                        ReportException(t);
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, taskSched);

                return(true);
            }
            catch (Exception ex) {
                if (execState != null)
                {
                    lock (lockObj)
                        execState.Executing = false;
                }
                replEditor.OutputPrintLine(string.Format("Error executing script:\n\n{0}", ex));
                return(false);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                // TODO: change this value to a cache size that is appropriate for your application
                rootFrame.CacheSize = 1;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
#if WINDOWS_PHONE_APP
                // Removes the turnstile navigation for startup.
                if (rootFrame.ContentTransitions != null)
                {
                    this.transitions = new TransitionCollection();
                    foreach (var c in rootFrame.ContentTransitions)
                    {
                        this.transitions.Add(c);
                    }
                }

                rootFrame.ContentTransitions = null;
                rootFrame.Navigated         += this.RootFrame_FirstNavigated;
#endif

                #region AdpPushClient

                await ADPPushSDK.AdpPushClient.Instance.Init(AppConstant.AppId, AppConstant.ApiKey, AppConstant.Username, AppConstant.Password);

                ADPPushSDK.AdpPushClient.Instance.SetDevelopment(false);

                ADPPushSDK.AdpPushClient.Instance.PushNotificationReceived += InstanceOnPushNotificationReceived;

                #endregion

                AppCulture.SetCulture();
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter

                if (!AppSetting.IsRegisterd)
                {
                    rootFrame.Navigate(typeof(RegisterationPage), e.Arguments);
                }
                else
                {
                    await ADPPushSDK.AdpPushClient.Instance.Register(AppSetting.UserId);

                    if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
                    {
                        throw new Exception("Failed to create initial page");
                    }
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }
Esempio n. 19
0
        public void Create()
        {
            SatelliteAssemblyFinder satelliteAssemblyFinder = null;

            try {
                var opts = new ParallelOptions {
                    CancellationToken      = options.CancellationToken,
                    MaxDegreeOfParallelism = options.NumberOfThreads <= 0 ? Environment.ProcessorCount : options.NumberOfThreads,
                };
                var filenameCreator = new FilenameCreator(options.Directory);
                var ctx             = new DecompileContext(options.CancellationToken, logger);
                satelliteAssemblyFinder = new SatelliteAssemblyFinder();
                Parallel.ForEach(options.ProjectModules, opts, modOpts => {
                    AppCulture.InitializeCulture();
                    options.CancellationToken.ThrowIfCancellationRequested();
                    string name;
                    lock (filenameCreator)
                        name = filenameCreator.Create(modOpts.Module);
                    var p = new Project(modOpts, name, satelliteAssemblyFinder);
                    lock (projects)
                        projects.Add(p);
                    p.CreateProjectFiles(ctx);
                });

                var  jobs = GetJobs().ToArray();
                bool writeSolutionFile = !string.IsNullOrEmpty(options.SolutionFilename);
                int  maxProgress       = jobs.Length + projects.Count;
                if (writeSolutionFile)
                {
                    maxProgress++;
                }
                progressListener.SetMaxProgress(maxProgress);

                Parallel.ForEach(GetJobs(), opts, job => {
                    AppCulture.InitializeCulture();
                    options.CancellationToken.ThrowIfCancellationRequested();
                    try {
                        job.Create(ctx);
                    }
                    catch (OperationCanceledException) {
                        throw;
                    }
                    catch (Exception ex) {
                        var fjob = job as IFileJob;
                        if (fjob != null)
                        {
                            logger.Error(string.Format(Languages_Resources.MSBuild_FileCreationFailed3, fjob.Filename, job.Description, ex.Message));
                        }
                        else
                        {
                            logger.Error(string.Format(Languages_Resources.MSBuild_FileCreationFailed2, job.Description, ex.Message));
                        }
                    }
                    progressListener.SetProgress(Interlocked.Increment(ref totalProgress));
                });
                Parallel.ForEach(projects, opts, p => {
                    AppCulture.InitializeCulture();
                    options.CancellationToken.ThrowIfCancellationRequested();
                    try {
                        var writer = new ProjectWriter(p, p.Options.ProjectVersion ?? options.ProjectVersion, projects, options.UserGACPaths);
                        writer.Write();
                    }
                    catch (OperationCanceledException) {
                        throw;
                    }
                    catch (Exception ex) {
                        logger.Error(string.Format(Languages_Resources.MSBuild_FailedToCreateProjectFile, p.Filename, ex.Message));
                    }
                    progressListener.SetProgress(Interlocked.Increment(ref totalProgress));
                });
                if (writeSolutionFile)
                {
                    options.CancellationToken.ThrowIfCancellationRequested();
                    try {
                        var writer = new SolutionWriter(options.ProjectVersion, projects, SolutionFilename);
                        writer.Write();
                    }
                    catch (OperationCanceledException) {
                        throw;
                    }
                    catch (Exception ex) {
                        logger.Error(string.Format(Languages_Resources.MSBuild_FailedToCreateSolutionFile, SolutionFilename, ex.Message));
                    }
                    progressListener.SetProgress(Interlocked.Increment(ref totalProgress));
                }
                Debug.Assert(totalProgress == maxProgress);
                progressListener.SetProgress(maxProgress);
            }
            finally {
                if (satelliteAssemblyFinder != null)
                {
                    satelliteAssemblyFinder.Dispose();
                }
            }
        }
Esempio n. 20
0
            public void Execute(ExportToProjectVM vm)
            {
                vm.ProgressMinimum = 0;
                vm.ProgressMaximum = 1;
                vm.TotalProgress   = 0;
                vm.IsIndeterminate = false;
                Task.Factory.StartNew(() => {
                    AppCulture.InitializeCulture();
                    var decompilationContext = new DecompilationContext {
                        CancellationToken      = cancellationTokenSource.Token,
                        GetDisableAssemblyLoad = () => owner.fileTreeView.FileManager.DisableAssemblyLoad(),
                    };
                    var options            = new ProjectCreatorOptions(vm.Directory, cancellationTokenSource.Token);
                    options.ProjectVersion = vm.ProjectVersion;
                    if (vm.CreateSolution)
                    {
                        options.SolutionFilename = vm.SolutionFilename;
                    }
                    options.Logger           = this;
                    options.ProgressListener = this;
                    foreach (var module in modules)
                    {
                        var projOpts = new ProjectModuleOptions(module, vm.Language, decompilationContext)
                        {
                            DontReferenceStdLib = vm.DontReferenceStdLib,
                            UnpackResources     = vm.UnpackResources,
                            CreateResX          = vm.CreateResX,
                            DecompileXaml       = vm.DecompileXaml,
                        };
                        if (owner.bamlDecompiler != null)
                        {
                            var o = BamlDecompilerOptions.Create(vm.Language);
                            projOpts.DecompileBaml = (a, b, c, d) => owner.bamlDecompiler.Value.Decompile(a, b, c, o, d);
                        }
                        options.ProjectModules.Add(projOpts);
                    }
                    var creator = new MSBuildProjectCreator(options);

                    creator.Create();
                    if (vm.CreateSolution)
                    {
                        fileToOpen = creator.SolutionFilename;
                    }
                    else
                    {
                        fileToOpen = creator.ProjectFilenames.FirstOrDefault();
                    }
                }, cancellationTokenSource.Token)
                .ContinueWith(t => {
                    var ex = t.Exception;
                    if (ex != null)
                    {
                        Error(string.Format(dnSpy_Resources.ErrorExceptionOccurred, ex));
                    }
                    EmtpyErrorList();
                    vm.OnExportComplete();
                    if (!vm.ExportErrors)
                    {
                        dlg.Close();
                        if (vm.OpenProject)
                        {
                            OpenProject();
                        }
                    }
                }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
            }