コード例 #1
0
ファイル: GetHelpCommand.cs プロジェクト: nickchal/pash
 private void HelpSystem_OnProgress(object sender, HelpProgressInfo arg)
 {
     ProgressRecord progressRecord = new ProgressRecord(0, base.CommandInfo.Name, arg.Activity) {
         PercentComplete = arg.PercentComplete
     };
     base.WriteProgress(progressRecord);
 }
コード例 #2
0
        protected async Task RunTransferJob(FileTransferJob job, ProgressRecord record)
        {
            this.SetRequestOptionsInTransferJob(job);
            job.AccessCondition = this.AccessCondition;
            job.OverwritePromptCallback = this.ConfirmOverwrite;

            try
            {
                await this.transferJobRunner.RunTransferJob(job,
                        (percent, speed) =>
                        {
                            record.PercentComplete = (int)percent;
                            record.StatusDescription = string.Format(CultureInfo.CurrentCulture, Resources.FileTransmitStatus, (int)percent, Util.BytesToHumanReadableSize(speed));
                            this.OutputStream.WriteProgress(record);
                        },
                        this.CmdletCancellationToken);

                record.PercentComplete = 100;
                record.StatusDescription = Resources.TransmitSuccessfully;
                this.OutputStream.WriteProgress(record);
            }
            catch (OperationCanceledException)
            {
                record.StatusDescription = Resources.TransmitCancelled;
                this.OutputStream.WriteProgress(record);
            }
            catch (Exception e)
            {
                record.StatusDescription = string.Format(CultureInfo.CurrentCulture, Resources.TransmitFailed, e.Message);
                this.OutputStream.WriteProgress(record);
                throw;
            }
        }
コード例 #3
0
 internal void AddProgress(ProgressRecord item)
 {
     if (this.progress != null)
     {
         this.progress.InternalAdd(this.psInstanceId, item);
     }
 }
コード例 #4
0
ファイル: CmdletListener.cs プロジェクト: Wdovin/vc-community
        //private readonly MemoryStream _MemoryStream = new MemoryStream();

        public CmdletListener(DomainCommand command, ProgressRecord progress)
        {
            //_MemoryStream
            //base.Writer = new StreamWriter();
            _command = command;
            _progress = progress;
        }
コード例 #5
0
        private void GetByWebAppName()
        {
            const string progressDescriptionFormat = "Progress: {0}/{1} web apps processed.";
            var progressRecord = new ProgressRecord(1, string.Format("Get web apps with name '{0}'", Name), "Progress:");

            WriteProgress(progressRecord);

            var sites = this.ResourcesClient.FilterPSResources(new PSResourceManagerModels.BasePSResourceParameters()
            {
                ResourceType = "Microsoft.Web/Sites"
            }).Where(s => string.Equals(s.Name, Name, StringComparison.OrdinalIgnoreCase)).ToArray();

            var list = new List<Site>();
            for (var i = 0; i < sites.Length; i++)
            {
                var s = sites[i];
                var result = WebsitesClient.GetWebApp(s.ResourceGroupName, s.Name, null);
                if (result != null)
                {
                    list.Add(result);
                }

                progressRecord.StatusDescription = string.Format(progressDescriptionFormat, i + 1, sites.Length);
                progressRecord.PercentComplete = (100 * (i + 1)) / sites.Length;
                WriteProgress(progressRecord);
            }

            WriteObject(list);
        }
コード例 #6
0
ファイル: PowwaProgressRecord.cs プロジェクト: nickchal/pash
		public PowwaProgressRecord(ProgressRecord record)
		{
			if (record != null)
			{
				this.ActivityId = record.ActivityId;
				this.ParentActivityId = record.ParentActivityId;
				this.Activity = record.Activity;
				this.StatusDescription = record.StatusDescription;
				this.CurrentOperation = record.CurrentOperation;
				this.PercentComplete = record.PercentComplete;
				this.RecordType = record.RecordType;
				if (record.SecondsRemaining <= 0)
				{
					this.TimeRemaining = string.Empty;
					return;
				}
				else
				{
					object[] objArray = new object[1];
					objArray[0] = TimeSpan.FromSeconds((double)record.SecondsRemaining);
					this.TimeRemaining = string.Format(CultureInfo.CurrentCulture, "{0}", objArray);
					return;
				}
			}
			else
			{
				throw new ArgumentNullException("record");
			}
		}
コード例 #7
0
 private static ProgressRecord Validate(ProgressRecord progressRecord)
 {
     if (progressRecord == null)
     {
         throw new ArgumentNullException("progressRecord");
     }
     return progressRecord;
 }
コード例 #8
0
 static private void HandleTransferException(Exception e, ProgressRecord record, TaskOutputStream outputStream)
 {
     if (record != null)
     {
         record.StatusDescription = string.Format(CultureInfo.CurrentCulture, Resources.TransmitFailed, e.Message);
         outputStream.WriteProgress(record);
     }
 }
コード例 #9
0
 public void OnStartTest()
 {
     ProgressRecord pr = null;
     command.OnTaskStart(pr);
     pr = new ProgressRecord(0, "a", "b");
     pr.PercentComplete = 10;
     command.OnTaskStart(pr);
     Assert.AreEqual(0, pr.PercentComplete);
 }
コード例 #10
0
        private void LogProgressComplete(int activityId, string activity)
        {
            ProgressRecord progressRecord = new ProgressRecord(activityId,
                                                               activity,
                                                               Rsrc.PSSyncOutputEventsLogProgressCompleteCompleted);

            progressRecord.RecordType = ProgressRecordType.Completed;

            cmdlet.WriteProgress(progressRecord);
        }
コード例 #11
0
ファイル: HostUI.cs プロジェクト: beefarino/bips
        public override void WriteProgress(long sourceId, ProgressRecord record)
        {
            var ev = Progress;
            if (null == ev)
            {
                return;
            }

            ev(this, new ProgressRecordEventArgs(sourceId, record));
        }
コード例 #12
0
 public void SafeWriteProgress(ProgressRecord progress)
 {
     if (CommandRuntime != null)
     {
         WriteProgress(progress);
     }
     else
     {
         Trace.WriteLine(progress.StatusDescription);
     }
 }
コード例 #13
0
ファイル: ProgressNode.cs プロジェクト: nickchal/pash
		internal ProgressNode(long sourceId, ProgressRecord record) : base(record.ActivityId, record.Activity, record.StatusDescription)
		{
			this.Style = ProgressNode.RenderStyle.FullPlus;
			base.ParentActivityId = record.ParentActivityId;
			base.CurrentOperation = record.CurrentOperation;
			base.PercentComplete = Math.Min(record.PercentComplete, 100);
			base.SecondsRemaining = record.SecondsRemaining;
			base.RecordType = record.RecordType;
			this.Style = ProgressNode.RenderStyle.FullPlus;
			this.SourceId = sourceId;
		}
コード例 #14
0
ファイル: WriteProgressCommand.cs プロジェクト: nickchal/pash
 protected override void ProcessRecord()
 {
     ProgressRecord progressRecord = new ProgressRecord(this.Id, this.Activity, this.Status) {
         ParentActivityId = this.ParentId,
         PercentComplete = this.PercentComplete,
         SecondsRemaining = this.SecondsRemaining,
         CurrentOperation = this.CurrentOperation,
         RecordType = (this.Completed != 0) ? ProgressRecordType.Completed : ProgressRecordType.Processing
     };
     base.WriteProgress((long) this.SourceId, progressRecord);
 }
コード例 #15
0
        internal static ProgressDetails Create(ProgressRecord progressRecord)
        {
            //progressRecord.RecordType == ProgressRecordType.Completed;
            //progressRecord.Activity;
            //progressRecord.

            return new ProgressDetails
            {
                PercentComplete = progressRecord.PercentComplete
            };
        }
コード例 #16
0
ファイル: ProgressRecord.cs プロジェクト: 40a/PowerShell
 /// <summary>
 /// Cloning constructor (all fields are value types - can treat our implementation of cloning as "deep" copy) 
 /// </summary>
 /// <param name="other"></param>
 internal ProgressRecord(ProgressRecord other)
 {
     _activity = other._activity;
     _currentOperation = other._currentOperation;
     _id = other._id;
     _parentId = other._parentId;
     _percent = other._percent;
     _secondsRemaining = other._secondsRemaining;
     _status = other._status;
     _type = other._type;
 }
コード例 #17
0
 public void OnFinishTest()
 {
     ProgressRecord pr = null;
     ArgumentException e = new ArgumentException("test");
     command.OnTaskFinish(pr, null);
     pr = new ProgressRecord(0, "a", "b");
     command.OnTaskFinish(pr, null);
     Assert.AreEqual(100, pr.PercentComplete);
     Assert.AreEqual(String.Format(Resources.TransmitSuccessfully), pr.StatusDescription);
     command.OnTaskFinish(pr, e);
     Assert.AreEqual(100, pr.PercentComplete);
     Assert.AreEqual(String.Format(Resources.TransmitFailed, e.Message), pr.StatusDescription);
 }
コード例 #18
0
        private void LogProgress(int activityId, string activity, double precentComplete, TimeSpan remainingTime, double avgThroughputMbps)
        {
            var message = String.Format(Rsrc.PSSyncOutputEventsLogProgress,
                                        precentComplete,
                                        FormatDuration(remainingTime),
                                        avgThroughputMbps);
            ProgressRecord progressRecord = new ProgressRecord(activityId, activity, message);

            progressRecord.SecondsRemaining = (int)remainingTime.TotalSeconds;
            progressRecord.PercentComplete  = (int)precentComplete;

            cmdlet.WriteProgress(progressRecord);
        }
コード例 #19
0
ファイル: DatasetCmdlets.cs プロジェクト: hning86/azuremlps
        protected override void ProcessRecord()
        {
            ProgressRecord pr = new ProgressRecord(1, "Upload file", string.Format("Upload file \"{0}\" into Azure ML Studio", Path.GetFileName(UploadFileName)));
            pr.PercentComplete = 1;
            pr.CurrentOperation = "Uploading...";
            WriteProgress(pr);

            // step 1. upload file
            Task<string> uploadTask = Sdk.UploadResourceAsnyc(GetWorkspaceSetting(), FileFormat, UploadFileName);
            while (!uploadTask.IsCompleted)
            {
                if (pr.PercentComplete < 100)
                    pr.PercentComplete++;
                else
                    pr.PercentComplete = 1;
                Thread.Sleep(500);
                WriteProgress(pr);
            }

            // step 2. generate schema
            pr.PercentComplete = 2;
            pr.StatusDescription = "Generating schema for dataset \"" + DatasetName + "\"";
            pr.CurrentOperation = "Generating schema...";
            WriteProgress(pr);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            dynamic parsed = jss.Deserialize<object>(uploadTask.Result);
            string dtId = parsed["DataTypeId"];
            string uploadId = parsed["Id"];
            string dataSourceId = Sdk.StartDatasetSchemaGen(GetWorkspaceSetting(), dtId, uploadId, DatasetName, Description, UploadFileName);

            // step 3. get status for schema generation
            string schemaJobStatus = "NotStarted";
            while (true)
            {
                if (pr.PercentComplete < 100)
                    pr.PercentComplete++;
                else
                    pr.PercentComplete = 1;
                pr.CurrentOperation = "Schema generation status: " + schemaJobStatus;
                WriteProgress(pr);

                schemaJobStatus = Sdk.GetDatasetSchemaGenStatus(GetWorkspaceSetting(), dataSourceId);
                if (schemaJobStatus == "NotSupported" || schemaJobStatus == "Complete" || schemaJobStatus == "Failed")
                    break;
            }
            pr.PercentComplete = 100;
            WriteProgress(pr);

            WriteObject("Dataset upload status: " + schemaJobStatus);
        }
コード例 #20
0
ファイル: ProgressRecord.cs プロジェクト: nickchal/pash
 internal ProgressRecord(ProgressRecord other)
 {
     this.parentId = -1;
     this.percent = -1;
     this.secondsRemaining = -1;
     this.activity = other.activity;
     this.currentOperation = other.currentOperation;
     this.id = other.id;
     this.parentId = other.parentId;
     this.percent = other.percent;
     this.secondsRemaining = other.secondsRemaining;
     this.status = other.status;
     this.type = other.type;
 }
コード例 #21
0
        protected override void BeginProcessing()
        {
            ProgressRecord pr = new ProgressRecord(1, "Create Custom Module", string.Format("Upload custom module ZIP file \"{0}\" into Azure ML Studio", CustomModuleZipFileName));
            pr.PercentComplete = 1;
            pr.CurrentOperation = "Uploading custom module ZIP file...";
            WriteProgress(pr);
            string uploadedResourceMetadata = Sdk.UploadResource(GetWorkspaceSetting(), "Zip");
            JavaScriptSerializer jss = new JavaScriptSerializer();
            dynamic m = jss.Deserialize<object>(uploadedResourceMetadata);
            string uploadId = m["Id"];
            Task<string> task = Sdk.UploadResourceInChunksAsnyc(GetWorkspaceSetting(), 1, 0, uploadId, CustomModuleZipFileName, "Zip");
            while (!task.IsCompleted)
            {
                if (pr.PercentComplete < 100)
                    pr.PercentComplete++;
                else
                    pr.PercentComplete = 1;
                Thread.Sleep(500);
                WriteProgress(pr);
            }
            string uploadMetadata = task.Result;
            string activityId = Sdk.BeginParseCustomModuleJob(GetWorkspaceSetting(), uploadMetadata);

            pr.CurrentOperation = "Creating custom module...";
            WriteProgress(pr);
            dynamic statusObj = jss.Deserialize<object>(Sdk.GetCustomModuleBuildJobStatus(GetWorkspaceSetting(), activityId));
            string jobStatus = statusObj[0];
            while (jobStatus == "Pending")
            {
                if (pr.PercentComplete < 100)
                    pr.PercentComplete++;
                else
                    pr.PercentComplete = 1;
                statusObj = jss.Deserialize<object>(Sdk.GetCustomModuleBuildJobStatus(GetWorkspaceSetting(), activityId));
                jobStatus = statusObj[0].ToString();
                Thread.Sleep(500);
                WriteProgress(pr);
            }

            pr.PercentComplete = 100;
            WriteProgress(pr);

            if (jobStatus == "Finished")
            {
                string moduleId = statusObj[1];
                WriteObject(moduleId);
            }
            else
                throw new System.Exception("Custom module upload failed: " + statusObj[1]);
        }
コード例 #22
0
ファイル: ProgressNode.cs プロジェクト: 40a/PowerShell
        ProgressNode(Int64 sourceId, ProgressRecord record)
            :
            base(record.ActivityId, record.Activity, record.StatusDescription)
        {
            Dbg.Assert(record.RecordType == ProgressRecordType.Processing, "should only create node for Processing records");

            this.ParentActivityId = record.ParentActivityId;
            this.CurrentOperation = record.CurrentOperation;
            this.PercentComplete = Math.Min(record.PercentComplete, 100);
            this.SecondsRemaining = record.SecondsRemaining;
            this.RecordType = record.RecordType;
            this.Style = RenderStyle.FullPlus;
            this.SourceId = sourceId;
        }
コード例 #23
0
 public RemotingProgressRecord(ProgressRecord progressRecord, System.Management.Automation.Remoting.OriginInfo originInfo) : base(Validate(progressRecord).ActivityId, Validate(progressRecord).Activity, Validate(progressRecord).StatusDescription)
 {
     this._originInfo = originInfo;
     if (progressRecord != null)
     {
         base.PercentComplete = progressRecord.PercentComplete;
         base.ParentActivityId = progressRecord.ParentActivityId;
         base.RecordType = progressRecord.RecordType;
         base.SecondsRemaining = progressRecord.SecondsRemaining;
         if (!string.IsNullOrEmpty(progressRecord.CurrentOperation))
         {
             base.CurrentOperation = progressRecord.CurrentOperation;
         }
     }
 }
コード例 #24
0
ファイル: CimWriteProgress.cs プロジェクト: nickchal/pash
		public override void Execute(CmdletOperationBase cmdlet)
		{
			object[] objArray = new object[4];
			objArray[0] = this.activity;
			objArray[1] = this.activityID;
			objArray[2] = this.secondsRemaining;
			objArray[3] = this.percentageCompleted;
			DebugHelper.WriteLog("...Activity {0}: id={1}, remain seconds ={2}, percentage completed = {3}", 4, objArray);
			ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
			ProgressRecord progressRecord = new ProgressRecord(this.activityID, this.activity, this.statusDescription);
			progressRecord.Activity = this.activity;
			progressRecord.ParentActivityId = 0;
			progressRecord.SecondsRemaining = this.secondsRemaining;
			progressRecord.PercentComplete = this.percentageCompleted;
			cmdlet.WriteProgress(progressRecord);
		}
コード例 #25
0
 public void OnProgressTest()
 {
     ProgressRecord pr = null;
     command.OnTaskProgress(pr, 0.0, 0.0);
     pr = new ProgressRecord(0, "a", "b");
     pr.PercentComplete = 10;
     command.OnTaskProgress(pr, 5.6, 12.3);
     Assert.AreEqual(12, pr.PercentComplete);
     command.OnTaskProgress(pr, 5.6, 12.8);
     Assert.AreEqual(12, pr.PercentComplete);
     command.OnTaskProgress(pr, 5.6, 11);
     Assert.AreEqual(11, pr.PercentComplete);
     command.OnTaskProgress(pr, 5.6, 12.8);
     Assert.AreEqual(12, pr.PercentComplete);
     command.OnTaskProgress(pr, 5.6, 5);
     Assert.AreEqual(5, pr.PercentComplete);
 }
コード例 #26
0
        public void ProgressHyperV(ushort percentComplete, string message)
        {
            var            status         = String.Format("{0}% Complete", percentComplete);
            ProgressRecord progressRecord = new ProgressRecord(0, message, status);

            if (percentComplete >= 100)
            {
                progressRecord.RecordType        = ProgressRecordType.Completed;
                progressRecord.StatusDescription = "100% Complete";
            }
            else
            {
                progressRecord.PercentComplete = percentComplete;
            }

            cmdlet.WriteProgress(progressRecord);
        }
コード例 #27
0
        public void ProgressEmptyBlockDetection(int processedRangeCount, int totalRangeCount)
        {
            ProgressRecord progressRecord = new ProgressRecord(2,
                                                               Rsrc.PSSyncOutputEventsProgressEmptyBlockDetection,
                                                               Rsrc.PSSyncOutputEventsEmptyBlockDetectionDetecting);

            if (processedRangeCount >= totalRangeCount)
            {
                progressRecord.RecordType        = ProgressRecordType.Completed;
                progressRecord.StatusDescription = Rsrc.PSSyncOutputEventsEmptyBlockDetectionCompleted;
            }
            else
            {
                progressRecord.PercentComplete = (int)((double)processedRangeCount / totalRangeCount * 100);
            }

            cmdlet.WriteProgress(progressRecord);
        }
コード例 #28
0
        protected TransferContext GetTransferContext(ProgressRecord record, long totalTransferLength)
        {
            TransferContext transferContext = new TransferContext();
            transferContext.ClientRequestId = CmdletOperationContext.ClientRequestId;
            transferContext.OverwriteCallback = ConfirmOverwrite;

            transferContext.ProgressHandler = new TransferProgressHandler((transferProgress) =>
            {
                if (record != null)
                {
                    record.PercentComplete = (int)(transferProgress.BytesTransferred * 100 / totalTransferLength);
                    record.StatusDescription = string.Format(CultureInfo.CurrentCulture, Resources.FileTransmitStatus, record.PercentComplete);
                    this.OutputStream.WriteProgress(record);
                }
            });

            return transferContext;
        }
コード例 #29
0
        static public async Task DoTransfer(Func<Task> doTransfer, ProgressRecord record, TaskOutputStream outputStream)
        {
            try
            {
                await doTransfer();

                if (record != null)
                {
                    record.PercentComplete = 100;
                    record.StatusDescription = Resources.TransmitSuccessfully;
                    outputStream.WriteProgress(record);
                }
            }
            catch (OperationCanceledException)
            {
                if (record != null)
                {
                    record.StatusDescription = Resources.TransmitCancelled;
                    outputStream.WriteProgress(record);
                }
            }
            catch (TransferException e)
            {
                // DMLib wrappers StorageException in its InnerException but didn't expose any detailed error messages, 
                // here throw its inner exception out to show more readable error messages.
                StorageException se = e.InnerException as StorageException;

                if (null != se)
                {
                    HandleTransferException(se, record, outputStream);
                    throw se;
                }
                else
                {
                    HandleTransferException(e, record, outputStream);
                    throw;
                }
            }
            catch (Exception e)
            {
                HandleTransferException(e, record, outputStream);
                throw;
            }
        }
コード例 #30
0
        public void ProgressCopy(double percentageDone)
        {
            var            status         = String.Format("{0}% Complete", (int)percentageDone);
            ProgressRecord progressRecord = new ProgressRecord(0,
                                                               "Making a copy of the VHD file before resizing",
                                                               status);

            if (percentageDone >= 100.0)
            {
                progressRecord.RecordType        = ProgressRecordType.Completed;
                progressRecord.StatusDescription = "100% Complete";
            }
            else
            {
                progressRecord.PercentComplete = (int)percentageDone;
            }

            cmdlet.WriteProgress(progressRecord);
        }
コード例 #31
0
        protected override void PromptForDataCollectionProfileIfNotExists()
        {
            // Initialize it from the environment variable or profile file.
            InitializeDataCollectionProfile();

            if (!_dataCollectionProfile.EnableAzureDataCollection.HasValue && CheckIfInteractive())
            {
                WriteWarning(Resources.DataCollectionPrompt);

                const double timeToWaitInSeconds = 60;
                var status = string.Format(Resources.DataCollectionConfirmTime, timeToWaitInSeconds);
                ProgressRecord record = new ProgressRecord(0, Resources.DataCollectionActivity, status);

                var startTime = DateTime.Now;
                var endTime = DateTime.Now;
                double elapsedSeconds = 0;

                while (!this.Host.UI.RawUI.KeyAvailable && elapsedSeconds < timeToWaitInSeconds)
                {
                    TestMockSupport.Delay(10 * 1000);
                    endTime = DateTime.Now;

                    elapsedSeconds = (endTime - startTime).TotalSeconds;
                    record.PercentComplete = ((int)elapsedSeconds * 100 / (int)timeToWaitInSeconds);
                    WriteProgress(record);
                }

                bool enabled = false;
                if (this.Host.UI.RawUI.KeyAvailable)
                {
                    KeyInfo keyInfo =
                        this.Host.UI.RawUI.ReadKey(ReadKeyOptions.NoEcho | ReadKeyOptions.AllowCtrlC |
                                                   ReadKeyOptions.IncludeKeyDown);
                    enabled = (keyInfo.Character == 'Y' || keyInfo.Character == 'y');
                }

                _dataCollectionProfile.EnableAzureDataCollection = enabled;

                WriteWarning(enabled ? Resources.DataCollectionConfirmYes : Resources.DataCollectionConfirmNo);

                SaveDataCollectionProfile();
            }
        }
コード例 #32
0
ファイル: DllMain.cs プロジェクト: jairoe05/ipm
        protected override void ProcessRecord()
        {
            var myprogress = new ProgressRecord(1, "Creating: " + this.path + ".iso", "Progress:");
            var isothread = new Thread(() => Start(this.path, this.outpath));
            isothread.Start();

            Console.WriteLine("Reading Target directory...");

            while (isothread.IsAlive)
            {
                myprogress.PercentComplete = GetProgress();
                Thread.Sleep(200);
                if (myprogress.PercentComplete != 0)
                {
                    WriteProgress(myprogress);
                }
            }

            WriteObject("Done...");
            Console.Beep();
        }
コード例 #33
0
ファイル: CimWriteProgress.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// <para>
        /// Write progress record to powershell
        /// </para>
        /// </summary>
        /// <param name="cmdlet"></param>
        public override void Execute(CmdletOperationBase cmdlet)
        {
            DebugHelper.WriteLog(
                "...Activity {0}: id={1}, remain seconds ={2}, percentage completed = {3}",
                4,
                this.activity,
                this.activityID,
                this.secondsRemaining,
                this.percentageCompleted);

            ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet");
            ProgressRecord record = new ProgressRecord(
                this.activityID,
                this.activity,
                this.statusDescription);
            record.Activity = this.activity;
            record.ParentActivityId = 0;
            record.SecondsRemaining = (int)this.secondsRemaining;
            record.PercentComplete = (int)this.percentageCompleted;
            cmdlet.WriteProgress(record);
        }
コード例 #34
0
        protected override void ProcessRecord()
        {
            if (JobConfigString == null || JobConfigString == string.Empty)
                JobConfigString = File.ReadAllText(JobConfigFile);
            ProgressRecord pr = new ProgressRecord(1, "Batch Execution Service", "Run Azure ML BES Job");

            // Submit the job
            pr.CurrentOperation = "Submitting the job...";
            pr.PercentComplete = 1;
            WriteProgress(pr);
            string jobId = Sdk.SubmitBESJob(SubmitJobRequestUrl, ApiKey, JobConfigString);
            pr.CurrentOperation = "Starting the job...";
            pr.PercentComplete = 2;
            WriteProgress(pr);
            pr.StatusDescription += ": " + jobId;
            Sdk.StartBESJob(SubmitJobRequestUrl, ApiKey, jobId);

            // Query job status
            pr.CurrentOperation = "Getting job status...";
            pr.PercentComplete = 3;
            WriteProgress(pr);

            string jobStatus = "Job Status: NotStarted";
            string outputMsg = string.Empty;
            while (true)
            {
                jobStatus = Sdk.GetBESJobStatus(SubmitJobRequestUrl, ApiKey, jobId, out outputMsg);
                pr.CurrentOperation = "Job Status: " + jobStatus;
                WriteProgress(pr);

                if (pr.PercentComplete < 100)
                    pr.PercentComplete++;
                else
                    pr.PercentComplete = 1;
                if (jobStatus == "Failed" || jobStatus == "Canceled" || jobStatus == "Finished")
                    break;
            }            
            WriteObject(outputMsg);
        }
コード例 #35
0
        HandleIncomingProgressRecord(Int64 sourceId, ProgressRecord record)
        {
            Dbg.Assert(record != null, "record should not be null");

            if (_pendingProgress == null)
            {
                Dbg.Assert(_progPane == null, "If there is no data struct, there shouldn't be a pane, either.");

                _pendingProgress = new PendingProgress();
            }

            _pendingProgress.Update(sourceId, record);

            if (_progPane == null)
            {
                // This is the first time we've received a progress record.  Create a pane to show it, and 
                // then show it.

                _progPane = new ProgressPane(this);
            }
            _progPane.Show(_pendingProgress);
        }
コード例 #36
0
 public override void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
 {
     ProgressStream.Add(record);
 }
コード例 #37
0
 public override void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
 {
     // throw new NotImplementedException();
 }
コード例 #38
0
 internal void SendProgressRecordToClient(ProgressRecord record)
 {
     using (ServerPowerShellDataStructureHandler.tracer.TraceMethod())
         this.SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(record, this.clientRunspacePoolId, this.clientPowerShellId));
 }
コード例 #39
0
        internal static ScriptAnalysis Analyze(string path, ExecutionContext context)
        {
            ModuleIntrinsics.Tracer.WriteLine("Analyzing path: {0}", path);

            try
            {
                if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null))
                {
                    ProgressRecord analysisProgress = new ProgressRecord(0,
                        Modules.ScriptAnalysisPreparing,
                        String.Format(CultureInfo.InvariantCulture, Modules.ScriptAnalysisModule, path));
                    analysisProgress.RecordType = ProgressRecordType.Processing;

                    // Write the progress using a static source ID so that all
                    // analysis messages get single-threaded in the progress pane (rather than nesting).
                    context.CurrentCommandProcessor.CommandRuntime.WriteProgress(typeof(ScriptAnalysis).FullName.GetHashCode(), analysisProgress);
                }
            }
            catch (InvalidOperationException)
            {
                // This may be called when we are not allowed to write progress,
                // So eat the invalid operation
            }

            string scriptContent = ReadScript(path);

            ParseError[] errors;
            var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis);

            // Don't bother analyzing if there are syntax errors (we don't do semantic analysis which would
            // detect other errors that we also might choose to ignore, but it's slower.)
            if (errors.Length > 0)
                return null;

            ExportVisitor exportVisitor = new ExportVisitor(forCompletion: false);
            moduleAst.Visit(exportVisitor);

            var result = new ScriptAnalysis
            {
                DiscoveredClasses = exportVisitor.DiscoveredClasses,
                DiscoveredExports = exportVisitor.DiscoveredExports,
                DiscoveredAliases = new Dictionary<string, string>(),
                DiscoveredModules = exportVisitor.DiscoveredModules,
                DiscoveredCommandFilters = exportVisitor.DiscoveredCommandFilters,
                AddsSelfToPath = exportVisitor.AddsSelfToPath
            };

            if (result.DiscoveredCommandFilters.Count == 0)
            {
                result.DiscoveredCommandFilters.Add("*");
            }
            else
            {
                // Post-process aliases, as they are not exported by default
                List<WildcardPattern> patterns = new List<WildcardPattern>();
                foreach (string discoveredCommandFilter in result.DiscoveredCommandFilters)
                {
                    patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase));
                }

                foreach (var pair in exportVisitor.DiscoveredAliases)
                {
                    string discoveredAlias = pair.Key;
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(discoveredAlias, patterns, defaultValue: false))
                    {
                        result.DiscoveredAliases[discoveredAlias] = pair.Value;
                    }
                }
            }

            return result;
        }
コード例 #40
0
 /// <summary>
 /// Default implementation - just discards it's arguments.
 /// </summary>
 /// <param name="progressRecord">Progress record to write.</param>
 public void WriteProgress(ProgressRecord progressRecord)
 {
     ;
 }
コード例 #41
0
 private void ProcessOutputHelper()
 {
     for (object obj2 = this.outputReader.Read(); obj2 != AutomationNull.Value; obj2 = this.outputReader.Read())
     {
         ProcessOutputObject obj3 = obj2 as ProcessOutputObject;
         if (obj3.Stream == MinishellStream.Error)
         {
             ErrorRecord data = obj3.Data as ErrorRecord;
             data.SetInvocationInfo(base.Command.MyInvocation);
             ActionPreference?actionPreference = null;
             base.commandRuntime._WriteErrorSkipAllowCheck(data, actionPreference);
         }
         else if (obj3.Stream == MinishellStream.Output)
         {
             base.commandRuntime._WriteObjectSkipAllowCheck(obj3.Data);
         }
         else if (obj3.Stream == MinishellStream.Debug)
         {
             string message = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteDebugLine(message);
         }
         else if (obj3.Stream == MinishellStream.Verbose)
         {
             string str2 = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteVerboseLine(str2);
         }
         else if (obj3.Stream == MinishellStream.Warning)
         {
             string str3 = obj3.Data as string;
             base.Command.PSHostInternal.UI.WriteWarningLine(str3);
         }
         else if (obj3.Stream == MinishellStream.Progress)
         {
             PSObject obj4 = obj3.Data as PSObject;
             if (obj4 != null)
             {
                 long         sourceId = 0L;
                 PSMemberInfo info     = obj4.Properties["SourceId"];
                 if (info != null)
                 {
                     sourceId = (long)info.Value;
                 }
                 info = obj4.Properties["Record"];
                 ProgressRecord record = null;
                 if (info != null)
                 {
                     record = info.Value as ProgressRecord;
                 }
                 if (record != null)
                 {
                     base.Command.PSHostInternal.UI.WriteProgress(sourceId, record);
                 }
             }
         }
         if (base.Command.Context.CurrentPipelineStopping)
         {
             this.StopProcessing();
             return;
         }
     }
 }
コード例 #42
0
 /// <summary>
 /// Default implementation - just discards it's arguments.
 /// </summary>
 /// <param name="sourceId">Source ID to write for.</param>
 /// <param name="progressRecord">Record to write.</param>
 public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord)
 {
     ;
 }
コード例 #43
0
 public void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
 {
 }
コード例 #44
0
 public void WriteProgress(long sourceId, ProgressRecord progressRecord)
 {
 }
コード例 #45
0
        private void ReportProgress(bool minimizeFrequentUpdates)
        {
            lock (_progressLock)
            {
                DateTime now = DateTime.UtcNow;

                if (minimizeFrequentUpdates)
                {
                    if ((now - _progressStartTime) < TimeSpan.FromSeconds(1))
                    {
                        return;
                    }

                    if ((!_progressReportLastTime.Equals(DateTime.MinValue)) &&
                        (now - _progressReportLastTime < TimeSpan.FromMilliseconds(200)))
                    {
                        return;
                    }
                }

                _progressReportLastTime = now;

                double workCompleted;
                double totalWork;
                int    percentComplete;
                lock (_lockObject)
                {
                    totalWork     = _countOfAllChildJobs;
                    workCompleted = this.CountOfFinishedChildJobs;
                }

                if (totalWork >= 1.0)
                {
                    percentComplete = (int)(100.0 * workCompleted / totalWork);
                }
                else
                {
                    percentComplete = -1;
                }

                percentComplete = Math.Max(-1, Math.Min(100, percentComplete));

                var progressRecord = new ProgressRecord(
                    activityId: _progressActivityId,
                    activity: this.Command,
                    statusDescription: this.StatusMessage);

                if (this.IsThrottlingJobCompleted)
                {
                    if (_progressReportLastTime.Equals(DateTime.MinValue))
                    {
                        return;
                    }

                    progressRecord.RecordType       = ProgressRecordType.Completed;
                    progressRecord.PercentComplete  = 100;
                    progressRecord.SecondsRemaining = 0;
                }
                else
                {
                    progressRecord.RecordType      = ProgressRecordType.Processing;
                    progressRecord.PercentComplete = percentComplete;
                    int?secondsRemaining = null;
                    if (percentComplete >= 0)
                    {
                        secondsRemaining = ProgressRecord.GetSecondsRemaining(_progressStartTime, (double)percentComplete / 100.0);
                    }

                    if (secondsRemaining.HasValue)
                    {
                        progressRecord.SecondsRemaining = secondsRemaining.Value;
                    }
                }

                this.WriteProgress(progressRecord);
            }
        }
コード例 #46
0
 /// <summary>
 /// Send the specified progress record to client
 /// </summary>
 /// <param name="record">progress record</param>
 internal void SendProgressRecordToClient(ProgressRecord record)
 {
     SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
                       record, _clientRunspacePoolId, _clientPowerShellId));
 }