예제 #1
0
        void WriteFileInternal(string file, string sourceFile, Solution solution, bool saveProjects, ProgressMonitor monitor)
        {
            if (saveProjects)
            {
                var items = solution.GetAllSolutionItems().ToArray();
                monitor.BeginTask(items.Length + 1);
                foreach (var item in items)
                {
                    try {
                        monitor.BeginStep();
                        item.SavingSolution = true;
                        item.SaveAsync(monitor).Wait();
                    } finally {
                        item.SavingSolution = false;
                    }
                }
            }
            else
            {
                monitor.BeginTask(1);
                monitor.BeginStep();
            }

            SlnFile sln = new SlnFile();

            sln.FileName = file;
            if (File.Exists(sourceFile))
            {
                try {
                    sln.Read(sourceFile);
                } catch (Exception ex) {
                    LoggingService.LogError("Existing solution can't be updated since it can't be read", ex);
                }
            }

            sln.FormatVersion = format.SlnVersion;

            // Don't modify the product description if it already has a value
            if (string.IsNullOrEmpty(sln.ProductDescription))
            {
                sln.ProductDescription = format.ProductDescription;
            }

            solution.WriteSolution(monitor, sln);

            sln.Write(file);
            monitor.EndTask();
        }
예제 #2
0
        internal bool Build(ProgressMonitor monitor)
        {
            monitor.BeginTask("Package: " + Description, 1);
            DeployContext ctx = null;

            try {
                ctx = CreateDeployContext();
                if (ctx != null)
                {
                    ctx.FileFilter = this;
                }
                if (!OnBuild(monitor, ctx))
                {
                    return(false);
                }
            } catch (Exception ex) {
                monitor.ReportError("Package creation failed", ex);
                LoggingService.LogError("Package creation failed", ex);
                return(false);
            } finally {
                monitor.EndTask();
                if (ctx != null)
                {
                    ctx.Dispose();
                }
            }
            return(true);
        }
 void RunActionsWithProgressMonitor(
     ProgressMonitorStatusMessage progressMessage,
     IList <IPackageAction> installPackageActions,
     TaskCompletionSource <bool> taskCompletionSource,
     bool clearConsole,
     CancellationTokenSource cancellationTokenSource)
 {
     using (ProgressMonitor monitor = progressMonitorFactory.CreateProgressMonitor(progressMessage.Status, clearConsole, cancellationTokenSource)) {
         using (PackageManagementEventsMonitor eventMonitor = CreateEventMonitor(monitor, taskCompletionSource)) {
             try {
                 monitor.BeginTask(null, installPackageActions.Count);
                 RunActionsWithProgressMonitor(monitor, installPackageActions);
                 eventMonitor.ReportResult(progressMessage);
             } catch (Exception ex) {
                 RemoveInstallActions(installPackageActions);
                 bool showPackageConsole = !monitor.CancellationToken.IsCancellationRequested;
                 eventMonitor.ReportError(progressMessage, ex, showPackageConsole);
             } finally {
                 monitor.EndTask();
                 GuiDispatch(() => {
                     RemoveInstallActions(installPackageActions);
                     packageManagementEvents.OnPackageOperationsFinished();
                 });
             }
         }
     }
 }
        protected async override Task OnExecute(ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
        {
            if (data == null || !data.SupportsIntegration || String.IsNullOrEmpty(data.ExecuteTargetName))
            {
                await base.OnExecute(monitor, context, configuration);

                return;
            }

            OperationConsole console = context.ConsoleFactory.CreateConsole();

            monitor.BeginTask(GettextCatalog.GetString("Executing {0}", Project.Name), 1);
            try
            {
                ProcessWrapper process = Runtime.ProcessService.StartProcess("make",
                                                                             data.ExecuteTargetName,
                                                                             Project.BaseDirectory,
                                                                             console.Out,
                                                                             console.Error,
                                                                             null);

                await process.Task;

                monitor.Log.WriteLine(GettextCatalog.GetString("The application exited with code: {0}", process.ExitCode));
                monitor.Step(1);
            } catch (Exception e) {
                monitor.ReportError(GettextCatalog.GetString("Project could not be executed: "), e);
                return;
            } finally {
                monitor.EndTask();
                console.Dispose();
            }
        }
예제 #5
0
        void InstallEntry(ProgressMonitor monitor, DeployContext ctx, SolutionFolderItem entry, ConfigurationSelector configuration)
        {
            foreach (DeployFile df in DeployService.GetDeployFiles(ctx, new SolutionFolderItem[] { entry }, configuration))
            {
                string targetPath = df.ResolvedTargetFile;
                if (targetPath == null)
                {
                    monitor.ReportWarning("Could not copy file '" + df.RelativeTargetPath + "': Unknown target directory.");
                    continue;
                }

                CopyFile(monitor, df.SourcePath, df.ResolvedTargetFile, df.FileAttributes);
            }

            SolutionFolder c = entry as SolutionFolder;

            if (c != null)
            {
                monitor.BeginTask("Installing solution '" + c.Name + "'", c.Items.Count);
                foreach (SolutionFolderItem ce in c.Items)
                {
                    InstallEntry(monitor, ctx, ce, configuration);
                    monitor.Step(1);
                }
                monitor.EndTask();
            }
        }
        public void CreateSchemaCommand()
        {
            try {
                TaskService.Errors.Clear();

                string xml = Editor.Text;
                using (ProgressMonitor monitor = XmlEditorService.GetMonitor()) {
                    XmlDocument doc = XmlEditorService.ValidateWellFormedness(monitor, xml, FileName);
                    if (doc == null)
                    {
                        return;
                    }
                    monitor.BeginTask(GettextCatalog.GetString("Creating schema..."), 0);
                    try {
                        string schema = XmlEditorService.CreateSchema(Editor, xml);

                        string fileName = XmlEditorService.GenerateFileName(FileName, "{0}.xsd");
                        IdeApp.Workbench.NewDocument(fileName, "application/xml", schema);
                        monitor.ReportSuccess(GettextCatalog.GetString("Schema created."));
                    } catch (Exception ex) {
                        string msg = GettextCatalog.GetString("Error creating XML schema.");
                        LoggingService.LogError(msg, ex);
                        monitor.ReportError(msg, ex);
                    }
                }
            } catch (Exception ex) {
                MessageService.ShowError(ex.Message);
            }
        }
예제 #7
0
        private void CommandBinding_FileExportAudioMix(object sender, ExecutedRoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = "wav";
            dlg.Filter     = "Wave files|*.wav";

            if (dlg.ShowDialog() == true)
            {
                // create a separate monitor just for the file export to isolate this progress for the
                // modal window (else other running tasks could be shown in the modal dialog too)
                var progressMonitor = new ProgressMonitor();
                ProgressMonitor.GlobalInstance.AddChild(progressMonitor);

                // progress window needs to be open before beginning a task (else progress bar init does not get called)
                var modalProgress = new ModalProgressWindow(progressMonitor);
                modalProgress.Owner = this;
                modalProgress.Show();

                var progressReporter = progressMonitor.BeginTask("Rendering mix to file...", true);

                Task.Factory.StartNew(() => {
                    player.SaveToFile(new FileInfo(dlg.FileName), progressReporter);

                    Dispatcher.BeginInvoke((Action) delegate {
                        progressReporter.Finish();
                        modalProgress.Close();
                        ProgressMonitor.GlobalInstance.RemoveChild(progressMonitor);
                        ShowStatus("Audio export finished", true);
                    });
                });
            }
        }
        protected override void OnReadProject(ProgressMonitor monitor, MonoDevelop.Projects.MSBuild.MSBuildProject msproject)
        {
            base.OnReadProject(monitor, msproject);
            var ext = msproject.GetMonoDevelopProjectExtension("MonoDevelop.Autotools.MakefileInfo");

            if (ext == null)
            {
                return;
            }

            data = MakefileData.Read(ext);
            if (data == null)
            {
                return;
            }

            monitor.BeginTask(GettextCatalog.GetString("Updating project from Makefile"), 1);
            try {
                data.OwnerProject = Project;
                if (data.SupportsIntegration)
                {
                    data.UpdateProject(monitor, false);
                }
                monitor.Step(1);
            } catch (Exception e) {
                monitor.ReportError(GettextCatalog.GetString(
                                        "\tError loading Makefile for project {0}", Project.Name), e);
            } finally {
                monitor.EndTask();
            }
        }
        private void MakeStaticLibrary(Project project,
                                       ProjectFileCollection projectFiles,
                                       CProjectConfiguration configuration,
                                       ProjectPackageCollection packages,
                                       CompilerResults cr,
                                       ProgressMonitor monitor, string outputName)
        {
            if (!NeedsUpdate(projectFiles, configuration, outputName))
            {
                return;
            }

            string objectFiles = string.Join(" ", ObjectFiles(projectFiles, configuration, true));
            string args        = string.Format("rcs \"{0}\" {1}", outputName, objectFiles);

            monitor.BeginTask(GettextCatalog.GetString("Generating static library {0} from object files", Path.GetFileName(outputName)), 1);

            string errorOutput;
            int    exitCode = ExecuteCommand("ar", args, Path.GetDirectoryName(outputName), monitor, out errorOutput);

            if (exitCode == 0)
            {
                monitor.Step(1);
            }
            monitor.EndTask();

            ParseCompilerOutput(errorOutput, cr);
            ParseLinkerOutput(errorOutput, cr);
            CheckReturnCode(exitCode, cr);
        }
예제 #10
0
        public async void OnReload()
        {
            var  solutions = new HashSet <Solution> ();
            Task task      = Task.CompletedTask;

            using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
                m.BeginTask(null, CurrentNodes.Length);
                foreach (ITreeNavigator node in CurrentNodes)
                {
                    UnknownSolutionItem entry = (UnknownSolutionItem)node.DataItem;
                    if (!entry.Enabled)
                    {
                        entry.Enabled = true;
                        solutions.Add(entry.ParentSolution);
                    }
                    var am = m.BeginAsyncStep(1);
                    var t  = entry.ParentFolder.ReloadItem(am, entry).ContinueWith(ta => {
                        am.Dispose();
                    });
                    task = Task.WhenAll(task, t);
                }
                m.EndTask();
            }
            await task;
            await IdeApp.ProjectOperations.SaveAsync(solutions);
        }
예제 #11
0
        public Task StartAsync()
        {
            tracker = CreateProgressMonitor();
            tracker.BeginTask(GetDescription(), 1);

            // Sync invoke background worker which will end up doing async invoke on the internal run.
            return(Task.Run(async() => await RunAsync().ConfigureAwait(false)).ContinueWith(t => {
                if (t.IsFaulted)
                {
                    var exception = t.Exception.FlattenAggregate().InnerException;
                    if (exception is DllNotFoundException)
                    {
                        var msg = GettextCatalog.GetString("The operation could not be completed because a shared library is missing: ");
                        tracker.ReportError(msg + exception.Message, null);
                        LoggingService.LogError("Version Control command failed: ", exception);
                    }
                    else
                    {
                        string msg = GettextCatalog.GetString("Version control operation failed");
                        tracker.ReportError($"{msg}: {exception.Message}", exception);
                        if (IdeApp.Workbench.RootWindow?.Visible == false)
                        {
                            ReportError(msg, exception.Message, exception);
                        }
                    }
                }
                Wakeup();
            }, Runtime.MainTaskScheduler));
        }
예제 #12
0
        public async Task <BuildResult> Clean(ProgressMonitor monitor, ConfigurationSelector configuration, OperationContext operationContext = null)
        {
            if (ParentSolution == null)
            {
                return(new BuildResult());
            }
            SolutionConfiguration conf = ParentSolution.GetConfiguration(configuration);

            if (conf == null)
            {
                return(new BuildResult());
            }

            ReadOnlyCollection <SolutionItem> allProjects;

            try {
                allProjects = GetAllBuildableEntries(configuration, true, true);
            } catch (CyclicDependencyException) {
                monitor.ReportError(GettextCatalog.GetString("Cyclic dependencies are not supported."), null);
                return(new BuildResult("", 1, 1));
            }

            monitor.BeginTask(GettextCatalog.GetString("Cleaning Solution: {0} ({1})", Name, configuration.ToString()), allProjects.Count);
            try {
                return(await RunParallelBuildOperation(monitor, configuration, allProjects, (ProgressMonitor m, SolutionItem item) => {
                    return item.Clean(m, configuration, operationContext);
                }, false));
            }
            finally {
                monitor.EndTask();
            }
        }
예제 #13
0
        ///	<summary>
        /// Perform push operation between local and remote repository - set remote
        /// refs appropriately, send needed objects and update local tracking refs.
        /// <para />
        /// When <seealso cref="Transport.DryRun"/> is true, result of this operation is
        /// just estimation of real operation result, no real action is performed.
        /// </summary>
        /// <param name="monitor">
        /// Progress monitor used for feedback about operation.
        /// </param>
        /// <returns> result of push operation with complete status description. </returns>
        /// <exception cref="NotSupportedException">
        /// When push operation is not supported by provided transport.
        /// </exception>
        /// <exception cref="TransportException">
        /// When some error occurred during operation, like I/O, protocol
        /// error, or local database consistency error.
        /// </exception>
        public PushResult execute(ProgressMonitor monitor)
        {
            monitor.BeginTask(PROGRESS_OPENING_CONNECTION, ProgressMonitor.UNKNOWN);
            _connection = _transport.openPush();

            try
            {
                monitor.EndTask();

                IDictionary <string, RemoteRefUpdate> preprocessed = PrepareRemoteUpdates();
                if (_transport.DryRun)
                {
                    ModifyUpdatesForDryRun();
                }
                else if (preprocessed.Count != 0)
                {
                    _connection.Push(monitor, preprocessed);
                }
            }
            finally
            {
                _connection.Close();
            }

            if (!_transport.DryRun)
            {
                UpdateTrackingRefs();
            }

            return(PrepareOperationResult());
        }
        /// <exception cref="System.IO.IOException"></exception>
        private void BreakModifies(ContentSource.Pair reader, ProgressMonitor pm)
        {
            AList <DiffEntry> newEntries = new AList <DiffEntry>(entries.Count);

            pm.BeginTask(JGitText.Get().renamesBreakingModifies, entries.Count);
            for (int i = 0; i < entries.Count; i++)
            {
                DiffEntry e = entries[i];
                if (e.GetChangeType() == DiffEntry.ChangeType.MODIFY)
                {
                    int score = CalculateModifyScore(reader, e);
                    if (score < breakScore)
                    {
                        IList <DiffEntry> tmp = DiffEntry.BreakModify(e);
                        DiffEntry         del = tmp[0];
                        del.score = score;
                        deleted.AddItem(del);
                        added.AddItem(tmp[1]);
                    }
                    else
                    {
                        newEntries.AddItem(e);
                    }
                }
                else
                {
                    newEntries.AddItem(e);
                }
                pm.Update(1);
            }
            entries = newEntries;
        }
예제 #15
0
        internal static void Report(ProgressMonitor monitor, List <Diagnostic> allDiagnostics, Projects.WorkspaceObject parent)
        {
            monitor.BeginTask(GettextCatalog.GetString("Reporting results..."), allDiagnostics.Count);
            TaskService.Errors.Clear();
            TaskService.Errors.AddRange(allDiagnostics.Select(diagnostic => {
                var startLinePosition = diagnostic.Location.GetLineSpan().StartLinePosition;
                return(new TaskListEntry(
                           diagnostic.Location.SourceTree.FilePath,
                           diagnostic.GetMessage(),
                           startLinePosition.Character + 1,
                           startLinePosition.Line + 1,
                           GetSeverity(diagnostic),
                           TaskPriority.Normal,
                           parent,
                           null,
                           diagnostic.Descriptor.Category
                           ));
            }));

            monitor.EndTask();
            if (!allDiagnostics.Any())
            {
                monitor.ReportSuccess(GettextCatalog.GetString("Analysis successful."));
            }
            else
            {
                ShowAnalyzationResults();
            }
        }
예제 #16
0
        /// <summary>
        /// Checks that the xml in this view is well-formed.
        /// </summary>
        public static XmlDocument ValidateWellFormedness(ProgressMonitor monitor, string xml, string fileName)
        {
            monitor.BeginTask(GettextCatalog.GetString("Validating XML..."), 1);
            bool        error = false;
            XmlDocument doc   = null;

            try {
                doc = new XmlDocument();
                doc.LoadXml(xml);
            } catch (XmlException ex) {
                monitor.ReportError(ex.Message, ex);
                AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error);
                error = true;
            }

            if (error)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Validation failed."));
                TaskService.ShowErrors();
            }
            else
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("XML is valid."));
            }

            monitor.EndTask();
            return(error? null: doc);
        }
        public List <Match> FindAllMatches(ProgressMonitor progressMonitor, Action <List <Match> > callback)
        {
            List <Match> matches = null;

            // NOTE The following task is passed the "default" task scheduler, because otherwise
            //      it uses the "current" scheduler, which can be the UI scheduler when called
            //      from a task run by the TaskScheduler.FromCurrentSynchronizationContext(), leading
            //      to a blocked UI.

            Task.Factory.StartNew(() => {
                var progressReporter = progressMonitor.BeginTask("Matching hashes...", true);

                Action <double> progressCallback = (progress) => {
                    progressReporter.ReportProgress(progress);
                };

                Stopwatch sw = new Stopwatch();
                sw.Start();
                store.Threshold       = FingerprintBerThreshold;
                store.FingerprintSize = FingerprintSize;
                matches = store.FindAllMatches(progressCallback);
                sw.Stop();
                Debug.WriteLine(matches.Count + " matches found in {0}", sw.Elapsed);

                matches = MatchProcessor.FilterDuplicateMatches(matches, progressCallback);
                Debug.WriteLine(matches.Count + " matches found (filtered)");

                progressReporter.Finish();
            }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) // Use default scheduler, see NOTE above
            .ContinueWith(task => {
                callback.Invoke(matches);
            }, TaskScheduler.FromCurrentSynchronizationContext());

            return(matches);
        }
 private ICollection <WalkRemoteObjectDatabase> ExpandOneAlternate(AnyObjectId id, ProgressMonitor pm)
 {
     while (_noAlternatesYet.Count > 0)
     {
         WalkRemoteObjectDatabase wrr = _noAlternatesYet.First.Value;
         _noAlternatesYet.RemoveFirst();
         try
         {
             pm.BeginTask("Listing alternates", ProgressMonitor.UNKNOWN);
             ICollection <WalkRemoteObjectDatabase> altList = wrr.getAlternates();
             if (altList != null && altList.Count > 0)
             {
                 return(altList);
             }
         }
         catch (IOException e)
         {
             // Try another repository.
             //
             RecordError(id, e);
         }
         finally
         {
             pm.EndTask();
         }
     }
     return(null);
 }
예제 #19
0
        public async Task <BuildResult> Build(ProgressMonitor monitor, ConfigurationSelector configuration, bool buildReferencedTargets = false, OperationContext operationContext = null)
        {
            ReadOnlyCollection <SolutionItem> allProjects;

            try {
                allProjects = GetAllBuildableEntries(configuration, true, true);
            } catch (CyclicDependencyException) {
                monitor.ReportError(GettextCatalog.GetString("Cyclic dependencies are not supported."), null);
                return(new BuildResult("", 1, 1));
            }

            if (operationContext == null)
            {
                operationContext = new OperationContext();
            }

            bool        operationStarted = false;
            BuildResult result           = null;

            try {
                monitor.BeginTask(GettextCatalog.GetString("Building Solution: {0} ({1})", Name, configuration.ToString()), allProjects.Count);

                operationStarted = ParentSolution != null && await ParentSolution.BeginBuildOperation(monitor, configuration, operationContext);

                return(result = await RunParallelBuildOperation(monitor, configuration, allProjects, (ProgressMonitor m, SolutionItem item) => {
                    return item.Build(m, configuration, false, operationContext);
                }, false));
            } finally {
                if (operationStarted)
                {
                    await ParentSolution.EndBuildOperation(monitor, configuration, operationContext, result);
                }
                monitor.EndTask();
            }
        }
예제 #20
0
 private ICollection <WalkRemoteObjectDatabase> ExpandOneAlternate(AnyObjectId id,
                                                                   ProgressMonitor pm)
 {
     while (!noAlternatesYet.IsEmpty())
     {
         WalkRemoteObjectDatabase wrr = noAlternatesYet.RemoveFirst();
         try
         {
             pm.BeginTask(JGitText.Get().listingAlternates, ProgressMonitor.UNKNOWN);
             ICollection <WalkRemoteObjectDatabase> altList = wrr.GetAlternates();
             if (altList != null && !altList.IsEmpty())
             {
                 return(altList);
             }
         }
         catch (IOException e)
         {
             // Try another repository.
             //
             RecordError(id, e);
         }
         finally
         {
             pm.EndTask();
         }
     }
     return(null);
 }
예제 #21
0
        static async Task Update(ProgressMonitor monitor, IEnumerator <ProjectFile> fileEnumerator, bool force, int succeeded, int warnings, int errors)
        {
            ProjectFile file = fileEnumerator.Current;
            SingleProjectFileCustomTool tool;
            ProjectFile genFile;

            bool shouldRun;

            while (!(shouldRun = ShouldRunGenerator(file, file.Project, force, out tool, out genFile)) && fileEnumerator.MoveNext())
            {
                continue;
            }

            //no files which can be generated in remaining elements of the collection, nothing to do
            if (!shouldRun)
            {
                WriteSummaryResults(monitor, succeeded, warnings, errors);
                return;
            }

            TaskService.Errors.ClearByOwner(file);

            var result = new SingleFileCustomToolResult();

            monitor.BeginTask(GettextCatalog.GetString("Running generator '{0}' on file '{1}'...", file.Generator, file.Name), 1);

            try {
                await tool.Generate(monitor, file.Project, file, result);

                if (!monitor.HasErrors && !monitor.HasWarnings)
                {
                    monitor.Log.WriteLine(GettextCatalog.GetString("File '{0}' was generated successfully.", result.GeneratedFilePath));
                    succeeded++;
                }
                else if (!monitor.HasErrors)
                {
                    monitor.Log.WriteLine(GettextCatalog.GetString("File '{0}' was generated with warnings.", result.GeneratedFilePath));
                    warnings++;
                }
                else
                {
                    monitor.Log.WriteLine(GettextCatalog.GetString("Errors in file '{0}' generation.", result.GeneratedFilePath));
                    errors++;
                }

                //check that we can process further. If UpdateCompleted returns `true` this means no errors or non-fatal errors occured
                if (UpdateCompleted(monitor, file, genFile, result, true) && fileEnumerator.MoveNext())
                {
                    await Update(monitor, fileEnumerator, force, succeeded, warnings, errors);
                }
                else
                {
                    WriteSummaryResults(monitor, succeeded, warnings, errors);
                }
            } catch (Exception ex) {
                result.UnhandledException = ex;
                UpdateCompleted(monitor, file, genFile, result, true);
            }
        }
        public ProgressMonitorWrapperJob(IAnalysisJob wrappedJob, string message)
        {
            this.wrappedJob = wrappedJob;
            monitor         = IdeApp.Workbench.ProgressMonitors.GetStatusProgressMonitor(message, null, false);
            var work = wrappedJob.GetFiles().Sum(f => wrappedJob.GetIssueProviders(f).Count());

            monitor.BeginTask(message, work);
        }
예제 #23
0
        public void Start()
        {
            tracker = CreateProgressMonitor();
            tracker.BeginTask(GetDescription(), 1);

            // Sync invoke background worker which will end up doing async invoke on the internal run.
            BackgroundWorker();
        }
예제 #24
0
파일: AmazonS3.cs 프로젝트: shoff/ngit
        /// <exception cref="System.IO.IOException"></exception>
        private void PutImpl(string bucket, string key, byte[] csum, TemporaryBuffer buf,
                             ProgressMonitor monitor, string monitorTask)
        {
            if (monitor == null)
            {
                monitor = NullProgressMonitor.INSTANCE;
            }
            if (monitorTask == null)
            {
                monitorTask = MessageFormat.Format(JGitText.Get().progressMonUploading, key);
            }
            string md5str = Base64.EncodeBytes(csum);
            long   len    = buf.Length();
            string lenstr = len.ToString();

            for (int curAttempt = 0; curAttempt < maxAttempts; curAttempt++)
            {
                HttpURLConnection c = Open("PUT", bucket, key);
                c.SetRequestProperty("Content-Length", lenstr);
                c.SetRequestProperty("Content-MD5", md5str);
                c.SetRequestProperty(X_AMZ_ACL, acl);
                encryption.Request(c, X_AMZ_META);
                Authorize(c);
                c.SetDoOutput(true);
                c.SetFixedLengthStreamingMode((int)len);
                monitor.BeginTask(monitorTask, (int)(len / 1024));
                OutputStream os = c.GetOutputStream();
                try
                {
                    buf.WriteTo(os, monitor);
                }
                finally
                {
                    monitor.EndTask();
                    os.Close();
                }
                switch (HttpSupport.Response(c))
                {
                case HttpURLConnection.HTTP_OK:
                {
                    return;
                }

                case HttpURLConnection.HTTP_INTERNAL_ERROR:
                {
                    continue;
                    goto default;
                }

                default:
                {
                    throw Error("Writing", key, c);
                }
                }
            }
            throw MaxAttempts("Writing", key);
        }
예제 #25
0
		public async Task SaveAsync (ProgressMonitor monitor)
		{
			monitor.BeginTask (GettextCatalog.GetString ("Saving Workspace..."), Items.Count);
			List<WorkspaceItem> items = new List<WorkspaceItem> (Items);
			foreach (WorkspaceItem it in items) {
				await it.SaveAsync (monitor);
				monitor.Step (1);
			}
			monitor.EndTask ();
		}
예제 #26
0
        void WriteProjects(SolutionFolder folder, SlnFile sln, ProgressMonitor monitor, HashSet <string> unknownProjects)
        {
            monitor.BeginTask(folder.Items.Count);
            foreach (SolutionFolderItem ce in folder.Items.ToArray())
            {
                monitor.BeginStep();
                if (ce is SolutionItem)
                {
                    SolutionItem item = (SolutionItem)ce;

                    var proj = sln.Projects.GetOrCreateProject(ce.ItemId);
                    proj.TypeGuid = item.TypeGuid;
                    proj.Name     = item.Name;
                    proj.FilePath = FileService.NormalizeRelativePath(FileService.AbsoluteToRelativePath(sln.BaseDirectory, item.FileName)).Replace('/', '\\');

                    var sec = proj.Sections.GetOrCreateSection("MonoDevelopProperties", SlnSectionType.PreProcess);
                    sec.SkipIfEmpty = true;
                    folder.ParentSolution.WriteSolutionFolderItemData(monitor, sec.Properties, ce);

                    if (item.ItemDependencies.Count > 0)
                    {
                        sec = proj.Sections.GetOrCreateSection("ProjectDependencies", SlnSectionType.PostProcess);
                        sec.Properties.ClearExcept(unknownProjects);
                        foreach (var dep in item.ItemDependencies)
                        {
                            sec.Properties.SetValue(dep.ItemId, dep.ItemId);
                        }
                    }
                    else
                    {
                        proj.Sections.RemoveSection("ProjectDependencies");
                    }
                }
                else if (ce is SolutionFolder)
                {
                    var proj = sln.Projects.GetOrCreateProject(ce.ItemId);
                    proj.TypeGuid = MSBuildProjectService.FolderTypeGuid;
                    proj.Name     = ce.Name;
                    proj.FilePath = ce.Name;

                    // Folder files
                    WriteFolderFiles(proj, (SolutionFolder)ce);

                    //Write custom properties
                    var sec = proj.Sections.GetOrCreateSection("MonoDevelopProperties", SlnSectionType.PreProcess);
                    sec.SkipIfEmpty = true;
                    folder.ParentSolution.WriteSolutionFolderItemData(monitor, sec.Properties, ce);
                }
                if (ce is SolutionFolder)
                {
                    WriteProjects(ce as SolutionFolder, sln, monitor, unknownProjects);
                }
            }
            monitor.EndTask();
        }
예제 #27
0
        /// <summary>
        /// Validates the schema.
        /// </summary>
        public static XmlSchema ValidateSchema(ProgressMonitor monitor, string xml, string fileName)
        {
            monitor.BeginTask(GettextCatalog.GetString("Validating schema..."), 1);
            bool      error  = false;
            XmlSchema schema = null;

            try {
                StringReader  stringReader = new StringReader(xml);
                XmlTextReader xmlReader    = new XmlTextReader(stringReader);
                xmlReader.XmlResolver = null;

                ValidationEventHandler callback = delegate(object source, ValidationEventArgs args) {
                    if (args.Severity == XmlSeverityType.Warning)
                    {
                        monitor.ReportWarning(args.Message);
                    }
                    else
                    {
                        monitor.ReportError(args.Message, args.Exception);
                        error = true;
                    }
                    AddTask(fileName, args.Message, args.Exception.LinePosition, args.Exception.LineNumber,
                            (args.Severity == XmlSeverityType.Warning)? TaskSeverity.Warning : TaskSeverity.Error);
                };
                schema = XmlSchema.Read(xmlReader, callback);
                XmlSchemaSet sset = new XmlSchemaSet();
                sset.Add(schema);
                sset.ValidationEventHandler += callback;
                sset.Compile();
            }
            catch (XmlSchemaException ex) {
                monitor.ReportError(ex.Message, ex);
                AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error);
                error = true;
            }
            catch (XmlException ex) {
                monitor.ReportError(ex.Message, ex);
                AddTask(fileName, ex.Message, ex.LinePosition, ex.LineNumber, TaskSeverity.Error);
                error = true;
            }

            if (error)
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Validation failed."));
                TaskService.ShowErrors();
            }
            else
            {
                monitor.Log.WriteLine(GettextCatalog.GetString("Schema is valid."));
            }

            monitor.EndTask();
            return(error? null: schema);
        }
        public void RunXslTransformCommand()
        {
            if (string.IsNullOrEmpty(stylesheetFileName))
            {
                stylesheetFileName = XmlEditorService.BrowseForStylesheetFile();

                if (string.IsNullOrEmpty(stylesheetFileName))
                {
                    return;
                }
            }

            using (ProgressMonitor monitor = XmlEditorService.GetMonitor()) {
                try {
                    string xsltContent;
                    try {
                        xsltContent = GetFileContent(stylesheetFileName);
                    } catch (System.IO.IOException) {
                        monitor.ReportError(
                            GettextCatalog.GetString("Error reading file '{0}'.", stylesheetFileName), null);
                        return;
                    }
                    System.Xml.Xsl.XslCompiledTransform xslt =
                        XmlEditorService.ValidateStylesheet(monitor, xsltContent, stylesheetFileName);
                    if (xslt == null)
                    {
                        return;
                    }

                    XmlDocument doc = XmlEditorService.ValidateXml(monitor, Editor.Text, FileName);
                    if (doc == null)
                    {
                        return;
                    }

                    string newFileName = XmlEditorService.GenerateFileName(FileName, "-transformed{0}.xml");

                    monitor.BeginTask(GettextCatalog.GetString("Executing transform..."), 1);
                    using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Editor)) {
                        xslt.Transform(doc, null, output);
                        IdeApp.Workbench.NewDocument(
                            newFileName, "application/xml", output.ToString());
                    }
                    monitor.ReportSuccess(GettextCatalog.GetString("Transform completed."));
                    monitor.EndTask();
                } catch (Exception ex) {
                    string msg = GettextCatalog.GetString("Could not run transform.");
                    monitor.ReportError(msg, ex);
                    monitor.EndTask();
                }
            }
        }
예제 #29
0
 public void OnReload()
 {
     using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
         m.BeginTask(null, CurrentNodes.Length);
         foreach (ITreeNavigator node in CurrentNodes)
         {
             Solution solution = (Solution)node.DataItem;
             solution.ParentWorkspace.ReloadItem(m, solution);
             m.Step(1);
         }
         m.EndTask();
     }
 }
예제 #30
0
 public void OnReload()
 {
     using (ProgressMonitor m = IdeApp.Workbench.ProgressMonitors.GetProjectLoadProgressMonitor(true)) {
         m.BeginTask(null, CurrentNodes.Length);
         foreach (ITreeNavigator nav in CurrentNodes)
         {
             Project p = (Project)nav.DataItem;
             p.ParentFolder.ReloadItem(m, p);
             m.Step(1);
         }
         m.EndTask();
     }
 }
예제 #31
0
        public PushResult execute(ProgressMonitor monitor)
        {
            monitor.BeginTask(PROGRESS_OPENING_CONNECTION, -1);
            connection = transport.openPush();
            try
            {
                monitor.EndTask();

                Dictionary<string, RemoteRefUpdate> preprocessed = prepareRemoteUpdates();
                if (transport.DryRun)
                    modifyUpdatesForDryRun();
                else if (preprocessed.Count != 0)
                    connection.Push(monitor, preprocessed);
            }
            finally
            {
                connection.Close();
            }
            if (!transport.DryRun)
                updateTrackingRefs();
            return prepareOperationResult();
        }
예제 #32
0
        ///	<summary>
        /// Perform push operation between local and remote repository - set remote
        /// refs appropriately, send needed objects and update local tracking refs.
        /// <para />
        /// When <seealso cref="Transport.DryRun"/> is true, result of this operation is
        /// just estimation of real operation result, no real action is performed.
        /// </summary>
        /// <param name="monitor">
        /// Progress monitor used for feedback about operation.
        /// </param>
        /// <returns> result of push operation with complete status description. </returns>
        /// <exception cref="NotSupportedException">
        /// When push operation is not supported by provided transport.
        /// </exception>
        /// <exception cref="TransportException">
        /// When some error occurred during operation, like I/O, protocol
        /// error, or local database consistency error.
        /// </exception>
        public PushResult execute(ProgressMonitor monitor)
        {
            if (monitor == null)
                throw new ArgumentNullException("monitor");

            monitor.BeginTask(PROGRESS_OPENING_CONNECTION, ProgressMonitor.UNKNOWN);
            _connection = _transport.openPush();

            try
            {
                monitor.EndTask();

                IDictionary<string, RemoteRefUpdate> preprocessed = PrepareRemoteUpdates();
                if (_transport.DryRun)
                {
                    ModifyUpdatesForDryRun();
                }
                else if (preprocessed.Count != 0)
                {
                    _connection.Push(monitor, preprocessed);
                }
            }
            finally
            {
                _connection.Close();
            }

            if (!_transport.DryRun)
            {
                UpdateTrackingRefs();
            }

            return PrepareOperationResult();
        }
예제 #33
0
        private void DownloadObject(ProgressMonitor pm, AnyObjectId id)
        {
            if (_local.HasObject(id)) return;

            while (true)
            {
                // Try a pack file we know about, but don't have yet. Odds are
                // that if it has this object, it has others related to it so
                // getting the pack is a good bet.
                //
                if (DownloadPackedObject(pm, id))
                    return;

                // Search for a loose object over all alternates, starting
                // from the one we last successfully located an object through.
                //
                string idStr = id.Name;
                string subdir = idStr.Slice(0, 2);
                string file = idStr.Substring(2);
                string looseName = subdir + "/" + file;

                for (int i = _lastRemoteIdx; i < _remotes.Count; i++)
                {
                    if (DownloadLooseObject(id, looseName, _remotes[i]))
                    {
                        _lastRemoteIdx = i;
                        return;
                    }
                }

                for (int i = 0; i < _lastRemoteIdx; i++)
                {
                    if (DownloadLooseObject(id, looseName, _remotes[i]))
                    {
                        _lastRemoteIdx = i;
                        return;
                    }
                }

                // Try to obtain more pack information and search those.
                //
                while (_noPacksYet.Count > 0)
                {
                    WalkRemoteObjectDatabase wrr = _noPacksYet.First.Value;
                    _noPacksYet.RemoveFirst();
                    ICollection<string> packNameList;
                    try
                    {
                        pm.BeginTask("Listing packs", ProgressMonitor.UNKNOWN);
                        packNameList = wrr.getPackNames();
                    }
                    catch (IOException e)
                    {
                        // Try another repository.
                        //
                        RecordError(id, e);
                        continue;
                    }
                    finally
                    {
                        pm.EndTask();
                    }

                    if (packNameList == null || packNameList.Count == 0)
                        continue;
                    foreach (string packName in packNameList)
                    {
                        bool contains = _packsConsidered.Contains(packName);
                        _packsConsidered.Add(packName);
                        if (!contains)
                        {
                            _unfetchedPacks.AddLast(new RemotePack(_lockMessage, _packLocks, _objCheck, _local, wrr, packName));
                        }
                    }
                    if (DownloadPackedObject(pm, id))
                        return;
                }

                // Try to expand the first alternate we haven't expanded yet.
                //
                ICollection<WalkRemoteObjectDatabase> al = ExpandOneAlternate(id, pm);
                if (al != null && al.Count > 0)
                {
                    foreach (WalkRemoteObjectDatabase alt in al)
                    {
                        _remotes.Add(alt);
                        _noPacksYet.AddLast(alt);
                        _noAlternatesYet.AddLast(alt);
                    }
                    continue;
                }

                // We could not obtain the object. There may be reasons why.
                //
                List<Exception> failures = _fetchErrors.get(id.Copy());

                var te = new TransportException("Cannot get " + id.Name + ".");

                if (failures != null && failures.Count > 0)
                {
                    te = failures.Count == 1 ?
                        new TransportException("Cannot get " + id.Name + ".", failures[0]) :
                        new TransportException("Cannot get " + id.Name + ".", new CompoundException(failures));
                }

                throw te;
            }
        }
예제 #34
0
            public void OpenIndex(ProgressMonitor pm)
            {
                if (Index != null) return;

                if (TmpIdx.IsFile())
                {
                    try
                    {
                        Index = PackIndex.Open(TmpIdx);
                        return;
                    }
                    catch (FileNotFoundException)
                    {
                        // Fall through and get the file.
                    }
                }

                using (Stream s = _connection.open("pack/" + _idxName))
                {
                    pm.BeginTask("Get " + _idxName.Slice(0, 12) + "..idx", !s.CanSeek ? ProgressMonitor.UNKNOWN : (int)(s.Length / 1024));

                    try
                    {
                        using (var fos = new FileStream(TmpIdx.FullName, System.IO.FileMode.CreateNew, FileAccess.Write))
                        {
                            var buf = new byte[2048];
                            int cnt;
                            while (!pm.IsCancelled && (cnt = s.Read(buf, 0, buf.Length)) > 0)
                            {
                                fos.Write(buf, 0, cnt);
                                pm.Update(cnt / 1024);
                            }
                        }
                    }
                    catch (IOException)
                    {
                        TmpIdx.DeleteFile();
                        throw;
                    }
                }

                pm.EndTask();

                if (pm.IsCancelled)
                {
                    TmpIdx.DeleteFile();
                    return;
                }

                try
                {
                    Index = PackIndex.Open(TmpIdx);
                }
                catch (IOException)
                {
                    TmpIdx.DeleteFile();
                    throw;
                }
            }
예제 #35
0
            public void OpenIndex(ProgressMonitor pm)
            {
                if (Index != null) return;

                try
                {
                    Index = PackIndex.Open(TmpIdx);
                    return;
                }
                catch (FileNotFoundException)
                {

                }

                Stream s = _connection.open("pack/" + _idxName);
                pm.BeginTask("Get " + _idxName.Slice(0, 12) + "..idx", s.Length < 0 ? -1 : (int)(s.Length / 1024));
                try
                {
                    var fos = new FileStream(TmpIdx.ToString(), System.IO.FileMode.Open, FileAccess.ReadWrite);
                    try
                    {
                        var buf = new byte[2048];
                        int cnt;
                        while (!pm.IsCancelled && (cnt = s.Read(buf, 0, buf.Length)) >= 0)
                        {
                            fos.Write(buf, 0, cnt);
                            pm.Update(cnt / 1024);
                        }
                    }
                    finally
                    {
                        fos.Close();
                    }
                }
                catch (IOException)
                {
                    TmpIdx.Delete();
                    throw;
                }
                finally
                {
                    s.Close();
                }
                pm.EndTask();

                if (pm.IsCancelled)
                {
                    TmpIdx.Delete();
                    return;
                }

                try
                {
                    Index = PackIndex.Open(TmpIdx);
                }
                catch (IOException)
                {
                    TmpIdx.Delete();
                    throw;
                }
            }
예제 #36
0
 private List<WalkRemoteObjectDatabase> ExpandOneAlternate(AnyObjectId id, ProgressMonitor pm)
 {
     while (_noAlternatesYet.Count > 0)
     {
         WalkRemoteObjectDatabase wrr = _noAlternatesYet.First.Value;
         _noAlternatesYet.RemoveFirst();
         try
         {
             pm.BeginTask("Listing alternates", ProgressMonitor.UNKNOWN);
             List<WalkRemoteObjectDatabase> altList = wrr.getAlternates();
             if (altList != null && altList.Count > 0)
                 return altList;
         }
         catch (IOException e)
         {
             RecordError(id, e);
         }
         finally
         {
             pm.EndTask();
         }
     }
     return null;
 }
예제 #37
0
        private void DownloadObject(ProgressMonitor pm, AnyObjectId id)
        {
            if (_local.HasObject(id)) return;

            while (true)
            {
                if (DownloadPackedObject(pm, id))
                    return;

                string idStr = id.Name;
                string subdir = idStr.Slice(0, 2);
                string file = idStr.Substring(2);
                string looseName = subdir + "/" + file;

                for (int i = _lastRemoteIdx; i < _remotes.Count; i++)
                {
                    if (DownloadLooseObject(id, looseName, _remotes[i]))
                    {
                        _lastRemoteIdx = i;
                        return;
                    }
                }

                for (int i = 0; i < _lastRemoteIdx; i++)
                {
                    if (DownloadLooseObject(id, looseName, _remotes[i]))
                    {
                        _lastRemoteIdx = i;
                        return;
                    }
                }

                while (_noPacksYet.Count > 0)
                {
                    WalkRemoteObjectDatabase wrr = _noPacksYet.First.Value;
                    _noPacksYet.RemoveFirst();
                    List<string> packNameList;
                    try
                    {
                        pm.BeginTask("Listing packs", ProgressMonitor.UNKNOWN);
                        packNameList = wrr.getPackNames();
                    }
                    catch (IOException e)
                    {
                        RecordError(id, e);
                        continue;
                    }
                    finally
                    {
                        pm.EndTask();
                    }

                    if (packNameList == null || packNameList.Count == 0)
                        continue;
                    foreach (string packName in packNameList)
                    {
                        if (!_packsConsidered.Contains(packName))
                        {
                            _packsConsidered.Add(packName);
                            _unfetchedPacks.AddLast(new RemotePack(_lockMessage, _packLocks, _objCheck, _local, wrr, packName));
                        }
                    }
                    if (DownloadPackedObject(pm, id))
                        return;
                }

                List<WalkRemoteObjectDatabase> al = ExpandOneAlternate(id, pm);
                if (al != null && al.Count > 0)
                {
                    foreach (WalkRemoteObjectDatabase alt in al)
                    {
                        _remotes.Add(alt);
                        _noPacksYet.AddLast(alt);
                        _noAlternatesYet.AddLast(alt);
                    }
                    continue;
                }

                List<Exception> failures = null;
                if (_fetchErrors.ContainsKey(id.Copy()))
                {
                    failures = _fetchErrors[id.Copy()];
                }

                TransportException te = null;
                if (failures != null && failures.Count > 0)
                {
                    te = failures.Count == 1 ?
                        new TransportException("Cannot get " + id.Name + ".", failures[0]) :
                        new TransportException("Cannot get " + id.Name + ".", new CompoundException(failures));
                }

                if (te == null)
                {
                    te = new TransportException("Cannot get " + id.Name + ".");
                }

                throw te;
            }
        }
		public ProgressStatusMonitor (ProgressMonitor monitor, int logLevel)
		{
			this.logLevel = logLevel;
			this.monitor = monitor;
			monitor.BeginTask ("", 100);
		}
예제 #39
0
 private void ResolveDeltas(ProgressMonitor progress)
 {
     progress.BeginTask(PROGRESS_RESOLVE_DELTA, _deltaCount);
     int last = _entryCount;
     for (int i = 0; i < last; i++)
     {
         int before = _entryCount;
         ResolveDeltas(_entries[i]);
         progress.Update(_entryCount - before);
         if (progress.IsCancelled)
         {
             throw new IOException("Download cancelled during indexing");
         }
     }
     progress.EndTask();
 }
예제 #40
0
        public void index(ProgressMonitor progress)
        {
            progress.Start(2 /* tasks */);
            try
            {
                try
                {
                    ReadPackHeader();

                    _entries = new PackedObjectInfo[(int)_objectCount];
                    _baseById = new ObjectIdSubclassMap<DeltaChain>();
                    _baseByPos = new LongMap<UnresolvedDelta>();

                    progress.BeginTask(PROGRESS_DOWNLOAD, (int)_objectCount);
                    for (int done = 0; done < _objectCount; done++)
                    {
                        IndexOneObject();
                        progress.Update(1);
                        if (progress.IsCancelled)
                        {
                            throw new IOException("Download cancelled");
                        }
                    }

                    ReadPackFooter();
                    EndInput();
                    progress.EndTask();

                    if (_deltaCount > 0)
                    {
                        if (_packOut == null)
                        {
                            throw new IOException("need packOut");
                        }

                        ResolveDeltas(progress);
                        if (_entryCount < _objectCount)
                        {
                            if (!_fixThin)
                            {
                                throw new IOException("pack has " + (_objectCount - _entryCount) + " unresolved deltas");
                            }

                            FixThinPack(progress);
                        }
                    }

                    if (_packOut != null && (_keepEmpty || _entryCount > 0))
                    {
                        _packOut.Flush();
                    }

                    _packDigest = null;
                    _baseById = null;
                    _baseByPos = null;

                    if (_dstIdx != null && (_keepEmpty || _entryCount > 0))
                    {
                        WriteIdx();
                    }
                }
                finally
                {
                    try
                    {
                        InflaterCache.Instance.release(_inflater);
                    }
                    finally
                    {
                        _inflater = null;
                    }
                    _windowCursor = WindowCursor.Release(_windowCursor);

                    progress.EndTask();
                    if (_packOut != null)
                    {
                        _packOut.Close();
                    }
                }

                if (_keepEmpty || _entryCount > 0)
                {
                    if (_dstPack != null)
                    {
                        _dstPack.IsReadOnly = true;
                    }
                    if (_dstIdx != null)
                    {
                        _dstIdx.IsReadOnly = true;
                    }
                }
            }
            catch (IOException)
            {
                if (_dstPack != null) _dstPack.Delete();
                if (_dstIdx != null) _dstIdx.Delete();
                throw;
            }
        }