public void WriteProgress(ProgressRecord progressRecord) { throw new NotImplementedException(); }
protected override void ProcessRecord() { try { if (string.IsNullOrWhiteSpace(ConnectionString)) { throw new ArgumentException(nameof(ConnectionString)); } if (ClustersIds?.Length != AppsIds.Length) { throw new ArgumentException(nameof(ClustersIds)); } if (Versions?.Length != AppsIds.Length) { throw new ArgumentException(nameof(Versions)); } if (BinariesPath?.Length != AppsIds.Length) { throw new ArgumentException(nameof(BinariesPath)); } if (AppsIds?.Length == 0) { throw new ArgumentException(nameof(AppsIds)); } int activityId = 0; var progressRecord = new ProgressRecord(activityId++, "Connect to blob storage", "Connecting to blob storage"); WriteProgress(progressRecord); var deploymentRepository = BlobStorageDeploymentRepository.Create(ConnectionString); progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); if (BinariesPath != null) { var tasks = new List <Task>(); for (int i = 0; i < AppsIds.Length; ++i) { string appId = AppsIds[i]; string version = Versions[i]; string binariesPath = BinariesPath[i]; var newAppIdentity = new AppIdentity(appId, version); if (BinariesPath != null) { tasks.Add(deploymentRepository.UploadApplicationBinaries(newAppIdentity, binariesPath, BinariesConflictResolutionMode)); } } progressRecord = new ProgressRecord(activityId++, "UploadApplicationBinaries", "Uploading binaries to blob storage"); WriteProgress(progressRecord); Task.WhenAll(tasks).Wait(); progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); } if (Deploy) { progressRecord = new ProgressRecord(activityId++, "FetchDeploymentConfig", "Fetching DeploymentConfig.json from blob storage"); WriteProgress(progressRecord); var deploymentConfig = deploymentRepository.FetchDeploymentConfig().Result; progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); for (int i = 0; i < AppsIds.Length; ++i) { string appId = AppsIds[i]; string version = Versions[i]; string clusterId = ClustersIds[i]; if (RemoveOldVersions && deploymentConfig.HasApplication(appId)) { deploymentConfig = deploymentConfig.RemoveApplication(appId, clusterId); } var newAppIdentity = new AppIdentity(appId, version); if (!deploymentConfig.HasApplication(newAppIdentity, clusterId)) { var appDeploymentConfig = deploymentConfig.HasApplication(newAppIdentity)? deploymentConfig.GetApplicationConfig(newAppIdentity) : new AppDeploymentConfig(newAppIdentity); appDeploymentConfig = appDeploymentConfig.AddClusterId(clusterId); if (Properties?.Length > i) { var appProperties = JsonConvert.DeserializeObject <Dictionary <string, string> >(Properties[i]); foreach (var kvp in appProperties) { appDeploymentConfig = appDeploymentConfig.AddProperty(kvp.Key, kvp.Value); } } deploymentConfig = deploymentConfig.SetApplicationConfig(appDeploymentConfig); } } progressRecord = new ProgressRecord(activityId++, "PublishDeploymentConfig", "Publishing DeploymentConfig.json to blob storage"); WriteProgress(progressRecord); deploymentRepository.PublishDeploymentConfig(deploymentConfig).Wait(); progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); WriteObject(deploymentConfig); } if (WaitForDeploymentsToComplete) { var waitForDeploymentsProgressRecord = new ProgressRecord(activityId++, "WaitForDeploymentsToComplete", "Waiting for all deployments to complete"); WriteProgress(waitForDeploymentsProgressRecord); List <AppInfo> pendingApps = new List <AppInfo>(); for (int i = 0; i < AppsIds.Length; ++i) { AppInfo app = new AppInfo { Id = AppsIds[i], Version = Versions[i], ClusterId = ClustersIds[i] }; pendingApps.Add(app); } while (pendingApps.Any()) { var appDeployments = new List <AppDeploymentStatus>(); var fetchTasks = new List <Task <ClusterDeploymentStatus> >(); progressRecord = new ProgressRecord(activityId++, "FetchClusterDeploymentStatus", "Fetching deployments status"); WriteProgress(progressRecord); foreach (string clusterId in ClustersIds) { fetchTasks.Add( deploymentRepository.FetchClusterDeploymentStatus(clusterId, ttlSeconds: 60)); } progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); ClusterDeploymentStatus[] result = Task.WhenAll(fetchTasks).Result; foreach (var clusterDeploymentStatus in result) { appDeployments.AddRange(clusterDeploymentStatus.ListAll()); } foreach (var appDeploymentStatus in appDeployments) { AppInfo app = pendingApps.FirstOrDefault( appInfo => appInfo.ClusterId == appDeploymentStatus.ClusterId && appInfo.Id == appDeploymentStatus.Id && appInfo.Version == appDeploymentStatus.Version); if (app != null) { pendingApps.Remove(app); float quotient = (float)(AppsIds.Length - pendingApps.Count) / AppsIds.Length; waitForDeploymentsProgressRecord.PercentComplete = (int)(100 * quotient); WriteProgress(waitForDeploymentsProgressRecord); } } Task.Delay(TimeSpan.FromSeconds(1)).Wait(); } waitForDeploymentsProgressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(waitForDeploymentsProgressRecord); } } catch (ArgumentException argException) { ThrowTerminatingError(new ErrorRecord(argException, "0", ErrorCategory.InvalidArgument, null)); } catch (Exception e) { ThrowTerminatingError(new ErrorRecord(e, "0", ErrorCategory.OperationStopped, null)); } }
internal ProgressKey(long sourceId, ProgressRecord record) { SourceId = sourceId; ActivityId = record.ActivityId; ParentActivityId = record.ParentActivityId; }
public override void WriteProgress(long sourceId, ProgressRecord record) { this.Write(record.PercentComplete.ToString()); }
public new void WriteProgress([NotNull] ProgressRecord progressRecord) { AsyncCmdletSynchronizationContext.PostItem(new MarshalItemAction <ProgressRecord>(base.WriteProgress, progressRecord)); }
/// <summary> /// Handle the object obtained from an ObjectStream's reader /// based on its type. /// </summary> /// <param name="cmdlet">Cmdlet to use for outputting the object.</param> /// <param name="instanceId"></param> /// <param name="overrideInquire">Suppresses prompt on messages with Inquire preference. /// Needed for Receive-Job</param> internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInquire = false) { switch (ObjectType) { case PSStreamObjectType.Output: { if (instanceId != Guid.Empty) { PSObject o = Value as PSObject; if (o != null) { AddSourceJobNoteProperty(o, instanceId); } } cmdlet.WriteObject(Value); } break; case PSStreamObjectType.Error: { ErrorRecord errorRecord = (ErrorRecord)this.Value; RemotingErrorRecord remoteErrorRecord = errorRecord as RemotingErrorRecord; if (remoteErrorRecord == null) { // if we get a base ErrorRecord object, check if the computerName is // populated in the RecommendedAction field if (errorRecord.ErrorDetails != null && !string.IsNullOrEmpty(errorRecord.ErrorDetails.RecommendedAction)) { string computerName; Guid jobInstanceId; GetIdentifierInfo(errorRecord.ErrorDetails.RecommendedAction, out jobInstanceId, out computerName); errorRecord = new RemotingErrorRecord(errorRecord, new OriginInfo(computerName, Guid.Empty, jobInstanceId)); } } else { errorRecord = remoteErrorRecord; } errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteError(errorRecord, overrideInquire); } } break; case PSStreamObjectType.Warning: { string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); } } break; case PSStreamObjectType.Verbose: { string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); } } break; case PSStreamObjectType.Progress: { ProgressRecord progressRecord = (ProgressRecord)Value; RemotingProgressRecord remotingProgressRecord = progressRecord as RemotingProgressRecord; if (remotingProgressRecord == null) { Guid jobInstanceId; string computerName; GetIdentifierInfo(progressRecord.CurrentOperation, out jobInstanceId, out computerName); OriginInfo info = new OriginInfo(computerName, Guid.Empty, jobInstanceId); progressRecord = new RemotingProgressRecord(progressRecord, info); } else { progressRecord = remotingProgressRecord; } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteProgress(progressRecord, overrideInquire); } } break; case PSStreamObjectType.Debug: { string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); } } break; case PSStreamObjectType.Information: { InformationRecord informationRecord = (InformationRecord)this.Value; RemotingInformationRecord remoteInformationRecord = informationRecord as RemotingInformationRecord; if (remoteInformationRecord == null) { // if we get a base InformationRecord object, check if the computerName is // populated in the Source field if (!string.IsNullOrEmpty(informationRecord.Source)) { string computerName; Guid jobInstanceId; GetIdentifierInfo(informationRecord.Source, out jobInstanceId, out computerName); informationRecord = new RemotingInformationRecord(informationRecord, new OriginInfo(computerName, Guid.Empty, jobInstanceId)); } } else { informationRecord = remoteInformationRecord; } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; if (mshCommandRuntime != null) { mshCommandRuntime.WriteInformation(informationRecord, overrideInquire); } } break; case PSStreamObjectType.WarningRecord: case PSStreamObjectType.MethodExecutor: case PSStreamObjectType.BlockingError: case PSStreamObjectType.ShouldMethod: { WriteStreamObject(cmdlet, overrideInquire); } break; } }
protected override void ExecuteCmdlet() { DefaultRetrievalExpressions = new Expression <Func <User, object> >[] { u => u.Id, u => u.Title, u => u.LoginName, u => u.Email, u => u.IsShareByEmailGuestUser, u => u.IsSiteAdmin, u => u.UserId, u => u.IsHiddenInUI, u => u.PrincipalType, u => u.Alerts.Include( a => a.Title, a => a.Status), u => u.Groups.Include( g => g.Id, g => g.Title, g => g.LoginName) }; if (Identity == null) { SelectedWeb.Context.Load(SelectedWeb.SiteUsers, u => u.Include(RetrievalExpressions)); List <DetailedUser> users = new List <DetailedUser>(); if (WithRightsAssigned || WithRightsAssignedDetailed ) { // Get all the role assignments and role definition bindings to be able to see which users have been given rights directly on the site level SelectedWeb.Context.Load(SelectedWeb.RoleAssignments, ac => ac.Include(a => a.RoleDefinitionBindings, a => a.Member)); var usersWithDirectPermissions = SelectedWeb.SiteUsers.Where(u => SelectedWeb.RoleAssignments.Any(ra => ra.Member.LoginName == u.LoginName)); // Get all the users contained in SharePoint Groups SelectedWeb.Context.Load(SelectedWeb.SiteGroups, sg => sg.Include(u => u.Users.Include(RetrievalExpressions), u => u.LoginName)); SelectedWeb.Context.ExecuteQueryRetry(); // Get all SharePoint groups that have been assigned access var usersWithGroupPermissions = new List <User>(); foreach (var group in SelectedWeb.SiteGroups.Where(g => SelectedWeb.RoleAssignments.Any(ra => ra.Member.LoginName == g.LoginName))) { usersWithGroupPermissions.AddRange(group.Users); } // Merge the users with rights directly on the site level and those assigned rights through SharePoint Groups var allUsersWithPermissions = new List <User>(usersWithDirectPermissions.Count() + usersWithGroupPermissions.Count()); allUsersWithPermissions.AddRange(usersWithDirectPermissions); allUsersWithPermissions.AddRange(usersWithGroupPermissions); // Add the found users and add them to the custom object if (WithRightsAssignedDetailed) { SelectedWeb.Context.Load(SelectedWeb, s => s.ServerRelativeUrl); SelectedWeb.Context.ExecuteQueryRetry(); WriteWarning("Using the -WithRightsAssignedDetailed parameter will cause the script to take longer than normal because of the all enumerations that take place"); users.AddRange(GetPermissions(SelectedWeb.RoleAssignments, SelectedWeb.ServerRelativeUrl)); foreach (var user in allUsersWithPermissions) { users.Add(new DetailedUser() { Groups = user.Groups, User = user, Url = SelectedWeb.ServerRelativeUrl }); } } else { // Filter out the users that have been given rights at both places so they will only be returned once WriteObject(allUsersWithPermissions.GroupBy(u => u.Id).Select(u => u.First()), true); } } else { SelectedWeb.Context.ExecuteQueryRetry(); WriteObject(SelectedWeb.SiteUsers, true); } if (WithRightsAssignedDetailed) { SelectedWeb.Context.Load(SelectedWeb.Lists, l => l.Include(li => li.ItemCount, li => li.IsSystemList, li => li.IsCatalog, li => li.RootFolder.ServerRelativeUrl, li => li.RoleAssignments, li => li.Title, li => li.HasUniqueRoleAssignments)); SelectedWeb.Context.ExecuteQueryRetry(); var progress = new ProgressRecord(0, $"Getting lists for {SelectedWeb.ServerRelativeUrl}", "Enumerating through lists"); var progressCounter = 0; foreach (var list in SelectedWeb.Lists) { WriteProgress(progress, $"Getting list {list.RootFolder.ServerRelativeUrl}", progressCounter++, SelectedWeb.Lists.Count); // ignoring the system lists if (list.IsSystemList || list.IsCatalog) { continue; } // if a list or a library has unique permissions then proceed if (list.HasUniqueRoleAssignments) { WriteVerbose(string.Format("List found with HasUniqueRoleAssignments {0}", list.RootFolder.ServerRelativeUrl)); string url = list.RootFolder.ServerRelativeUrl; SelectedWeb.Context.Load(list.RoleAssignments, r => r.Include( ra => ra.RoleDefinitionBindings, ra => ra.Member.LoginName, ra => ra.Member.Title, ra => ra.Member.PrincipalType)); SelectedWeb.Context.ExecuteQueryRetry(); users.AddRange(GetPermissions(list.RoleAssignments, url)); // if the list with unique permissions also has items, check every item which is uniquely permissioned if (list.ItemCount > 0) { WriteVerbose(string.Format("Enumerating through all listitems of {0}", list.RootFolder.ServerRelativeUrl)); CamlQuery query = CamlQuery.CreateAllItemsQuery(); var queryElement = XElement.Parse(query.ViewXml); var rowLimit = queryElement.Descendants("RowLimit").FirstOrDefault(); if (rowLimit != null) { rowLimit.RemoveAll(); } else { rowLimit = new XElement("RowLimit"); queryElement.Add(rowLimit); } rowLimit.SetAttributeValue("Paged", "TRUE"); rowLimit.SetValue(1000); query.ViewXml = queryElement.ToString(); List <ListItemCollection> items = new List <ListItemCollection>(); do { var listItems = list.GetItems(query); SelectedWeb.Context.Load(listItems); SelectedWeb.Context.ExecuteQueryRetry(); query.ListItemCollectionPosition = listItems.ListItemCollectionPosition; items.Add(listItems); } while (query.ListItemCollectionPosition != null); // Progress bar for item enumerations var itemProgress = new ProgressRecord(0, $"Getting items for {list.RootFolder.ServerRelativeUrl}", "Enumerating through items"); var itemProgressCounter = 0; foreach (var item in items) { WriteProgress(itemProgress, $"Retrieving items", itemProgressCounter++, items.Count); WriteVerbose(string.Format("Enumerating though listitemcollections")); foreach (var listItem in item) { WriteVerbose(string.Format("Enumerating though listitems")); listItem.EnsureProperty(i => i.HasUniqueRoleAssignments); if (listItem.HasUniqueRoleAssignments) { string listItemUrl = listItem["FileRef"].ToString(); WriteVerbose(string.Format("List item {0} HasUniqueRoleAssignments", listItemUrl)); SelectedWeb.Context.Load(listItem.RoleAssignments, r => r.Include( ra => ra.RoleDefinitionBindings, ra => ra.Member.LoginName, ra => ra.Member.Title, ra => ra.Member.PrincipalType)); SelectedWeb.Context.ExecuteQueryRetry(); users.AddRange(GetPermissions(listItem.RoleAssignments, listItemUrl)); } } } itemProgress.RecordType = ProgressRecordType.Completed; WriteProgress(itemProgress); } } progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } // Fetch all the unique users from everything that has been collected var uniqueUsers = (from u in users select u.User.LoginName).Distinct(); // Looping through each user, getting all the details like specific permissions and groups an user belongs to foreach (var uniqueUser in uniqueUsers) { // Getting all the assigned permissions per user var userPermissions = (from u in users where u.User.LoginName == uniqueUser && u.Permissions != null select u).ToList(); // Making the permissions readable by getting the name of the permission and the URL of the artifact Dictionary <string, string> Permissions = new Dictionary <string, string>(); foreach (var userPermission in userPermissions) { StringBuilder stringBuilder = new StringBuilder(); foreach (var permissionMask in userPermission.Permissions) { stringBuilder.Append(permissionMask); } Permissions.Add(userPermission.Url, stringBuilder.ToString()); } // Getting all the groups where the user is added to var groupsMemberships = (from u in users where u.User.LoginName == uniqueUser && u.Groups != null select u.Groups).ToList(); // Getting the titles of the all the groups List <string> Groups = new List <string>(); foreach (var groupMembership in groupsMemberships) { foreach (var group in groupMembership) { Groups.Add(group.Title); } } // Getting the User object of the user so we can get to the title, loginname, etc var userInformation = (from u in users where u.User.LoginName == uniqueUser select u.User).FirstOrDefault(); WriteObject(new { userInformation.Title, userInformation.LoginName, userInformation.Email, Groups, Permissions }, true); } } } else { User user = null; if (Identity.Id > 0) { user = SelectedWeb.GetUserById(Identity.Id); } else if (Identity.User != null && Identity.User.Id > 0) { user = SelectedWeb.GetUserById(Identity.User.Id); } else if (!string.IsNullOrWhiteSpace(Identity.Login)) { user = SelectedWeb.SiteUsers.GetByLoginName(Identity.Login); } if (user != null) { SelectedWeb.Context.Load(user, RetrievalExpressions); SelectedWeb.Context.ExecuteQueryRetry(); } WriteObject(user); } }
protected virtual void ProcessArchive(FileInfo fileInfo) { var entries = new List <ArchiveEntry>(); var archive = ArchiveFactory.Open(fileInfo); // don't need password to dump header/entries /*using (var extractor = new SevenZipExtractor(archive.FullName)) * { */ int total = archive.Entries.Count(); ProgressRecord progress = null; foreach (IArchiveEntry info in archive.Entries) { if (ShowProgress) { progress = new ProgressRecord(1, "Scanning...", fileInfo.FullName) { CurrentOperation = info.FilePath, PercentComplete = (int)Math.Floor(((float)info.Index / total) * 100), RecordType = ProgressRecordType.Processing }; WriteProgress(progress); } if (this.IncludeDirectories || !info.IsDirectory) { entries.Add(new ArchiveEntry(info, fileInfo.FullName, ToArchiveFormat(archive.Type))); } } if (ShowProgress && progress != null) { progress.PercentComplete = 100; progress.RecordType = ProgressRecordType.Completed; WriteProgress(progress); } //} WriteObject(entries, enumerateCollection: false); // true? which is better for piping to expand-archive? //ArchiveFormat format = this.Format; //if ((format != ArchiveFormat.Unknown) || // SevenZipBase.TryGetFormat(this, archive, ref format)) //{ // using (var reader = new PscxSevenZipReader(this, archive, format)) // { // reader.ShowScanProgress = ShowProgress; // foreach (ArchiveEntry entry in reader) // { // // only dump out the zero-length folder entries // // if instructed to. // if (this.IncludeDirectories || !entry.IsFolder) // { // WriteObject(entry); // } // } // } //} //else //{ // // todo: localize // // unknown file extension / format and no -Format override specified // ErrorHandler.HandleError(true, // new ErrorRecord(new PSArgumentException("Unknown file extension or invalid archive. You may override the format used with the -Format parameter."), // "UnknownArchiveFormat", ErrorCategory.ReadError, archive)); //} }
public new void WriteProgress(ProgressRecord progressRecord) { _messages.Add(() => base.WriteProgress(progressRecord)); }
internal static IEnumerable<string> GetDefaultAvailableModuleFiles(bool force, bool isForAutoDiscovery, ExecutionContext context) { HashSet<string> uniqueModuleFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string directory in ModuleIntrinsics.GetModulePath(isForAutoDiscovery, context)) { var needWriteProgressCompleted = false; ProgressRecord analysisProgress = null; // Write a progress message for UNC paths, so that users know what is happening try { if ((context.CurrentCommandProcessor != null) && Utils.PathIsUnc(directory)) { analysisProgress = new ProgressRecord(0, Modules.DeterminingAvailableModules, String.Format(CultureInfo.InvariantCulture, Modules.SearchingUncShare, directory)) { RecordType = ProgressRecordType.Processing }; context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress); needWriteProgressCompleted = true; } } catch (InvalidOperationException) { // This may be called when we are not allowed to write progress, // So eat the invalid operation } try { foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(directory)) { if (uniqueModuleFiles.Add(moduleFile)) { yield return moduleFile; } } } finally { if (needWriteProgressCompleted) { analysisProgress.RecordType = ProgressRecordType.Completed; context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress); } } } }
WriteProgress(Int64 sourceId, ProgressRecord record) { if (record == null) { throw PSTraceSource.NewArgumentNullException("record"); } // Write to Information Buffers if (null != _informationalBuffers) { _informationalBuffers.AddProgress(record); } if (_externalUI == null) { return; } _externalUI.WriteProgress(sourceId, record); }
} // WriteVerbose /// <Content contentref="System.Management.Automation.Cmdlet.WriteProgress" /> public void WriteProgress(ProgressRecord progressRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( Context != null, "The context should always be set"); if (progressRecord == null) { throw PSTraceSource.NewArgumentNullException("progressRecord"); } Context.WriteProgress(progressRecord); } } // WriteProgress
private static ProgressRecord Validate(ProgressRecord progressRecord) { if (progressRecord == null) throw new ArgumentNullException("progressRecord"); return progressRecord; }
/// <summary> /// Constructor /// </summary> /// <param name="progressRecord">the progress record that is wrapped</param> /// <param name="originInfo">origin information</param> public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originInfo) : base(Validate(progressRecord).ActivityId, Validate(progressRecord).Activity, Validate(progressRecord).StatusDescription) { _originInfo = originInfo; if (progressRecord != null) { this.PercentComplete = progressRecord.PercentComplete; this.ParentActivityId = progressRecord.ParentActivityId; this.RecordType = progressRecord.RecordType; this.SecondsRemaining = progressRecord.SecondsRemaining; if (!string.IsNullOrEmpty(progressRecord.CurrentOperation)) { this.CurrentOperation = progressRecord.CurrentOperation; } } }
protected void WriteProgress(ProgressRecord progressRecord) { Queue.Add(progressRecord); }
private void SyncProgressReady(ScriptRunner sender, ProgressRecord data) { OnProgressReady(this, data); }
public override void ExecuteCmdlet() { CloudFile fileToBeDownloaded; string[] path = NamingUtil.ValidatePath(this.Path, true); switch (this.ParameterSetName) { case LocalConstants.FileParameterSetName: fileToBeDownloaded = this.File; break; case LocalConstants.ShareNameParameterSetName: var share = this.BuildFileShareObjectFromName(this.ShareName); fileToBeDownloaded = share.GetRootDirectoryReference().GetFileReferenceByPath(path); break; case LocalConstants.ShareParameterSetName: fileToBeDownloaded = this.Share.GetRootDirectoryReference().GetFileReferenceByPath(path); break; case LocalConstants.DirectoryParameterSetName: fileToBeDownloaded = this.Directory.GetFileReferenceByPath(path); break; default: throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName)); } string resolvedDestination = this.GetUnresolvedProviderPathFromPSPath( string.IsNullOrWhiteSpace(this.Destination) ? "." : this.Destination); FileMode mode = this.Force ? FileMode.Create : FileMode.CreateNew; string targetFile; if (LocalDirectory.Exists(resolvedDestination)) { // If the destination pointed to an existing directory, we // would download the file into the folder with the same name // on cloud. targetFile = LocalPath.Combine(resolvedDestination, fileToBeDownloaded.GetBaseName()); } else { // Otherwise we treat the destination as a file no matter if // there's one existing or not. The overwrite behavior is configured // by FileMode. targetFile = resolvedDestination; } this.RunTask(async taskId => { var downloadJob = new TransferJob( new TransferLocation(fileToBeDownloaded), new TransferLocation(targetFile), TransferMethod.SyncCopy); var progressRecord = new ProgressRecord( this.OutputStream.GetProgressId(taskId), string.Format(CultureInfo.CurrentCulture, Resources.ReceiveAzureFileActivity, fileToBeDownloaded.GetFullPath(), targetFile), Resources.PrepareDownloadingFile); await this.RunTransferJob(downloadJob, progressRecord); if (this.PassThru) { this.OutputStream.WriteObject(taskId, fileToBeDownloaded); } }); }
private void OnProgressUpdate(ProgressRecord p) => this.ProgressUpdate?.Invoke(this, new PSProgressEventArgs(p.PercentComplete, p.Activity ?? string.Empty));
/// <summary> /// Write progress. /// </summary> public override void WriteProgress(long sourceId, ProgressRecord record) { _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteProgress, new object[] { sourceId, record }); }
public void WriteProgress(ProgressRecord progressRecord) { _provider.WriteProgress(progressRecord); }
public override void WriteProgress(long sourceId, ProgressRecord record) { this.OnWrite?.Invoke(record.ToString()); }
/// <summary> /// Decode object. /// </summary> internal static object DecodeObject(object obj, Type type) { if (obj == null) { return(null); } Dbg.Assert(type != null, "Expected type != null"); if (type == typeof(PSObject)) { return(DecodePSObject(obj)); } else if (type == typeof(ProgressRecord)) { return(ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj))); } else if (IsKnownType(type)) { return(obj); } else if (obj is SecureString) { return(obj); } else if (obj is PSCredential) { return(obj); } else if (obj is PSObject && type == typeof(PSCredential)) { // BUGBUG: The following piece of code is a workaround // because custom serialization is busted. If rehydration // works correctly then PSCredential should be available PSObject objAsPSObject = (PSObject)obj; PSCredential cred = null; try { cred = new PSCredential((string)objAsPSObject.Properties["UserName"].Value, (SecureString)objAsPSObject.Properties["Password"].Value); } catch (GetValueException) { cred = null; } return(cred); } else if (obj is int && type.IsEnum) { return(Enum.ToObject(type, (int)obj)); } else if (obj is string && type == typeof(CultureInfo)) { return(new CultureInfo((string)obj)); } else if (obj is PSObject && type == typeof(Exception)) { return(DecodeException((PSObject)obj)); } else if (obj is PSObject && type == typeof(object[])) { return(DecodeObjectArray((PSObject)obj)); } else if (obj is PSObject && type.IsArray) { return(DecodeArray((PSObject)obj, type)); } else if (obj is PSObject && IsCollection(type)) { return(DecodeCollection((PSObject)obj, type)); } else if (obj is PSObject && IsDictionary(type)) { return(DecodeDictionary((PSObject)obj, type)); } else if (obj is PSObject && IsEncodingAllowedForClassOrStruct(type)) { return(DecodeClassOrStruct((PSObject)obj, type)); } else if (obj is PSObject && IsGenericIEnumerableOfInt(type)) { // we cannot create an instance of interface type like IEnumerable // Since a Collection implements IEnumerable, falling back to use // that. return(DecodeCollection((PSObject)obj, typeof(Collection <int>))); } else if (obj is PSObject && type == typeof(RemoteHostCall)) { return(RemoteHostCall.Decode((PSObject)obj)); } else if (obj is PSObject && type == typeof(RemoteHostResponse)) { return(RemoteHostResponse.Decode((PSObject)obj)); } else { throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type); } }
protected override async Task ProcessRecordAsync() { var directory = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path ?? ""); // Ensure the path is a directory. if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException(directory); } WriteVerbose(string.Format("Archiving the contents of {0}", directory)); using (var reader = Archiver.CreateTarStream(new List <string> { directory }, CmdletCancellationToken)) { var parameters = new ImageBuildParameters { NoCache = SkipCache, ForceRemove = ForceRemoveIntermediateContainers, Remove = !PreserveIntermediateContainers, }; if (this.Isolation != IsolationType.Default) { parameters.Isolation = this.Isolation.ToString(); } string repoTag = null; if (!string.IsNullOrEmpty(Repository)) { repoTag = Repository; if (!string.IsNullOrEmpty(Tag)) { repoTag += ":"; repoTag += Tag; } parameters.Tags = new List <string> { repoTag }; } else if (!string.IsNullOrEmpty(Tag)) { throw new Exception("You must specify a repository name in order to specify a tag."); } string imageId = null; bool failed = false; var progress = new Progress <ProgressReader.Status>(); var progressRecord = new ProgressRecord(0, "Dockerfile context", "Uploading"); progress.ProgressChanged += (o, status) => { if (status.Complete) { progressRecord.CurrentOperation = null; progressRecord.StatusDescription = "Processing"; } else { progressRecord.StatusDescription = string.Format("Uploaded {0} bytes", status.TotalBytesRead); } WriteProgress(progressRecord); }; var progressReader = new ProgressReader(reader, progress, 512 * 1024); var buildTask = DkrClient.Miscellaneous.BuildImageFromDockerfileAsync(progressReader, parameters, CmdletCancellationToken); var messageWriter = new JsonMessageWriter(this); using (var buildStream = await buildTask) { // Complete the upload progress bar. progressRecord.RecordType = ProgressRecordType.Completed; WriteProgress(progressRecord); // ReadLineAsync is not cancellable without closing the whole stream, so register a callback to do just that. using (CmdletCancellationToken.Register(() => buildStream.Dispose())) using (var buildReader = new StreamReader(buildStream, new UTF8Encoding(false))) { string line; while ((line = await buildReader.ReadLineAsync()) != null) { var message = JsonConvert.DeserializeObject <JsonMessage>(line); if (message.Stream != null && message.Stream.StartsWith(SuccessfullyBuilt)) { // This is probably the image ID. imageId = message.Stream.Substring(SuccessfullyBuilt.Length).Trim(); } if (message.Error != null) { failed = true; } messageWriter.WriteJsonMessage(message); } } } messageWriter.ClearProgress(); if (imageId != null) { WriteObject(await ContainerOperations.GetImageById(imageId, DkrClient)); } else if (!failed) { throw new Exception("Could not find image, but no error was returned"); } } }
public override void WriteProgress(long sourceId, ProgressRecord record) { TryOutputProgress(record.Activity + " - " + record.StatusDescription, record.PercentComplete); }
protected new void WriteProgress(ProgressRecord progressRecord) { FlushDebugMessages(); base.WriteProgress(progressRecord); }
/// <summary> /// Sets up the PowerShell shell stream event handlers. /// </summary> /// <param name="shell">The PowerShell shell.</param> private static void SetupStreamEventHandlers(PowerShell shell) { Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); try { shell.Streams.ClearStreams(); shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender; ErrorRecord record = errorStream[e.Index]; if (record == null) { return; } StringBuilder builder = new StringBuilder(); builder.AppendLine(record.ToString()); if (record.InvocationInfo != null) { builder.AppendLine(); builder.AppendLine(record.InvocationInfo.PositionMessage); } Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString()); }; shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender; WarningRecord record = warningStream[e.Index]; if (record != null) { Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString()); } }; shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender; DebugRecord record = debugStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString()); } }; shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender; VerboseRecord record = versboseStream[e.Index]; if (record != null) { Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString()); } }; shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender; ProgressRecord record = progressStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString()); } }; } finally { Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); } }
/// <summary> /// WriteProgress /// </summary> /// <param name="sourceId"></param> /// <param name="record"></param> public override void WriteProgress(long sourceId, ProgressRecord record) { }
public override void WriteProgress(long sourceId, ProgressRecord record) => this._serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteProgress, new object[2] { (object)sourceId, (object)record });
/// <summary> /// Invoked by <see cref="Cmdlet.WriteProgress(ProgressRecord)" /> to display a progress record. /// </summary> /// <param name="sourceId"> /// Unique identifier of the source of the record. An int64 is used because typically, /// the 'this' pointer of the command from whence the record is originating is used, and /// that may be from a remote Runspace on a 64-bit machine. /// </param> /// <param name="record"> /// The record being reported to the host. /// </param> protected virtual void WriteProgressImpl(long sourceId, ProgressRecord record) { }
public override void ExecuteCmdlet() { CloudFile fileToBeDownloaded; string[] path = NamingUtil.ValidatePath(this.Path, true); switch (this.ParameterSetName) { case LocalConstants.FileParameterSetName: fileToBeDownloaded = this.File; break; case LocalConstants.ShareNameParameterSetName: var share = this.BuildFileShareObjectFromName(this.ShareName); fileToBeDownloaded = share.GetRootDirectoryReference().GetFileReferenceByPath(path); break; case LocalConstants.ShareParameterSetName: fileToBeDownloaded = this.Share.GetRootDirectoryReference().GetFileReferenceByPath(path); break; case LocalConstants.DirectoryParameterSetName: fileToBeDownloaded = this.Directory.GetFileReferenceByPath(path); break; default: throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName)); } string resolvedDestination = this.GetUnresolvedProviderPathFromPSPath( string.IsNullOrWhiteSpace(this.Destination) ? "." : this.Destination); FileMode mode = this.Force ? FileMode.Create : FileMode.CreateNew; string targetFile; if (LocalDirectory.Exists(resolvedDestination)) { // If the destination pointed to an existing directory, we // would download the file into the folder with the same name // on cloud. targetFile = LocalPath.Combine(resolvedDestination, fileToBeDownloaded.GetBaseName()); } else { // Otherwise we treat the destination as a file no matter if // there's one existing or not. The overwrite behavior is configured // by FileMode. targetFile = resolvedDestination; } if (ShouldProcess(targetFile, "Download")) { this.RunTask(async taskId => { await fileToBeDownloaded.FetchAttributesAsync(null, this.RequestOptions, OperationContext, CmdletCancellationToken).ConfigureAwait(false); var progressRecord = new ProgressRecord( this.OutputStream.GetProgressId(taskId), string.Format(CultureInfo.CurrentCulture, Resources.ReceiveAzureFileActivity, fileToBeDownloaded.GetFullPath(), targetFile), Resources.PrepareDownloadingFile); await DataMovementTransferHelper.DoTransfer(() => { return(this.TransferManager.DownloadAsync( fileToBeDownloaded, targetFile, new DownloadOptions { DisableContentMD5Validation = !this.CheckMd5 }, this.GetTransferContext(progressRecord, fileToBeDownloaded.Properties.Length), CmdletCancellationToken)); }, progressRecord, this.OutputStream).ConfigureAwait(false); if (this.PassThru) { this.OutputStream.WriteObject(taskId, fileToBeDownloaded); } }); } }
public virtual void NewPaaSDeploymentProcess() { bool removePackage = false; AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Production); AssertNoPersistenVmRoleExistsInDeployment(DeploymentSlotType.Staging); var storageName = CurrentSubscription.CurrentStorageAccountName; Uri packageUrl; if (this.Package.StartsWith(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || this.Package.StartsWith(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { packageUrl = new Uri(this.Package); } else { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.UploadingPackage); WriteProgress(progress); removePackage = true; packageUrl = this.RetryCall(s => AzureBlob.UploadPackageToBlob( this.StorageClient, storageName, this.Package, null)); } ExtensionConfiguration extConfig = null; if (ExtensionConfiguration != null) { string errorConfigInput = null; if (!ExtensionManager.Validate(ExtensionConfiguration, out errorConfigInput)) { throw new Exception(string.Format(Resources.ServiceExtensionCannotApplyExtensionsInSameType, errorConfigInput)); } foreach (ExtensionConfigurationInput context in ExtensionConfiguration) { if (context != null && context.X509Certificate != null) { ExecuteClientActionNewSM( null, string.Format(Resources.ServiceExtensionUploadingCertificate, CommandRuntime, context.X509Certificate.Thumbprint), () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, CertUtilsNewSM.Create(context.X509Certificate))); } } var slotType = (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true); DeploymentGetResponse d = null; InvokeInOperationContext(() => { try { d = this.ComputeClient.Deployments.GetBySlot(this.ServiceName, slotType); } catch (CloudException ex) { if (ex.Response.StatusCode != HttpStatusCode.NotFound && IsVerbose() == false) { this.WriteExceptionDetails(ex); } } }); ExtensionManager extensionMgr = new ExtensionManager(this, ServiceName); extConfig = extensionMgr.Set(d, ExtensionConfiguration, this.Slot); } var deploymentInput = new DeploymentCreateParameters { PackageUri = packageUrl, Configuration = GeneralUtilities.GetConfiguration(this.Configuration), ExtensionConfiguration = extConfig, Label = this.Label, Name = this.Name, StartDeployment = !this.DoNotStart.IsPresent, TreatWarningsAsError = this.TreatWarningsAsError.IsPresent, }; InvokeInOperationContext(() => { try { var progress = new ProgressRecord(0, Resources.WaitForUploadingPackage, Resources.CreatingNewDeployment); WriteProgress(progress); ExecuteClientActionNewSM( deploymentInput, CommandRuntime.ToString(), () => this.ComputeClient.Deployments.Create( this.ServiceName, (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), this.Slot, true), deploymentInput)); if (removePackage == true) { this.RetryCall(s => AzureBlob.DeletePackageFromBlob( this.StorageClient, storageName, packageUrl)); } } catch (CloudException ex) { this.WriteExceptionDetails(ex); } }); }
protected T StartRequestAndWait <T>(Func <Task <AzureOperationResponse <T> > > requestAction, Func <string> getResourceCurrentStatus) where T : class { var progress = new ProgressRecord(0, string.Format("Request for {0} in progress", typeof(T).Name), "Starting..."); WriteProgress(progress); AzureOperationResponse <T> beginRequestResponse = null; AzureOperationResponse <T> result = null; string armCorrelationId = string.Empty; var tokenSource = new CancellationTokenSource(); try { var requestTask = Task.Factory.StartNew(() => { try { beginRequestResponse = requestAction().GetAwaiter().GetResult(); result = this.SFRPClient.GetPutOrPatchOperationResultAsync(beginRequestResponse, null, default(CancellationToken)).GetAwaiter().GetResult(); } finally { tokenSource.Cancel(); } }); bool correlationPrinted = false; while (!tokenSource.IsCancellationRequested) { tokenSource.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(WriteVerboseIntervalInSec)); if (!RunningTest) { if (!correlationPrinted && beginRequestResponse != null) { WriteVerboseWithTimestamp(string.Format( "Beging request ARM correlationId: '{0}' response: '{1}'", beginRequestResponse.RequestId, beginRequestResponse.Response.StatusCode)); correlationPrinted = true; } string progressMessage = getResourceCurrentStatus(); WriteVerboseWithTimestamp(progressMessage); progress.StatusDescription = progressMessage; WriteProgress(progress); } } if (requestTask.IsFaulted) { string errorMessage = "Begin request operation failed"; if (beginRequestResponse != null) { errorMessage = string.Format( "Operation Failed. Begin request with ARM correlationId: '{0}' response: '{1}'", beginRequestResponse.RequestId, beginRequestResponse.Response.StatusCode); } WriteErrorWithTimestamp(errorMessage); throw requestTask.Exception; } } catch (Exception e) { PrintSdkExceptionDetail(e); throw; } return(result?.Body); }
protected override void ProcessRecord() { foreach (var computer in _computername) { ConnectionInfo connectInfo; if (_keyfile.Equals("")) { WriteVerbose("Using SSH Username and Password authentication for connection."); var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName); connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer, _port, _credential, _proxyserver, _proxytype, _proxyport, _proxycredential, kIconnectInfo); // Event Handler for interactive Authentication kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e) { foreach (var prompt in e.Prompts) { if (prompt.Request.Contains("Password")) { prompt.Response = _credential.GetNetworkCredential().Password; } } }; } else { WriteVerbose("Using SSH Key authentication for connection."); connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer, _port, _keyfile, _credential, _proxyserver, _proxytype, _proxyport, _proxycredential); } //Ceate instance of SSH Client with connection info var client = new ScpClient(connectInfo); // Handle host key var computer1 = computer; client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) { var sb = new StringBuilder(); foreach (var b in e.FingerPrint) { sb.AppendFormat("{0:x}:", b); } var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1); if (_sshHostKeys.ContainsKey(computer1)) { if (_sshHostKeys[computer1] == fingerPrint) { if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1); } e.CanTrust = true; } else { var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1); ThrowTerminatingError(new ErrorRecord( ex, "SSH fingerprint mismatch for host " + computer1, ErrorCategory.SecurityError, computer1)); } } else { int choice; if (_acceptkey) { choice = 0; } else { var choices = new Collection <ChoiceDescription> { new ChoiceDescription("Y"), new ChoiceDescription("N") }; choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1); } if (choice == 0) { var keymng = new TrustedKeyMng(); keymng.SetKey(computer1, fingerPrint); e.CanTrust = true; } else { e.CanTrust = false; } } }; // Set the connection timeout client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout); // Connect to host using Connection info client.Connect(); var counter = 0; // Print progess of download. client.Downloading += delegate(object sender, ScpDownloadEventArgs e) { if (e.Size != 0) { counter++; if (counter > 900) { var percent = Convert.ToInt32((e.Downloaded * 100) / e.Size); if (percent == 100) { return; } var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size)) { PercentComplete = percent }; Host.UI.WriteProgress(1, progressRecord); counter = 0; } } }; var localfullPath = Path.GetFullPath(_localfolder); WriteVerbose("Downloading " + _remotefolder); var dirinfo = new DirectoryInfo(@localfullPath); client.Download(_remotefolder, dirinfo); client.Disconnect(); WriteVerbose("Finished downloading."); } } // End process record
public virtual void WriteProgress(ProgressRecord progressRecord) { cmdlet.WriteProgress(progressRecord); }
Update(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "record should not be null"); do { if (record.ParentActivityId == record.ActivityId) { // ignore malformed records. break; } ArrayList listWhereFound = null; int indexWhereFound = -1; ProgressNode foundNode = FindNodeById(sourceId, record.ActivityId, out listWhereFound, out indexWhereFound); if (foundNode != null) { Dbg.Assert(listWhereFound != null, "node found, but list not identified"); Dbg.Assert(indexWhereFound >= 0, "node found, but index not returned"); if (record.RecordType == ProgressRecordType.Completed) { RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound); break; } if (record.ParentActivityId == foundNode.ParentActivityId) { // record is an update to an existing activity. Copy the record data into the found node, and // reset the age of the node. foundNode.Activity = record.Activity; foundNode.StatusDescription = record.StatusDescription; foundNode.CurrentOperation = record.CurrentOperation; foundNode.PercentComplete = Math.Min(record.PercentComplete, 100); foundNode.SecondsRemaining = record.SecondsRemaining; foundNode.Age = 0; break; } else { // The record's parent Id mismatches with that of the found node's. We interpret // this to mean that the activity represented by the record (and the found node) is // being "re-parented" elsewhere. So we remove the found node and treat the record // as a new activity. RemoveNodeAndPromoteChildren(listWhereFound, indexWhereFound); } } // At this point, the record's activity is not in the tree. So we need to add it. if (record.RecordType == ProgressRecordType.Completed) { // We don't track completion records that don't correspond to activities we're not // already tracking. break; } ProgressNode newNode = new ProgressNode(sourceId, record); // If we're adding a node, and we have no more space, then we need to pick a node to evict. while (_nodeCount >= maxNodeCount) { EvictNode(); } if (newNode.ParentActivityId >= 0) { ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId); if (parentNode != null) { if (parentNode.Children == null) { parentNode.Children = new ArrayList(); } AddNode(parentNode.Children, newNode); break; } // The parent node is not in the tree. Make the new node's parent the root, // and add it to the tree. If the parent ever shows up, then the next time // we receive a record for this activity, the parent id's won't match, and the // activity will be properly re-parented. newNode.ParentActivityId = -1; } AddNode(_topLevelNodes, newNode); } while (false); // At this point the tree is up-to-date. Make a pass to age all of the nodes AgeNodesAndResetStyle(); }
/// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteProgress(Int64, System.Management.Automation.ProgressRecord)"/> to display a progress record. /// </summary> /// <param name="sourceId"> /// Unique identifier of the source of the record. An int64 is used because typically, the 'this' pointer of /// the command from whence the record is originating is used, and that may be from a remote Runspace on a 64-bit /// machine. /// </param> /// <param name="record"> /// The record being reported to the host. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/> public abstract void WriteProgress(Int64 sourceId, ProgressRecord record);