Inheritance: ISerializable
示例#1
0
 protected override void ProcessRecord()
 {
     System.Management.Automation.ErrorRecord errorRecord = this.ErrorRecord;
     if (errorRecord != null)
     {
         errorRecord = new System.Management.Automation.ErrorRecord(errorRecord, null);
     }
     else
     {
         System.Exception exception = this.Exception;
         string message = this.Message;
         if (exception == null)
         {
             exception = new WriteErrorException(message);
         }
         string errorId = this.ErrorId;
         if (string.IsNullOrEmpty(errorId))
         {
             errorId = exception.GetType().FullName;
         }
         errorRecord = new System.Management.Automation.ErrorRecord(exception, errorId, this.Category, this.TargetObject);
         if ((this.Exception != null) && !string.IsNullOrEmpty(message))
         {
             errorRecord.ErrorDetails = new ErrorDetails(message);
         }
     }
     string recommendedAction = this.RecommendedAction;
     if (!string.IsNullOrEmpty(recommendedAction))
     {
         if (errorRecord.ErrorDetails == null)
         {
             errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString());
         }
         errorRecord.ErrorDetails.RecommendedAction = recommendedAction;
     }
     if (!string.IsNullOrEmpty(this.CategoryActivity))
     {
         errorRecord.CategoryInfo.Activity = this.CategoryActivity;
     }
     if (!string.IsNullOrEmpty(this.CategoryReason))
     {
         errorRecord.CategoryInfo.Reason = this.CategoryReason;
     }
     if (!string.IsNullOrEmpty(this.CategoryTargetName))
     {
         errorRecord.CategoryInfo.TargetName = this.CategoryTargetName;
     }
     if (!string.IsNullOrEmpty(this.CategoryTargetType))
     {
         errorRecord.CategoryInfo.TargetType = this.CategoryTargetType;
     }
     InvocationInfo variableValue = base.GetVariableValue("MyInvocation") as InvocationInfo;
     if (variableValue != null)
     {
         errorRecord.SetInvocationInfo(variableValue);
         errorRecord.PreserveInvocationInfoOnce = true;
         errorRecord.CategoryInfo.Activity = "Write-Error";
     }
     base.WriteError(errorRecord);
 }
 protected override void ProcessRecord()
 {
     ProviderInfo provider = null;
     Collection<string> resolvedProviderPathFromPSPath;
     try
     {
         if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem))
         {
             resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider);
         }
         else
         {
             resolvedProviderPathFromPSPath = new Collection<string> {
                 this._path
             };
         }
     }
     catch (ItemNotFoundException)
     {
         FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
         ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
         base.WriteError(errorRecord);
         return;
     }
     if (!provider.NameEquals(base.Context.ProviderNames.FileSystem))
     {
         throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName });
     }
     if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1))
     {
         if (resolvedProviderPathFromPSPath.Count > 1)
         {
             throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]);
         }
         string path = resolvedProviderPathFromPSPath[0];
         ExternalScriptInfo scriptInfo = null;
         if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase))
         {
             string str5;
             scriptInfo = base.GetScriptInfoForFile(path, out str5, false);
             PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null);
             if (sendToPipeline != null)
             {
                 base.WriteObject(sendToPipeline);
             }
         }
         else
         {
             InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path));
             ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path);
             base.ThrowTerminatingError(record3);
         }
     }
     else
     {
         FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
         ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
         base.WriteError(record2);
     }
 }
示例#3
0
 protected override void EndProcessing()
 {
     if ((this._numberRemoved == 0) && !base.MyInvocation.BoundParameters.ContainsKey("WhatIf"))
     {
         bool flag = true;
         bool flag2 = true;
         foreach (string str in this._name)
         {
             if (!InitialSessionState.IsEngineModule(str))
             {
                 flag2 = false;
             }
             if (!WildcardPattern.ContainsWildcardCharacters(str))
             {
                 flag = false;
             }
         }
         if (!flag2 && (!flag || (this._moduleInfo.Length != 0)))
         {
             InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(Modules.NoModulesRemoved, new object[0]));
             ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_NoModulesRemoved", ErrorCategory.ResourceUnavailable, null);
             base.WriteError(errorRecord);
         }
     }
 }
        public static string ExtractErrorFromErrorRecord(this Runspace runspace, ErrorRecord record)
        {
            Pipeline pipeline = runspace.CreatePipeline("$input", false);
            pipeline.Commands.Add("out-string");

            Collection<PSObject> result;
            using (PSDataCollection<object> inputCollection = new PSDataCollection<object>())
            {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = pipeline.Invoke(inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return str.Substring(0, str.Length - 2);
                }
            }

            return String.Empty;
        }
示例#5
0
 public void WriteError(ErrorRecord errorRecord)
 {
     if (_errors != null)
     {
         _errors.Add(errorRecord);
     }
 }
 private static ICollection<object> PopulateFromList( ICollection<object> list, out ErrorRecord error )
 {
     ICollection<object> objs;
     error = null;
     List<object> objs1 = new List<object>( );
     using ( IEnumerator<object> enumerator = list.GetEnumerator( ) ) {
         while ( enumerator.MoveNext( ) ) {
             object current = enumerator.Current;
             if ( current is IDictionary<string, object> ) {
                 PSObject pSObject = JsonObject.PopulateFromDictionary( current as IDictionary<string, object>, out error );
                 if ( error == null ) {
                     objs1.Add( pSObject );
                 }
                 else {
                     objs = null;
                     return objs;
                 }
             }
             else if ( !( current is ICollection<object> ) ) {
                 objs1.Add( current );
             }
             else {
                 ICollection<object> objs2 = JsonObject.PopulateFromList( current as ICollection<object>, out error );
                 if ( error == null ) {
                     objs1.Add( objs2 );
                 }
                 else {
                     objs = null;
                     return objs;
                 }
             }
         }
         return objs1.ToArray( );
     }
 }
示例#7
0
 protected override void ProcessRecord()
 {
     foreach (PSObject obj2 in this._object)
     {
         using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(obj2.ToString())))
         {
             using (StreamReader reader = new StreamReader(stream, Encoding.Unicode))
             {
                 ImportCsvHelper helper = new ImportCsvHelper(this, this._delimiter, this._header, this._typeName, reader);
                 try
                 {
                     helper.Import(ref this._alreadyWarnedUnspecifiedNames);
                 }
                 catch (ExtendedTypeSystemException exception)
                 {
                     ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
                     base.ThrowTerminatingError(errorRecord);
                 }
                 if ((this._header == null) && (helper.Header != null))
                 {
                     this._header = helper.Header.ToArray<string>();
                 }
                 if ((this._typeName == null) && (helper.TypeName != null))
                 {
                     this._typeName = helper.TypeName;
                 }
             }
         }
     }
 }
 protected override void ProcessRecord()
 {
     // TODO: Extract as resource
     this.WriteVerbose("Calculating NT hash.");
     try
     {
         byte[] hashBytes = NTHash.ComputeHash(Password);
         string hashHex = hashBytes.ToHex();
         this.WriteObject(hashHex);
     }
     catch (ArgumentException ex)
     {
         ErrorRecord error = new ErrorRecord(ex, "Error1", ErrorCategory.InvalidArgument, this.Password);
         this.WriteError(error);
     }
     catch (Win32Exception ex)
     {
         ErrorCategory category = ((Win32ErrorCode)ex.NativeErrorCode).ToPSCategory();
         ErrorRecord error = new ErrorRecord(ex, "Error2", category, this.Password);
         // Allow the processing to continue on this error:
         this.WriteError(error);
     }
     catch (Exception ex)
     {
         ErrorRecord error = new ErrorRecord(ex, "Error3", ErrorCategory.NotSpecified, this.Password);
         this.WriteError(error);
     }
 }
        //todo: requires implemetation
        /*
        [SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
        }
        */

        // todo: handle info and context
        protected ActionPreferenceStopException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            base.NoPrompt = true;

            errorRecord = null;
        }
示例#10
0
 protected override void ProcessRecord()
 {
     base.ProcessRecord();
     if (Globals.authToken != null)
     {
         _serverProxy = new ServerCommandProxy(Globals.ComputerName, Globals.Port, Globals.authToken);
         try
         {
             _serverProxy.AddAdminAccessUser(UserName);
             PSObject returnAddPcutAdminAccessUser = new PSObject();
             returnAddPcutAdminAccessUser.Properties.Add(new PSNoteProperty("Username", UserName));
             returnAddPcutAdminAccessUser.Properties.Add(new PSNoteProperty("AdminAccess", true));
             WriteObject(returnAddPcutAdminAccessUser);
         }
         catch (XmlRpcFaultException fex)
         {
             ErrorRecord errRecord = new ErrorRecord(new Exception(fex.Message, fex.InnerException), fex.FaultString, ErrorCategory.NotSpecified, fex);
             WriteError(errRecord);
         }
     }
     else
     {
         WriteObject("Please run Connect-PcutServer in order to establish connection.");
     }
 }
示例#11
0
		internal static ErrorRecord CreateFileNotFoundErrorRecord(string resourceStr, string errorId, object[] args)
		{
			string str = StringUtil.Format(resourceStr, args);
			FileNotFoundException fileNotFoundException = new FileNotFoundException(str);
			ErrorRecord errorRecord = new ErrorRecord(fileNotFoundException, errorId, ErrorCategory.ObjectNotFound, null);
			return errorRecord;
		}
示例#12
0
 internal void ReportHelpFileError(Exception exception, string target, string helpFile)
 {
     ErrorRecord item = new ErrorRecord(exception, "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, null) {
         ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "HelpErrors", "LoadHelpFileForTargetFailed", new object[] { target, helpFile, exception.Message })
     };
     this.HelpSystem.LastErrors.Add(item);
 }
示例#13
0
 private Task WriteErrorObject(object obj)
 {
     ErrorRecord er = obj as ErrorRecord;
     if (er == null)
     {
         IContainsErrorRecord cer = obj as IContainsErrorRecord;
         if (cer != null)
         {
             er = cer.ErrorRecord;
         }
         else
         {
             Exception ex = obj as Exception;
             if (ex != null)
             {
                 er = new ErrorRecord(ex, "Error.Unknown", ErrorCategory.InvalidOperation, null);
             }
             else
             {
                 er = new ErrorRecord(new Exception(obj.ToString()), "Error.Unknown", ErrorCategory.InvalidOperation, null);
             }
         }
     }
     Host.WriteLine(new FormattedText(TextClassifications.Error, er.ToString()));
     return TaskEx.FromCompleted();
 }
示例#14
0
 internal void TraceError(ErrorRecord errorRecord)
 {
     if (this._traceFrames.Count > 0)
     {
         ((TraceFrame) this._traceFrames[this._traceFrames.Count - 1]).TraceError(errorRecord);
     }
 }
示例#15
0
 protected override void ProcessRecord()
 {
     if (!(this.specifiedPath ^ this.isLiteralPath))
     {
         InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
         ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
         base.ThrowTerminatingError(errorRecord);
     }
     if (this._paths != null)
     {
         foreach (string str in this._paths)
         {
             using (StreamReader reader = PathUtils.OpenStreamReader(this, str, this.Encoding, this.isLiteralPath))
             {
                 ImportCsvHelper helper = new ImportCsvHelper(this, this._delimiter, this._header, null, reader);
                 try
                 {
                     helper.Import(ref this._alreadyWarnedUnspecifiedNames);
                 }
                 catch (ExtendedTypeSystemException exception2)
                 {
                     ErrorRecord record2 = new ErrorRecord(exception2, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
                     base.ThrowTerminatingError(record2);
                 }
             }
         }
     }
 }
 /// <summary>
 /// Processes the pipeline.
 /// </summary>
 protected override void ProcessRecord()
 {
     if (InputObject != null && InputObject is Wizard) {
         WizardStep stepToRemove = null;
         foreach (WizardStep step in InputObject.Steps) {
             if (step.Name == Name) {
                 stepToRemove = step;
             }
         }
         InputObject.Steps.Remove(stepToRemove);
         if (PassThru) {
             WriteObject(this, InputObject);
         } else {
             WriteObject(this, true);
         }
     } else {
         ErrorRecord err =
             new ErrorRecord(
                 new Exception("The wizard object you provided is not valid"),
                 "WrongWizardObject",
                 ErrorCategory.InvalidArgument,
                 InputObject);
         err.ErrorDetails =
             new ErrorDetails(
                 "The wizard object you provided is not valid");
         WriteError(this, err, true);
     }
     // WizardStep step = new WizardStep(Name, Order);
     // if (SearchCriteria != null && SearchCriteria.Length > 0) {
 }
示例#17
0
 protected override void ProcessRecord()
 {
     bool flag = false;
     List<PSEventSubscriber> list = new List<PSEventSubscriber>(base.Events.Subscribers);
     foreach (PSEventSubscriber subscriber in list)
     {
         if ((((this.sourceIdentifier == null) || this.matchPattern.IsMatch(subscriber.SourceIdentifier)) && ((this.subscriptionId < 0) || (subscriber.SubscriptionId == this.subscriptionId))) && (!subscriber.SupportEvent || (this.Force != 0)))
         {
             base.WriteObject(subscriber);
             flag = true;
         }
     }
     if (!flag)
     {
         bool flag2 = (this.sourceIdentifier != null) && !WildcardPattern.ContainsWildcardCharacters(this.sourceIdentifier);
         bool flag3 = this.subscriptionId >= 0;
         if (flag2 || flag3)
         {
             object sourceIdentifier = null;
             string format = null;
             if (flag2)
             {
                 sourceIdentifier = this.sourceIdentifier;
                 format = EventingStrings.EventSubscriptionSourceNotFound;
             }
             else if (flag3)
             {
                 sourceIdentifier = this.subscriptionId;
                 format = EventingStrings.EventSubscriptionNotFound;
             }
             ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, format, new object[] { sourceIdentifier })), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, null);
             base.WriteError(errorRecord);
         }
     }
 }
示例#18
0
 protected override void BeginProcessing()
 {
     Wizard wzd = GetWizard(Name);
     if (wzd == null) {
         ErrorRecord err =
             new ErrorRecord(
                 new Exception("Couldn't get the wizard you asked for"),
                 "NoSuchWizard",
                 ErrorCategory.InvalidArgument,
                 Name);
         err.ErrorDetails =
             new ErrorDetails(
                 "Failed to get the wizard you asked for");
         //ThrowTerminatingError(err);
         this.WriteError(this, err, true);
     } else {
         this.WriteVerbose(this, "running script blocks");
         RunWizardScriptBlocks(this, wzd);
         //if (PassThru) {
         this.WriteObject(this, wzd);
         //} else {
         // WriteObject(this, true);
         //}
     }
 }
        private static void WarnAboutUnsupportedActionPreferences(
            Cmdlet cmdlet,
            ActionPreference effectiveActionPreference,
            string nameOfCommandLineParameter,
            Func<string> inquireMessageGetter,
            Func<string> stopMessageGetter)
        {
            string message;
            switch (effectiveActionPreference)
            {
                case ActionPreference.Stop:
                    message = stopMessageGetter();
                    break;

                case ActionPreference.Inquire:
                    message = inquireMessageGetter();
                    break;

                default:
                    return; // we can handle everything that is not Stop or Inquire
            }

            bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);
            if (actionPreferenceComesFromCommandLineParameter)
            {
                Exception exception = new ArgumentException(message);
                ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
示例#20
0
		protected override void EndProcessing()
		{
			using (base.CurrentPSTransaction)
			{
				try
				{
					this.transactedScript.InvokeUsingCmdlet(this, false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, null, new object[0], AutomationNull.Value, new object[0]);
				}
				catch (Exception exception1)
				{
					Exception exception = exception1;
					CommandProcessorBase.CheckForSevereException(exception);
					ErrorRecord errorRecord = new ErrorRecord(exception, "TRANSACTED_SCRIPT_EXCEPTION", ErrorCategory.NotSpecified, null);
					bool flag = false;
					Exception innerException = exception;
					while (innerException != null)
					{
						if (innerException as TimeoutException == null)
						{
							innerException = innerException.InnerException;
						}
						else
						{
							flag = true;
							break;
						}
					}
					if (flag)
					{
						errorRecord = new ErrorRecord(new InvalidOperationException(TransactionResources.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, exception);
					}
					base.WriteError(errorRecord);
				}
			}
		}
示例#21
0
		internal static ErrorRecord CreateNotSupportedErrorRecord(string resourceStr, string errorId, object[] args)
		{
			string str = StringUtil.Format(resourceStr, args);
			NotSupportedException notSupportedException = new NotSupportedException(str);
			ErrorRecord errorRecord = new ErrorRecord(notSupportedException, errorId, ErrorCategory.NotImplemented, null);
			return errorRecord;
		}
示例#22
0
 protected override void ProcessRecord()
 {
     bool flag = false;
     lock (base.Events.ReceivedEvents.SyncRoot)
     {
         PSEventArgsCollection receivedEvents = base.Events.ReceivedEvents;
         for (int i = receivedEvents.Count; i > 0; i--)
         {
             PSEventArgs args = receivedEvents[i - 1];
             if (((this.sourceIdentifier == null) || this.matchPattern.IsMatch(args.SourceIdentifier)) && ((this.eventIdentifier < 0) || (args.EventIdentifier == this.eventIdentifier)))
             {
                 flag = true;
                 if (base.ShouldProcess(string.Format(Thread.CurrentThread.CurrentCulture, EventingStrings.EventResource, new object[] { args.SourceIdentifier }), EventingStrings.Remove))
                 {
                     receivedEvents.RemoveAt(i - 1);
                 }
             }
         }
     }
     if (((this.sourceIdentifier != null) && !WildcardPattern.ContainsWildcardCharacters(this.sourceIdentifier)) && !flag)
     {
         ErrorRecord errorRecord = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, EventingStrings.SourceIdentifierNotFound, new object[] { this.sourceIdentifier })), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, null);
         base.WriteError(errorRecord);
     }
     else if ((this.eventIdentifier >= 0) && !flag)
     {
         ErrorRecord record2 = new ErrorRecord(new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, EventingStrings.EventIdentifierNotFound, new object[] { this.eventIdentifier })), "INVALID_EVENT_IDENTIFIER", ErrorCategory.InvalidArgument, null);
         base.WriteError(record2);
     }
 }
示例#23
0
 private void ExtractTags(Object obj, string filename)
 {
     try {
         var f = TagLib.File.Create(filename);
         WriteObject(new TagSet(filename,f.Tag));
     }
     catch (TagLib.UnsupportedFormatException e)
     {
         if (!useWildcard)
         {
             var err = new ErrorRecord(e, "The format is unsupported by get-tags", ErrorCategory.InvalidArgument, obj);
             WriteError(err);
         }
     }
     catch (System.IO.FileNotFoundException e)
     {
         var err = new ErrorRecord(e, "File doesn't exist", ErrorCategory.ResourceUnavailable, obj);
         WriteError(err);
     }
     catch (TagLib.CorruptFileException e)
     {
         var err = new ErrorRecord(e, "File is corrupted", ErrorCategory.InvalidData, obj);
         WriteError(err);
     }
     catch (Exception e)
     {
         WriteDebug(e.ToString());
     }
 }
        protected override void ProcessRecord()
        {
            const string particular = @"Software\ParticularSoftware";

            ProviderInfo provider;
            PSDriveInfo drive;
            var psPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LicenseFile, out provider, out drive);
            

            if (provider.ImplementingType != typeof(FileSystemProvider))
            {
                var ex = new ArgumentException(string.Format("{0} does not resolve to a path on the FileSystem provider.", psPath));
                var error = new ErrorRecord(ex, "InvalidProvider", ErrorCategory.InvalidArgument, psPath);
                WriteError(error);
                return;
            }

            var content = File.ReadAllText(psPath);
            if (!CheckFileContentIsALicenseFile(content))
            {
                var ex = new InvalidDataException(string.Format("{0} is not not a valid license file", psPath));
                var error = new ErrorRecord(ex, "InvalidLicense", ErrorCategory.InvalidData, psPath);
                WriteError(error);
                return;
            }

            if (EnvironmentHelper.Is64BitOperatingSystem)
            {
                RegistryHelper.LocalMachine(RegistryView.Registry64).WriteValue(particular, "License", content, RegistryValueKind.String);    
            }
            RegistryHelper.LocalMachine(RegistryView.Registry32).WriteValue(particular, "License", content, RegistryValueKind.String);
        }
示例#25
0
 internal PSInvalidOperationException(string message, string id, ErrorCategory errorCategory,
                                      Exception innerException, bool terminating = true)
     : base(message, innerException)
 {
     Terminating = terminating;
     ErrorRecord = new ErrorRecord(this, id, errorCategory, null);
 }
示例#26
0
 private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocument xDoc, Hashtable namespacetable)
 {
     XmlNamespaceManager manager;
     if (parametersetname.Equals("Xml"))
     {
         XmlNameTable nameTable = new NameTable();
         manager = new XmlNamespaceManager(nameTable);
     }
     else
     {
         manager = new XmlNamespaceManager(xDoc.NameTable);
     }
     foreach (DictionaryEntry entry in namespacetable)
     {
         try
         {
             string prefix = entry.Key.ToString();
             manager.AddNamespace(prefix, entry.Value.ToString());
         }
         catch (NullReferenceException)
         {
             InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError, new object[0]));
             ErrorRecord errorRecord = new ErrorRecord(exception, "PrefixError", ErrorCategory.InvalidOperation, namespacetable);
             base.WriteError(errorRecord);
         }
         catch (ArgumentNullException)
         {
             InvalidOperationException exception2 = new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError, new object[0]));
             ErrorRecord record2 = new ErrorRecord(exception2, "PrefixError", ErrorCategory.InvalidOperation, namespacetable);
             base.WriteError(record2);
         }
     }
     return manager;
 }
示例#27
0
 /// <summary>
 /// Default implementation of WriteError - if the error record contains
 /// an exception then that exception will be thrown. If not, then an
 /// InvalidOperationException will be constructed and thrown.
 /// </summary>
 /// <param name="errorRecord">Error record instance to process</param>
 public void WriteError(ErrorRecord errorRecord)
 {
     if (errorRecord.Exception != null)
         throw errorRecord.Exception;
     else
         throw new InvalidOperationException(errorRecord.ToString());
 }
        public static ErrorRecord WriteException(this Cmdlet cmdlet, Exception ex, bool isTerminating = false)
        {
            var errorCode = "Unknown";
            var errorCategory = ErrorCategory.NotSpecified;
            object targetObj = null;

            if (ex.Data.Contains(ERROR_CODE))
            {
                errorCode = ex.Data[ERROR_CODE].ToString();
            }

            if (ex.Data.Contains(ERROR_CATEGORY))
            {
                errorCategory = (ex.Data[ERROR_CATEGORY] as ErrorCategory?).GetValueOrDefault();
            }

            if (ex.Data.Contains(ERROR_TARGET))
            {
                targetObj = ex.Data[ERROR_TARGET];
            }

            var err = new ErrorRecord(ex, errorCode, errorCategory, targetObj);

            if (isTerminating)
            {
                cmdlet.ThrowTerminatingError(err);
            }
            else
            {
                cmdlet.WriteError(err);
            }

            return err;
        }
示例#29
0
		protected override void BeginProcessing()
		{
			try
			{
				string str = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "eventvwr.exe");
				Process.Start(str, this._computerName);
			}
			catch (Win32Exception win32Exception1)
			{
				Win32Exception win32Exception = win32Exception1;
				int nativeErrorCode = win32Exception.NativeErrorCode;
				if (!nativeErrorCode.Equals(2))
				{
					ErrorRecord errorRecord = new ErrorRecord(win32Exception, "Win32Exception", ErrorCategory.InvalidArgument, null);
					base.WriteError(errorRecord);
				}
				else
				{
					string str1 = StringUtil.Format(EventlogResources.NotSupported, new object[0]);
					InvalidOperationException invalidOperationException = new InvalidOperationException(str1);
					ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException, "Win32Exception", ErrorCategory.InvalidOperation, null);
					base.WriteError(errorRecord1);
				}
			}
			catch (SystemException systemException1)
			{
				SystemException systemException = systemException1;
				ErrorRecord errorRecord2 = new ErrorRecord(systemException, "InvalidComputerName", ErrorCategory.InvalidArgument, this._computerName);
				base.WriteError(errorRecord2);
			}
		}
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fullyQualifiedErrorId"></param>
        /// <param name="errorCategory"></param>
        /// <param name="innerException"></param>
        /// <param name="resourceId"></param>
        /// <param name="resourceParms"></param>
        /// <returns></returns>
        internal static ErrorRecord CreateErrorRecord(
            string fullyQualifiedErrorId,
            ErrorCategory errorCategory,
            Exception innerException,
            string resourceId,
            params object[] resourceParms)
        {
            InvalidOperationException invalidOperationException;

            string errorMessage = string.Format(
                CultureInfo.CurrentCulture,
                resourceId,
                resourceParms);

            if (innerException != null)
            {
                invalidOperationException = new InvalidOperationException(errorMessage, innerException);
            }
            else
            {
                invalidOperationException = new InvalidOperationException(errorMessage);
            }

            ErrorRecord errorRecord = new ErrorRecord(
                invalidOperationException,
                fullyQualifiedErrorId,
                errorCategory,
                null);

            return errorRecord;
        }
 private void CreateErrorRecord()
 {
     if (!string.IsNullOrEmpty(this._assemblyName) && !string.IsNullOrEmpty(this._typeName))
     {
         this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "UndefinedRunspaceConfigurationType", ErrorCategory.ResourceUnavailable, null);
         this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "MiniShellErrors", "UndefinedRunspaceConfigurationType", new object[] { this._assemblyName, this._typeName });
     }
 }
        protected bool CheckFileExists(string file)
        {
            if (System.IO.File.Exists(file)) return true;

            this.WriteVerbose("Filename: {0}", file);
            this.WriteVerbose("Abs Filename: {0}", System.IO.Path.GetFullPath(file));
            var exc = new System.IO.FileNotFoundException(file);
            var er = new SMA.ErrorRecord(exc, "FILE_NOT_FOUND", SMA.ErrorCategory.ResourceUnavailable, null);
            this.WriteError(er);
            return false;
        }
示例#33
0
        private void CreateErrorRecord()
        {
            StringBuilder builder = new StringBuilder();

            if (this.PSSnapInExceptions != null)
            {
                foreach (PSSnapInException exception in this.PSSnapInExceptions)
                {
                    builder.Append("\n");
                    builder.Append(exception.Message);
                }
            }
            this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "ConsoleLoadFailure", ErrorCategory.ResourceUnavailable, null);
            this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "ConsoleInfoErrorStrings", "ConsoleLoadFailure", new object[] { this._consoleFileName, builder.ToString() });
        }
示例#34
0
 private void CreateErrorRecord()
 {
     if (!string.IsNullOrEmpty(this._PSSnapin) && !string.IsNullOrEmpty(this._reason))
     {
         if (this._warning)
         {
             this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadWarning", ErrorCategory.ResourceUnavailable, null);
             this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "ConsoleInfoErrorStrings", "PSSnapInLoadWarning", new object[] { this._PSSnapin, this._reason });
         }
         else
         {
             this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "PSSnapInLoadFailure", ErrorCategory.ResourceUnavailable, null);
             this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "ConsoleInfoErrorStrings", "PSSnapInLoadFailure", new object[] { this._PSSnapin, this._reason });
         }
     }
 }
示例#35
0
        /// <summary>
        /// THE method for opening a file for writing.
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">Cmdlet that is opening the file (used mainly for error reporting).</param>
        /// <param name="filePath">Path to the file (as specified on the command line - this method will resolve the path).</param>
        /// <param name="resolvedEncoding">Encoding (this method will convert the command line string to an Encoding instance).</param>
        /// <param name="defaultEncoding">If <see langword="true"/>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter.</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing.</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing.</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<see langword="null"/> is this is not needed).</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            Encoding resolvedEncoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;

            // resolve the path and the encoding
            string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                // variable to track file open mode
                // this is controlled by append/force parameters
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    // throw IOException if file exists
                    mode = FileMode.CreateNew;
                }

                if (Force && (Append || !NoClobber))
                {
                    if (File.Exists(resolvedPath))
                    {
                        FileInfo fInfo = new FileInfo(resolvedPath);
                        if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            // remember to reset the read-only attribute later
                            readOnlyFileInfo = fInfo;
                            // Clear the read-only attribute
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                    }
                }

                // if the user knows what he/she is doing and uses "-Force" switch,
                // then we let more than 1 process write to the same file at the same time
                FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read;

                // mode is controlled by force and ShouldContinue()
                fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare);

                // create stream writer
                // NTRAID#Windows Out Of Band Releases-931008-2006/03/27
                // For some reason, calling this without specifying
                // the encoding is different from passing Encoding.Default.
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            // These are the known exceptions for File.Load and StreamWriter.ctor
            catch (ArgumentException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (IOException e)
            {
                if (NoClobber && File.Exists(resolvedPath))
                {
                    // This probably happened because the file already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    errorRecord.ErrorDetails = new ErrorDetails(
                        cmdlet,
                        "PathUtilsStrings",
                        "UtilityFileExistsNoClobber",
                        filePath,
                        "NoClobber"); // prevents localization

                    // NOTE: this call will throw
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (UnauthorizedAccessException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (NotSupportedException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (System.Security.SecurityException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
        }
        /// <summary>
        /// Wraps the exception which occurred during cmdlet invocation,
        /// stores that as the exception to be returned from
        /// PipelineProcessor.SynchronousExecute, and writes it to
        /// the error variable.
        /// </summary>
        /// <param name="e">
        /// The exception to wrap in a CmdletInvocationException or
        /// CmdletProviderInvocationException.
        /// </param>
        /// <returns>
        /// Always returns PipelineStoppedException.  The caller should
        /// throw this exception.
        /// </returns>
        /// <remarks>
        /// Almost all exceptions which occur during pipeline invocation
        /// are wrapped in CmdletInvocationException before they are stored
        /// in the pipeline.  However, there are several exceptions:
        ///
        /// AccessViolationException, StackOverflowException:
        /// These are considered to be such severe errors that we
        /// FailFast the process immediately.
        ///
        /// ProviderInvocationException: In this case, we assume that the
        /// cmdlet is get-item or the like, a thin wrapper around the
        /// provider API.  We discard the original ProviderInvocationException
        /// and re-wrap its InnerException (the real error) in
        /// CmdletProviderInvocationException. This makes it easier to reach
        /// the real error.
        ///
        /// CmdletInvocationException, ActionPreferenceStopException:
        /// This indicates that the cmdlet itself ran a command which failed.
        /// We could go ahead and wrap the original exception in multiple
        /// layers of CmdletInvocationException, but this makes it difficult
        /// for the caller to access the root problem, plus the serialization
        /// layer might not communicate properties beyond some fixed depth.
        /// Instead, we choose to not re-wrap the exception.
        ///
        /// PipelineStoppedException: This could mean one of two things.
        /// It usually means that this pipeline has already stopped,
        /// in which case the pipeline already stores the original error.
        /// It could also mean that the cmdlet ran a command which was
        /// stopped by CTRL-C etc, in which case we choose not to
        /// re-wrap the exception as with CmdletInvocationException.
        /// </remarks>
        internal PipelineStoppedException ManageInvocationException(Exception e)
        {
            try
            {
                if (Command != null)
                {
                    do // false loop
                    {
                        if (e is ProviderInvocationException pie)
                        {
                            // If a ProviderInvocationException occurred, discard the ProviderInvocationException
                            // and re-wrap it in CmdletProviderInvocationException.
                            e = new CmdletProviderInvocationException(pie, Command.MyInvocation);
                            break;
                        }

                        // HaltCommandException will cause the command to stop, but not be reported as an error.
                        // FlowControlException should not be wrapped.
                        if (e is PipelineStoppedException ||
                            e is CmdletInvocationException ||
                            e is ActionPreferenceStopException ||
                            e is HaltCommandException ||
                            e is FlowControlException ||
                            e is ScriptCallDepthException)
                        {
                            // do nothing; do not rewrap these exceptions
                            break;
                        }

                        RuntimeException rte = e as RuntimeException;
                        if (rte != null && rte.WasThrownFromThrowStatement)
                        {
                            // do not rewrap a script based throw
                            break;
                        }

                        // wrap all other exceptions
                        e = new CmdletInvocationException(e, Command.MyInvocation);
                    } while (false);

                    // commandRuntime.ManageException will always throw PipelineStoppedException
                    // Otherwise, just return this exception...

                    // If this exception happened in a transacted cmdlet,
                    // rollback the transaction
                    if (commandRuntime.UseTransaction)
                    {
                        // The "transaction timed out" exception is
                        // exceedingly obtuse. We clarify things here.
                        bool      isTimeoutException = false;
                        Exception tempException      = e;
                        while (tempException != null)
                        {
                            if (tempException is System.TimeoutException)
                            {
                                isTimeoutException = true;
                                break;
                            }

                            tempException = tempException.InnerException;
                        }

                        if (isTimeoutException)
                        {
                            ErrorRecord errorRecord = new ErrorRecord(
                                new InvalidOperationException(
                                    TransactionStrings.TransactionTimedOut),
                                "TRANSACTION_TIMEOUT",
                                ErrorCategory.InvalidOperation,
                                e);
                            errorRecord.SetInvocationInfo(Command.MyInvocation);

                            e = new CmdletInvocationException(errorRecord);
                        }

                        // Rollback the transaction in the case of errors.
                        if (
                            _context.TransactionManager.HasTransaction
                            &&
                            _context.TransactionManager.RollbackPreference != RollbackSeverity.Never
                            )
                        {
                            Context.TransactionManager.Rollback(true);
                        }
                    }

                    return((PipelineStoppedException)this.commandRuntime.ManageException(e));
                }

                // Upstream cmdlets see only that execution stopped
                // This should only happen if Command is null
                return(new PipelineStoppedException());
            }
            catch (Exception)
            {
                // this method should not throw exceptions; warn about any violations on checked builds and re-throw
                Diagnostics.Assert(false, "This method should not throw exceptions!");
                throw;
            }
        }
示例#37
0
        internal static void MasterStreamOpen(PSCmdlet cmdlet, string filePath, Encoding resolvedEncoding, bool defaultEncoding, bool Append, bool Force, bool NoClobber, out FileStream fileStream, out StreamWriter streamWriter, out FileInfo readOnlyFileInfo, bool isLiteralPath)
        {
            fileStream       = null;
            streamWriter     = null;
            readOnlyFileInfo = null;
            string path = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                FileMode create = FileMode.Create;
                if (Append)
                {
                    create = FileMode.Append;
                }
                else if (NoClobber)
                {
                    create = FileMode.CreateNew;
                }
                if ((Force && (Append || !NoClobber)) && File.Exists(path))
                {
                    FileInfo info = new FileInfo(path);
                    if ((info.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        readOnlyFileInfo = info;
                        info.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                    }
                }
                FileShare share = Force ? FileShare.ReadWrite : FileShare.Read;
                fileStream = new FileStream(path, create, FileAccess.Write, share);
                if (defaultEncoding)
                {
                    streamWriter = new StreamWriter(fileStream);
                }
                else
                {
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
                }
            }
            catch (ArgumentException exception)
            {
                ReportFileOpenFailure(cmdlet, path, exception);
            }
            catch (IOException exception2)
            {
                if (NoClobber && File.Exists(path))
                {
                    ErrorRecord errorRecord = new ErrorRecord(exception2, "NoClobber", ErrorCategory.ResourceExists, path)
                    {
                        ErrorDetails = new ErrorDetails(cmdlet, "PathUtilsStrings", "UtilityFileExistsNoClobber", new object[] { filePath, "NoClobber" })
                    };
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                ReportFileOpenFailure(cmdlet, path, exception2);
            }
            catch (UnauthorizedAccessException exception3)
            {
                ReportFileOpenFailure(cmdlet, path, exception3);
            }
            catch (NotSupportedException exception4)
            {
                ReportFileOpenFailure(cmdlet, path, exception4);
            }
            catch (SecurityException exception5)
            {
                ReportFileOpenFailure(cmdlet, path, exception5);
            }
        }
示例#38
0
        internal static List <string> GetSuggestion(Runspace runspace)
        {
            LocalRunspace localRunspace = runspace as LocalRunspace;

            if (localRunspace is null)
            {
                return(new List <string>());
            }

            // Get the last value of $?
            bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;

            // Get the last history item
            History history = localRunspace.History;

            HistoryInfo[] entries = history.GetEntries(-1, 1, true);

            if (entries.Length == 0)
            {
                return(new List <string>());
            }

            HistoryInfo lastHistory = entries[0];

            // Get the last error
            ArrayList errorList = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable;
            object    lastError = null;

            if (errorList.Count > 0)
            {
                lastError = errorList[0] as Exception;
                ErrorRecord lastErrorRecord = null;

                // The error was an actual ErrorRecord
                if (lastError is null)
                {
                    lastErrorRecord = errorList[0] as ErrorRecord;
                }
                else if (lastError is RuntimeException)
                {
                    lastErrorRecord = ((RuntimeException)lastError).ErrorRecord;
                }

                // If we got information about the error invocation,
                // we can be more careful with the errors we pass along
                if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null))
                {
                    if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id)
                    {
                        lastError = lastErrorRecord;
                    }
                    else
                    {
                        lastError = null;
                    }
                }
            }

            Runspace oldDefault     = null;
            bool     changedDefault = false;

            if (Runspace.DefaultRunspace != runspace)
            {
                oldDefault               = Runspace.DefaultRunspace;
                changedDefault           = true;
                Runspace.DefaultRunspace = runspace;
            }

            List <string> suggestions = null;

            try
            {
                suggestions = GetSuggestion(lastHistory, lastError, errorList);
            }
            finally
            {
                if (changedDefault)
                {
                    Runspace.DefaultRunspace = oldDefault;
                }
            }

            // Restore $?
            localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue;
            return(suggestions);
        }
        private static IEnumerable <CimModule> GetCimModules(
            CimSession cimSession,
            Uri resourceUri,
            string cimNamespace,
            string moduleNamePattern,
            bool onlyManifests,
            Cmdlet cmdlet,
            CancellationToken cancellationToken)
        {
            Dbg.Assert(cimSession != null, "Caller should verify cimSession != null");
            Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null");

            const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
            var    wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions);
            string dosWildcard     = WildcardPatternToDosWildcardParser.Parse(wildcardPattern);

            var options = new CimOperationOptions {
                CancellationToken = cancellationToken
            };

            options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false);
            if (resourceUri != null)
            {
                options.ResourceUri = resourceUri;
            }

            if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null))
            {
                cimNamespace = DiscoveryProviderNamespace;
            }

            // TODO/FIXME: ETW for method invocation
            IEnumerable <CimInstance> syncResults = cimSession.EnumerateInstances(
                cimNamespace,
                DiscoveryProviderModuleClass,
                options);
            // TODO/FIXME: ETW for method results
            IEnumerable <CimModule> cimModules = syncResults
                                                 .Select(cimInstance => new CimModule(cimInstance))
                                                 .Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName));

            if (!onlyManifests)
            {
                cimModules = cimModules.Select(
                    delegate(CimModule cimModule)
                {
                    cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options);
                    return(cimModule);
                });
            }

            return(EnumerateWithCatch(
                       cimModules,
                       delegate(Exception exception)
            {
                ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception);
                if (!cmdlet.MyInvocation.ExpectingInput)
                {
                    if (((-1) != errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase)) ||
                        (cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) ||
                        (!cimSession.TestConnection()))
                    {
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }

                cmdlet.WriteError(errorRecord);
            }));
        }
示例#40
0
        /// <summary>
        /// Make a hash for the file
        /// </summary>
        ///
        /// <param name="filePath"> Path of the file </param>
        /// <param name="hashAlgorithm"> Used to calculate Hash </param>
        /// <returns> HashValue for the file </returns>
        internal static string CalculateFileHash(string filePath, string hashAlgorithm)
        {
            string hashValue = string.Empty;
            IntPtr catAdmin  = IntPtr.Zero;

            // To get handle to the hash algorithm to be used to calculate hashes
            if (!NativeMethods.CryptCATAdminAcquireContext2(ref catAdmin, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0))
            {
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm)), "UnableToAcquireHashAlgorithmContext", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }

            DWORD  GENERIC_READ         = 0x80000000;
            DWORD  OPEN_EXISTING        = 3;
            IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

            // Open the file that is to be hashed for reading and get its handle
            IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero);

            if (fileHandle != INVALID_HANDLE_VALUE)
            {
                try
                {
                    DWORD  hashBufferSize = 0;
                    IntPtr hashBuffer     = IntPtr.Zero;

                    // Call first time to get the size of expected buffer to hold new hash value
                    if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0))
                    {
                        ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null);
                        _cmdlet.ThrowTerminatingError(errorRecord);
                    }

                    int size = (int)hashBufferSize;
                    hashBuffer = Marshal.AllocHGlobal(size);
                    try
                    {
                        // Call second time to actually get the hash value
                        if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0))
                        {
                            ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null);
                            _cmdlet.ThrowTerminatingError(errorRecord);
                        }

                        byte[] hashBytes = new byte[size];
                        Marshal.Copy(hashBuffer, hashBytes, 0, size);
                        hashValue = BitConverter.ToString(hashBytes).Replace("-", "");
                    }
                    finally
                    {
                        if (hashBuffer != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(hashBuffer);
                        }
                    }
                }
                finally
                {
                    NativeMethods.CryptCATAdminReleaseContext(catAdmin, 0);
                    NativeMethods.CloseHandle(fileHandle);
                }
            }
            else
            {
                // If we are not able to open file that is to be hashed we can not continue with catalog validation
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }
            return(hashValue);
        }
示例#41
0
        /// <summary>
        /// Generate the Catalog file for Input Catalog Defintion File
        /// </summary>
        ///
        /// <param name="cdfFilePath"> Path to the Input .cdf file </param>
        internal static void GenerateCatalogFile(string cdfFilePath)
        {
            string pwszFilePath = cdfFilePath;

            NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback);

            // Open CDF File
            IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack);

            // navigate CDF header and files sections
            if (resultCDF != IntPtr.Zero)
            {
                // First navigate all catalog level attributes entries first, they represent zero size files
                IntPtr catalogAttr = IntPtr.Zero;
                do
                {
                    catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack);

                    if (catalogAttr != IntPtr.Zero)
                    {
                        string filePath = ProcessFilePathAttributeInCatalog(catalogAttr);
                        _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, filePath, filePath));
                    }
                } while (catalogAttr != IntPtr.Zero);

                // navigate all the files hash entries in the .cdf file
                IntPtr memberInfo = IntPtr.Zero;
                try
                {
                    IntPtr memberFile = IntPtr.Zero;
                    NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback);
                    string fileName = string.Empty;
                    do
                    {
                        memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero);
                        fileName   = Marshal.PtrToStringUni(memberFile);

                        if (!String.IsNullOrEmpty(fileName))
                        {
                            IntPtr memberAttr       = IntPtr.Zero;
                            string fileRelativePath = String.Empty;
                            do
                            {
                                memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack);

                                if (memberAttr != IntPtr.Zero)
                                {
                                    fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr);
                                    if (!String.IsNullOrEmpty(fileRelativePath))
                                    {
                                        // Found the attribute we are looking for
                                        // Filename we read from the above API has <Hash> appended to its name as per CDF file tags convention
                                        // Truncating that Information from the string.
                                        string itemName = fileName.Substring(6);
                                        _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath));
                                        break;
                                    }
                                }
                            } while (memberAttr != IntPtr.Zero);
                        }
                    } while (fileName != null);
                }
                finally
                {
                    NativeMethods.CryptCATCDFClose(resultCDF);
                }
            }
            else
            {
                // If we are not able to open CDF file we can not continue generating catalog
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
 protected PSInvalidOperationException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     ErrorRecord = new ErrorRecord(this, "InvalidOperation",
                                   ErrorCategory.InvalidOperation, null);
 }
示例#43
0
        /// <summary>
        /// Make list of hashes for given Catalog File
        /// </summary>
        /// <param name="catalogFilePath"> Path to the folder having catalog file </param>
        /// <param name="excludedPatterns"></param>
        /// <param name="catalogVersion"> The version of input catalog we read from catalog meta data after opening it.</param>
        /// <returns> Dictionary mapping files relative paths to HashValues </returns>
        internal static Dictionary <String, String> GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion)
        {
            IntPtr resultCatalog        = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0);
            IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
            Dictionary <String, String> catalogHashes = new Dictionary <String, String>(StringComparer.CurrentCultureIgnoreCase);

            catalogVersion = 0;

            if (resultCatalog != INVALID_HANDLE_VALUE)
            {
                try
                {
                    IntPtr catAttrInfo = IntPtr.Zero;

                    // First traverse all catalog level attributes to get information about zero size file.
                    do
                    {
                        catAttrInfo = NativeMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo);

                        // If we found attribute it is a file information  retrieve its relative path
                        // and add it to catalog hash collection if its not in excluded files criteria
                        if (catAttrInfo != IntPtr.Zero)
                        {
                            string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo);
                            if (!String.IsNullOrEmpty(relativePath))
                            {
                                ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes);
                            }
                        }
                    } while (catAttrInfo != IntPtr.Zero);

                    catalogVersion = GetCatalogVersion(resultCatalog);

                    IntPtr memberInfo = IntPtr.Zero;
                    // Next Navigate all members in Catalog files and get their relative paths and hashes
                    do
                    {
                        memberInfo = NativeMethods.CryptCATEnumerateMember(resultCatalog, memberInfo);
                        if (memberInfo != IntPtr.Zero)
                        {
                            NativeMethods.CRYPTCATMEMBER    currentMember = ClrFacade.PtrToStructure <NativeMethods.CRYPTCATMEMBER>(memberInfo);
                            NativeMethods.SIP_INDIRECT_DATA pIndirectData = ClrFacade.PtrToStructure <NativeMethods.SIP_INDIRECT_DATA>(currentMember.pIndirectData);

                            // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well
                            // We validate those along with file hashes so we are skipping duplicate entries
                            if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase))))
                            {
                                string relativePath   = String.Empty;
                                IntPtr memberAttrInfo = IntPtr.Zero;
                                do
                                {
                                    memberAttrInfo = NativeMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo);

                                    if (memberAttrInfo != IntPtr.Zero)
                                    {
                                        relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo);
                                        if (!String.IsNullOrEmpty(relativePath))
                                        {
                                            break;
                                        }
                                    }
                                }while (memberAttrInfo != IntPtr.Zero);

                                // If we did not find any Relative Path for the item in catalog we should quit
                                // This catalog must  not be valid for our use as catalogs generated using New-FileCatalog
                                // always contains relative file Paths
                                if (String.IsNullOrEmpty(relativePath))
                                {
                                    ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null);
                                    _cmdlet.ThrowTerminatingError(errorRecord);
                                }

                                ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes);
                            }
                        }
                    } while (memberInfo != IntPtr.Zero);
                }
                finally
                {
                    NativeMethods.CryptCATClose(resultCatalog);
                }
            }
            else
            {
                ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null);
                _cmdlet.ThrowTerminatingError(errorRecord);
            }
            return(catalogHashes);
        }
示例#44
0
 internal SelectObjectException(System.Management.Automation.ErrorRecord errorRecord)
 {
     this.errorRecord = errorRecord;
 }
示例#45
0
 private void CreateErrorRecord()
 {
     this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "HelpCategoryInvalid", ErrorCategory.InvalidArgument, null);
     this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "HelpErrors", "HelpCategoryInvalid", new object[] { this._helpCategory });
 }
        protected override void ProcessRecord()
        {
            System.Management.Automation.ErrorRecord errorRecord = this.ErrorRecord;
            if (errorRecord != null)
            {
                errorRecord = new System.Management.Automation.ErrorRecord(errorRecord, null);
            }
            else
            {
                System.Exception exception = this.Exception;
                string           message   = this.Message;
                if (exception == null)
                {
                    exception = new WriteErrorException(message);
                }
                string errorId = this.ErrorId;
                if (string.IsNullOrEmpty(errorId))
                {
                    errorId = exception.GetType().FullName;
                }
                errorRecord = new System.Management.Automation.ErrorRecord(exception, errorId, this.Category, this.TargetObject);
                if ((this.Exception != null) && !string.IsNullOrEmpty(message))
                {
                    errorRecord.ErrorDetails = new ErrorDetails(message);
                }
            }
            string recommendedAction = this.RecommendedAction;

            if (!string.IsNullOrEmpty(recommendedAction))
            {
                if (errorRecord.ErrorDetails == null)
                {
                    errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString());
                }
                errorRecord.ErrorDetails.RecommendedAction = recommendedAction;
            }
            if (!string.IsNullOrEmpty(this.CategoryActivity))
            {
                errorRecord.CategoryInfo.Activity = this.CategoryActivity;
            }
            if (!string.IsNullOrEmpty(this.CategoryReason))
            {
                errorRecord.CategoryInfo.Reason = this.CategoryReason;
            }
            if (!string.IsNullOrEmpty(this.CategoryTargetName))
            {
                errorRecord.CategoryInfo.TargetName = this.CategoryTargetName;
            }
            if (!string.IsNullOrEmpty(this.CategoryTargetType))
            {
                errorRecord.CategoryInfo.TargetType = this.CategoryTargetType;
            }
            InvocationInfo variableValue = base.GetVariableValue("MyInvocation") as InvocationInfo;

            if (variableValue != null)
            {
                errorRecord.SetInvocationInfo(variableValue);
                errorRecord.PreserveInvocationInfoOnce = true;
                errorRecord.CategoryInfo.Activity      = "Write-Error";
            }
            base.WriteError(errorRecord);
        }
示例#47
0
 private void CreateErrorRecord()
 {
     this._errorRecord = new System.Management.Automation.ErrorRecord(new ParentContainsErrorRecordException(this), "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
     this._errorRecord.ErrorDetails = new ErrorDetails(Assembly.GetExecutingAssembly(), "HelpErrors", "HelpNotFound", new object[] { this._helpTopic });
 }
示例#48
0
 public void WriteErrorRecord(System.Management.Automation.ErrorRecord errorRecord)
 {
     Console.WriteLine(ConsoleColor.Red, ConsoleColor.Black, errorRecord.ToString());
 }
示例#49
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
示例#50
0
        internal static void ReportFileOpenFailure(Cmdlet cmdlet, string filePath, Exception e)
        {
            ErrorRecord errorRecord = new ErrorRecord(e, "FileOpenFailure", ErrorCategory.OpenError, null);

            cmdlet.ThrowTerminatingError(errorRecord);
        }