public void Increment_WithException_AddReadingDataForTheSpecificException() { var sensor = new ExceptionSensor(); ArgumentException exception = new ArgumentException(); sensor.AddError(exception); Reading reading = null; ReadingPublisher.Readings.TryDequeue(out reading); // TotalExceptions ReadingPublisher.Readings.TryDequeue(out reading); Assert.That(reading.Data.Name, Is.EqualTo(exception.GetType().Name)); }
//------------------------------------------------------------------------- public virtual void failure() { System.ArgumentException ex = new System.ArgumentException("failure"); Result <string> test = Result.failure(ex); assertEquals(test.Success, false); assertEquals(test.Failure, true); assertEquals(test.getValueOrElse("blue"), "blue"); assertEquals(test.getValueOrElseApply(f => "blue"), "blue"); //JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter: assertEquals(test.getValueOrElseApply(Failure::getMessage), "failure"); assertThrowsIllegalArg(() => test.getValueOrElse(null)); assertThrowsIllegalArg(() => test.getValueOrElseApply(null)); assertEquals(test.Failure.Reason, ERROR); assertEquals(test.Failure.Message, "failure"); assertEquals(test.Failure.Items.size(), 1); FailureItem item = test.Failure.Items.GetEnumerator().next(); assertEquals(item.Reason, ERROR); assertEquals(item.Message, "failure"); assertEquals(item.CauseType.get(), ex.GetType()); assertEquals(item.StackTrace, Throwables.getStackTraceAsString(ex).replace(Environment.NewLine, "\n")); }
public void TestCompareEndpointsMethod50316(TestCaseAttribute testCase) { HeaderComment(testCase); ArgumentException ex = new ArgumentException("Unused, just need an instance for GetType() below"); CompareEndpointsHelper(SampleText.Random256, TargetRangeType.DocumentRange, TargetRangeType.DifferentTextPattern, ValueComparison.Equals, ValueComparison.Equals, ValueComparison.Equals, ValueComparison.Equals, ex.GetType()); }
public void PruebaConstructorConLímiteDeVelocidadClaseDeRutaBoolArray() { #region Caso 1: Caso normal. { // Preparación. LímiteDeVelocidad límiteDeVelocidad = new LímiteDeVelocidad(2); ClaseDeRuta claseDeRuta = new ClaseDeRuta(3); bool[] otrosParámetros = new bool[] { true, false, true, false, false, false, true, true, false, true }; // Llama al constructor en prueba. CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(límiteDeVelocidad, claseDeRuta, otrosParámetros); // Prueba Propiedades. Assert.That(objectoEnPrueba.Identificador, Is.EqualTo(CampoParámetrosDeRuta.IdentificadorDeParámetrosDeRuta), "Identificador"); Assert.That(objectoEnPrueba.ClaseDeRuta, Is.EqualTo(claseDeRuta), "ClaseDeRuta"); Assert.That(objectoEnPrueba.LímiteDeVelocidad, Is.EqualTo(límiteDeVelocidad), "LímiteDeVelocidad"); Assert.That(objectoEnPrueba.OtrosParámetros, Is.EqualTo(otrosParámetros), "OtrosParámetros"); } #endregion #region Caso 2: Muy pocos elementos en Otros Parámetros. { // Preparación. LímiteDeVelocidad límiteDeVelocidad = new LímiteDeVelocidad(2); ClaseDeRuta claseDeRuta = new ClaseDeRuta(3); bool[] otrosParámetros = new bool[] { true, true, false, false, false, true, true, false, true }; bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "El números de Otrós Parámetros debe ser 10 pero es 9\r\nParameter name: losOtrosParámetros"); // Llama al constructor en prueba. try { CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(límiteDeVelocidad, claseDeRuta, otrosParámetros); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion #region Caso 3: Muchos elementos en Otros Parámetros. { // Preparación. LímiteDeVelocidad límiteDeVelocidad = new LímiteDeVelocidad(2); ClaseDeRuta claseDeRuta = new ClaseDeRuta(3); bool[] otrosParámetros = new bool[] { true, true, false, true, false, false, false, true, true, false, true }; bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "El números de Otrós Parámetros debe ser 10 pero es 11\r\nParameter name: losOtrosParámetros"); // Llama al constructor en prueba. try { CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(límiteDeVelocidad, claseDeRuta, otrosParámetros); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion }
public void PruebaConstructorConString() { #region Caso 1: Indice en rango válido. { // Preparación. LímiteDeVelocidad límiteDeVelocidad = new LímiteDeVelocidad (2); ClaseDeRuta claseDeRuta = new ClaseDeRuta (3); string parámetrosDeRuta = "2,3,0,1,0,0,0,0,0,0,0,1"; bool[] otrosParámetrosEsperados = new bool[] { false, true, false, false, false, false, false, false, false, true }; // Llama al constructor en prueba. CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parámetrosDeRuta); // Prueba Propiedades. Assert.That(objectoEnPrueba.Identificador, Is.EqualTo(CampoParámetrosDeRuta.IdentificadorDeParámetrosDeRuta), "Identificador"); Assert.That(objectoEnPrueba.ClaseDeRuta, Is.EqualTo(claseDeRuta), "ClaseDeRuta"); Assert.That(objectoEnPrueba.LímiteDeVelocidad, Is.EqualTo(límiteDeVelocidad), "LímiteDeVelocidad"); Assert.That(objectoEnPrueba.OtrosParámetros, Is.EqualTo(otrosParámetrosEsperados), "OtrosParámetros"); } #endregion #region Caso 2: Parametros de Tuta con muy pocos elementos. { // Preparación. string parametrosDeRutaInválidos = "2"; bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "Los parámetros de rutas deben tener 12 elementos separados por coma, pero es: 2"); // Llama al constructor en prueba. try { CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parametrosDeRutaInválidos); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion #region Caso 3: Otros Parámetros con valores diferente de 0 ó 1. { // Preparación. string parametrosDeRutaInválidos = "2,3,0,5,0,0,0,0,0,0,0,1"; bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "El números de los parámetros de ruta para el tercer elemento en adelante tiene que ser 0 ó 1:" + " 2,3,0,5,0,0,0,0,0,0,0,1\r\nParameter name: elTextoDeParámetrosDeRuta"); // Llama al constructor en prueba. try { CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parametrosDeRutaInválidos); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion }
} // CopyRegistryKey private bool ErrorIfDestinationIsSourceOrChildOfSource( string sourcePath, string destinationPath) { s_tracer.WriteLine("destinationPath = {0}", destinationPath); // Note the paths have already been normalized so case-insensitive // comparisons should be sufficient bool result = false; do { // See if the paths are equal if (String.Compare( sourcePath, destinationPath, StringComparison.OrdinalIgnoreCase) == 0) { result = true; break; } string newDestinationPath = GetParentPath(destinationPath, null); if (String.IsNullOrEmpty(newDestinationPath)) { // We reached the root so the destination must not be a child // of the source break; } if (String.Compare( newDestinationPath, destinationPath, StringComparison.OrdinalIgnoreCase) == 0) { // We reached the root so the destination must not be a child // of the source break; } destinationPath = newDestinationPath; } while (true); if (result) { Exception e = new ArgumentException( RegistryProviderStrings.DestinationChildOfSource); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, destinationPath)); } return result; } // ErrorIfDestinationIsSourceOrChildOfSource
private void TS_ThrowTextPatternExceptions() { TextPatternRange returnedRange = null; Point screenLocation = new Point(); ArgumentException aeEx = new ArgumentException("<<Fake argument>>"); ArgumentNullException anEx = new ArgumentNullException("<<Fake null argument>>"); //---------------- // RangeFromPoint //---------------- screenLocation.X = Int32.MaxValue; screenLocation.Y = Int32.MinValue; // ArgumentException – if given point is outside of AutomationElement of the control _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, aeEx.GetType(), CheckType.Verification); //---------------- // RangeFromChild //---------------- // ArgumentNullException – if returnedRange is null _tth.Pattern_RangeFromChild(_pattern, ref returnedRange, null, anEx.GetType(), CheckType.Verification); //// InvalidOperationException – if the child could not have come from this container. // Bug 1199703: Spec bug: RangeFromChild returns incorrect exception when passed an automation element from another container //_tth.Pattern_RangeFromChild(_pattern, ref returnedRange, differentautoElement, ioeEx.GetType(), CheckType.Verification); m_TestStep++; }
private void TS_Coverage_FindText() { Type type = null; ArgumentException aeEx = new ArgumentException("FAKE Argument"); TextPatternRange callingRange = _pattern.DocumentRange; TextPatternRange returnedRange = null; string text = callingRange.GetText(-1); TextTestsHelper.TrimTrailingCRLF(m_le, ref text); if (string.IsNullOrEmpty(text) == true) { type = aeEx.GetType(); } // Empty text _tth.Range_FindText(callingRange, ref returnedRange, "", true, true, aeEx.GetType(), CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "", true, false, aeEx.GetType(), CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "", false, true, aeEx.GetType(), CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "", false, true, aeEx.GetType(), CheckType.Verification); // Non-matching text _tth.Range_FindText(callingRange, ref returnedRange, "ATG", true, true, null, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "ATG", true, false, null, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "ATG", false, true, null, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, "ATG", false, true, null, CheckType.Verification); // Matching Text with matching case text = text.Substring(0, ((text.Length / 2))); _tth.Range_FindText(callingRange, ref returnedRange, text, true, true, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, true, false, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, false, true, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, false, true, type, CheckType.Verification); // Matching Text with mis-matched case text = text.ToUpperInvariant(); _tth.Range_FindText(callingRange, ref returnedRange, text, true, true, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, true, false, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, false, true, type, CheckType.Verification); _tth.Range_FindText(callingRange, ref returnedRange, text, false, true, type, CheckType.Verification); Comment("Called FindText kitchen sink"); m_TestStep++; }
//------------------------------------------------------------------- // Regress Bug //------------------------------------------------------------------- internal void Bug1106920( string bugID, string controls, string bugTitle ) { TextPatternRange range = null; TS_RegressionTest(bugID, controls, bugTitle); try { string actualText = ""; SetText(SampleText.String1, out actualText, CheckType.IncorrectElementConfiguration); range = Pattern_DocumentRange(CheckType.Verification); ArgumentException aeEx = new ArgumentException(); ArgumentNullException aneEx = new ArgumentNullException(); TextPatternRange targetRange = null; Range_FindText( range, ref targetRange, null, false, false, aneEx.GetType(), CheckType.IncorrectElementConfiguration ); Range_FindText( range, ref targetRange, "", false, false, aeEx.GetType(), CheckType.IncorrectElementConfiguration ); Comment("FindText raised correct exceptions"); } catch (Exception ex) { if (IsUIVerifyException(ex)) // Don't interfere with legitimate ThrowMe(...) throw; ThrowMe(CheckType.Verification, "Unexpected exception encountered:\n" + ex.ToString()); } }
protected override PSDriveInfo NewDrive(PSDriveInfo drive) { if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } if (!this.ItemExists(drive.Root)) { Exception exception = new ArgumentException(RegistryProviderStrings.NewDriveRootDoesNotExist); base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, drive.Root)); } return drive; }
} // EscapeChildName /// <summary> /// Renames the key at the specified <paramref name="path"/> to <paramref name="newName"/>. /// </summary> /// /// <param name="path"> /// The path to the key to rename. /// </param> /// /// <param name="newName"> /// The new name of the key. /// </param> protected override void RenameItem( string path, string newName) { if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } if (String.IsNullOrEmpty(newName)) { throw PSTraceSource.NewArgumentException("newName"); } s_tracer.WriteLine("newName = {0}", newName); string parentPath = GetParentPath(path, null); string newPath = MakePath(parentPath, newName); // Make sure we aren't going to overwrite an existing item bool exists = ItemExists(newPath); if (exists) { Exception e = new ArgumentException(RegistryProviderStrings.RenameItemAlreadyExists); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, newPath)); return; } // Confirm the rename item with the user string action = RegistryProviderStrings.RenameItemAction; string resourceTemplate = RegistryProviderStrings.RenameItemResourceTemplate; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path, newPath); if (ShouldProcess(resource, action)) { // Implement rename as a move operation MoveRegistryItem(path, newPath); } // ShouldProcess } // RenameItem
} // WriteRegistryItemObject /// <summary> /// Takes a string and tries to parse it into a RegistryValueKind enum /// type. /// If the conversion fails, WriteError() is called /// </summary> /// /// <param name="type"> /// The type as specified by the user that should be parsed into a RegistryValueKind enum. /// </param> /// /// <param name="kind"> output for the RegistryValueKind for the string</param> /// <returns> /// true if the conversion succeeded /// </returns> private bool ParseKind(string type, out RegistryValueKind kind) { kind = RegistryValueKind.Unknown; if (String.IsNullOrEmpty(type)) { return true; } bool success = true; Exception innerException = null; try { // Convert the parameter to a RegistryValueKind kind = (RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), type, true); } catch (InvalidCastException invalidCast) { innerException = invalidCast; } catch (ArgumentException argException) { innerException = argException; } if (innerException != null) { success = false; string formatString = RegistryProviderStrings.TypeParameterBindingFailure; Exception e = new ArgumentException( string.Format( CultureInfo.CurrentCulture, formatString, type, typeof(RegistryValueKind).FullName), innerException); WriteError(new ErrorRecord( e, e.GetType().FullName, ErrorCategory.InvalidArgument, type)); } return success; } // ParseKind
/// <summary> /// A private helper method that retrieves a RegistryKey for the specified /// path and if an exception is thrown retrieving the key, an error is written /// and null is returned. /// </summary> /// /// <param name="path"> /// The path to the registry key to retrieve. /// </param> /// /// <param name="writeAccess"> /// If write access is required the key then this should be true. If false, /// the key will be opened with read access only. /// </param> /// /// <returns> /// The RegistryKey associated with the specified path. /// </returns> /// private IRegistryWrapper GetRegkeyForPathWriteIfError(string path, bool writeAccess) { IRegistryWrapper result = null; try { result = GetRegkeyForPath(path, writeAccess); if (result == null) { // The key was not found, write out an error. ArgumentException exception = new ArgumentException( RegistryProviderStrings.KeyDoesNotExist); WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); return null; } } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(ioException, ioException.GetType().FullName, ErrorCategory.OpenError, path)); return result; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError(new ErrorRecord(unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return result; } return result; }
} // RemovePropertyValueAt /// <summary> /// Adds a property value on the item specified by the path. /// </summary> /// /// <param name="path"> /// The path to the item on which the property should be added. /// </param> /// /// <param name="at"> /// The position of the property to add. /// </param> /// /// <param name="propertyValue"> /// The property to add the value on. /// </param> /// /// <returns> /// Nothing. A PSObject representing the property and value that was /// added should be passed to the WriteObject() method. /// </returns> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows multivalued properties. /// </remarks> /// public void AddPropertyValueAt( string path, object at, PSObject propertyValue) { if (path == null) { throw tracer.NewArgumentNullException("path"); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } if (propertyValue == null) { throw tracer.NewArgumentNullException("propertyValue"); } // Convert the at parameter to an int int index = GetIndexFromAt(at); IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } string action = RegistryProviderStrings.AddPropertyValueAtAction; string resourceTemplate = RegistryProviderStrings.AddPropertyValueAtResourceTemplate; PSMemberInfoCollection properties = null; try { properties = propertyValue.Properties; } catch (System.IO.IOException ioException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, path)); return; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } foreach (PSMemberInfo property in properties) { object newPropertyValue = property.Value; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path, property.Name, at); if (ShouldProcess(resource, action)) { string propertyNameToSet = GetPropertyName(property.Name); // First get the current value object currentValue = null; try { currentValue = key.GetValue(propertyNameToSet); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.ReadError, property.Name)); continue; } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); continue; } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); continue; } if (currentValue != null && currentValue is string[]) { ArrayList newValueArrayList = new ArrayList((string[])currentValue); if (index == -1 || index >= newValueArrayList.Count) { newValueArrayList.Add(newPropertyValue.ToString()); } else { newValueArrayList.Insert(index, newPropertyValue.ToString()); } currentValue = newValueArrayList.ToArray(typeof(string)); } else if (currentValue != null && currentValue is byte[]) { ArrayList newValueArrayList = new ArrayList((byte[])currentValue); if (index == -1 || index >= newValueArrayList.Count) { newValueArrayList.Add((byte)newPropertyValue); } else { newValueArrayList.Insert(index, (byte)newPropertyValue); } currentValue = newValueArrayList.ToArray(typeof(byte)); } else { Exception e = new ArgumentException ( RegistryProviderStrings.PropertyNotMultivaluedChange); WriteError (new ErrorRecord ( e, e.GetType().FullName, ErrorCategory.InvalidOperation, propertyNameToSet)); continue; } try { key.SetValue(propertyNameToSet, currentValue); // Now write out the value by getting the value from the store object value = key.GetValue(propertyNameToSet); PSObject result = new PSObject(); result.Properties.Add(new PSNoteProperty(property.Name, value)); WritePropertyObject(result, path); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, property.Name)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, property.Name)); } } // if ShouldProcess } } // RemovePropertyValueAt
/// <summary> /// Removes the specified value of a property on the item specified by the path. /// </summary> /// /// <param name="path"> /// The path to the item from which the property value should be removed. /// </param> /// /// <param name="propertyName"> /// The property to remove the value from. /// </param> /// /// <param name="at"> /// The position of the property value to remove. /// </param> /// /// <returns> /// Nothing. A PSObject representing the property and value that was /// removed should be passed to the WriteObject() method. /// </returns> /// /// <remarks> /// Implement this method when you are providing access to a data store /// that allows multivalued properties. /// </remarks> /// public void RemovePropertyValueAt( string path, string propertyName, object at) { if (path == null) { throw tracer.NewArgumentNullException("path"); } if (!CheckOperationNotAllowedOnHiveContainer(path)) { return; } // Convert the at parameter to an int int index = GetIndexFromAt(at); if (index == -1) { // The key was not found, write out an error. ArgumentException exception = new ArgumentException( RegistryProviderStrings.BadAtParam); WriteError (new ErrorRecord (exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); return; } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); if (key == null) { return; } string action = RegistryProviderStrings.RemovePropertyValueAtAction; string resourceTemplate = RegistryProviderStrings.RemovePropertyValueAtResourceTemplate; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path, propertyName, at); if (ShouldProcess(resource, action)) { try { string propertyNameToRemove = GetPropertyName(propertyName); // First get the current value object currentValue = key.GetValue(propertyNameToRemove); if (currentValue != null && currentValue is string[]) { ArrayList newValueArrayList = new ArrayList((string[])currentValue); newValueArrayList.RemoveAt(index); currentValue = newValueArrayList.ToArray(typeof(string)); } else if (currentValue != null && currentValue is byte[]) { ArrayList newValueArrayList = new ArrayList((byte[])currentValue); newValueArrayList.RemoveAt(index); currentValue = newValueArrayList.ToArray(typeof(byte)); } else { Exception e = new ArgumentException ( RegistryProviderStrings.PropertyNotMultivalued); WriteError (new ErrorRecord ( e, e.GetType().FullName, ErrorCategory.InvalidOperation, propertyNameToRemove)); return; } key.SetValue(propertyNameToRemove, currentValue); } catch (System.IO.IOException ioException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (ioException, ioException.GetType().FullName, ErrorCategory.WriteError, propertyName)); } catch (System.Security.SecurityException securityException) { // An exception occurred while trying to set the value. Write // out the error. WriteError (new ErrorRecord (securityException, securityException.GetType().FullName, ErrorCategory.PermissionDenied, propertyName)); } catch (System.UnauthorizedAccessException unauthorizedAccessException) { // An exception occurred while trying to get the key. Write // out the error. WriteError (new ErrorRecord (unauthorizedAccessException, unauthorizedAccessException.GetType().FullName, ErrorCategory.PermissionDenied, propertyName)); } } } // RemovePropertyValueAt
public void TestFindAttributeMethod50513(TestCaseAttribute testCase) { HeaderComment(testCase); ArgumentException ex = new ArgumentException("Unused, just need an instance for GetType() below"); FindAttributeHelper(SampleText.Empty, TypeValue.WrongTypeAndValue, AttributeType.SupportedAttributes, false, FindResults.Exception, ex.GetType()); }
public void TestFindTextMethod50615(TestCaseAttribute testCase) { HeaderComment(testCase); ArgumentException ex = new ArgumentException("Unused, just need an instance for GetType() below"); FindTextHelper(SampleText.Random256, SearchText.Empty, FindResults.Exception, FindResults.Exception, FindResults.Exception, FindResults.Exception, ex.GetType()); }
private bool ParseKind(string type, out RegistryValueKind kind) { kind = RegistryValueKind.Unknown; if (string.IsNullOrEmpty(type)) { return true; } bool flag = true; Exception innerException = null; try { kind = (RegistryValueKind) Enum.Parse(typeof(RegistryValueKind), type, true); } catch (InvalidCastException exception2) { innerException = exception2; } catch (ArgumentException exception3) { innerException = exception3; } if (innerException != null) { flag = false; string typeParameterBindingFailure = RegistryProviderStrings.TypeParameterBindingFailure; Exception exception = new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, typeParameterBindingFailure, new object[] { type, typeof(RegistryValueKind).FullName }), innerException); base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, type)); } tracer.WriteLine("result = {0}", new object[] { (RegistryValueKind) kind }); return flag; }
protected override void RenameItem(string path, string newName) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } if (string.IsNullOrEmpty(newName)) { throw PSTraceSource.NewArgumentException("newName"); } tracer.WriteLine("newName = {0}", new object[] { newName }); string parentPath = this.GetParentPath(path, null); string str2 = this.MakePath(parentPath, newName); if (this.ItemExists(str2)) { Exception exception = new ArgumentException(RegistryProviderStrings.RenameItemAlreadyExists); base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, str2)); } else { string renameItemAction = RegistryProviderStrings.RenameItemAction; string renameItemResourceTemplate = RegistryProviderStrings.RenameItemResourceTemplate; string target = string.Format(base.Host.CurrentCulture, renameItemResourceTemplate, new object[] { path, str2 }); if (base.ShouldProcess(target, renameItemAction)) { this.MoveRegistryItem(path, str2); } } }
private bool ErrorIfDestinationIsSourceOrChildOfSource(string sourcePath, string destinationPath) { tracer.WriteLine("destinationPath = {0}", new object[] { destinationPath }); bool flag = false; Label_001D: if (string.Compare(sourcePath, destinationPath, StringComparison.OrdinalIgnoreCase) == 0) { flag = true; } else { string parentPath = this.GetParentPath(destinationPath, null); if (!string.IsNullOrEmpty(parentPath) && (string.Compare(parentPath, destinationPath, StringComparison.OrdinalIgnoreCase) != 0)) { destinationPath = parentPath; goto Label_001D; } } if (flag) { Exception exception = new ArgumentException(RegistryProviderStrings.DestinationChildOfSource); base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, destinationPath)); } tracer.WriteLine("result = {0}", new object[] { flag }); return flag; }
private void TS_Coverage_RangeFromPoint() { object temp = m_le.GetCurrentPropertyValue( AutomationElement.BoundingRectangleProperty); Rect autoElementRect = (Rect)temp; ; Rect[] boundRects = new Rect[0]; Point screenLocation = new Point(); ArgumentException aeEx = new ArgumentException("bogus argument exception"); TextPatternRange callingRange = _pattern.DocumentRange; TextPatternRange returnedRange = null; _tth.Range_GetBoundingRectangles(callingRange, ref boundRects, null, CheckType.Verification); // Point is center of topLeft corner screenLocation.X = autoElementRect.Left + 1; screenLocation.Y = autoElementRect.Top + 1; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, null, CheckType.Verification); // Point is middle screenLocation.X = (autoElementRect.Left + autoElementRect.Right) / 2; screenLocation.Y = (autoElementRect.Top + autoElementRect.Bottom) / 2; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, null, CheckType.Verification); // Point is inside bottom right screenLocation.X = autoElementRect.Right - 1; screenLocation.Y = autoElementRect.Bottom - 1; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, null, CheckType.Verification); // Point is outside bottom right screenLocation.X = autoElementRect.Right + 1; screenLocation.Y = autoElementRect.Bottom + 1; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, aeEx.GetType(), CheckType.Verification); // Point is outside top left screenLocation.X = autoElementRect.Left - 1; screenLocation.Y = autoElementRect.Top - 1; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, aeEx.GetType(), CheckType.Verification); // Point is outsdie autoElement screenLocation.X = autoElementRect.Left - 1; screenLocation.Y = autoElementRect.Top - 1; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, aeEx.GetType(), CheckType.Verification); // Point is outsdie autoElement screenLocation.X = Int32.MaxValue; screenLocation.Y = Int32.MaxValue; _tth.Pattern_RangeFromPoint(_pattern, ref returnedRange, screenLocation, aeEx.GetType(), CheckType.Verification); m_TestStep++; }
private IRegistryWrapper GetRegkeyForPathWriteIfError(string path, bool writeAccess) { IRegistryWrapper regkeyForPath = null; try { regkeyForPath = this.GetRegkeyForPath(path, writeAccess); if (regkeyForPath == null) { ArgumentException exception = new ArgumentException(RegistryProviderStrings.KeyDoesNotExist); base.WriteError(new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.InvalidArgument, path)); return regkeyForPath; } } catch (ArgumentException exception2) { base.WriteError(new ErrorRecord(exception2, exception2.GetType().FullName, ErrorCategory.OpenError, path)); return regkeyForPath; } catch (IOException exception3) { base.WriteError(new ErrorRecord(exception3, exception3.GetType().FullName, ErrorCategory.OpenError, path)); return regkeyForPath; } catch (SecurityException exception4) { base.WriteError(new ErrorRecord(exception4, exception4.GetType().FullName, ErrorCategory.PermissionDenied, path)); return regkeyForPath; } catch (UnauthorizedAccessException exception5) { base.WriteError(new ErrorRecord(exception5, exception5.GetType().FullName, ErrorCategory.PermissionDenied, path)); return regkeyForPath; } return regkeyForPath; }
private void TS_ThrowTextPatternRangeExceptions() { int results = 0; bool isEqual = false; string text = ""; object nullObject = null; TextPattern differentTextPattern = TextTestsHelper.GetDifferentTextPattern(m_le, CheckType.IncorrectElementConfiguration); TextPatternRange targetRange = null; ArgumentException aeEx = new ArgumentException("<<Fake argument>>"); ArgumentNullException anEx = new ArgumentNullException("<<Fake null argument>>"); TextPatternRange callingRange = null; ArgumentOutOfRangeException aoreEx = new ArgumentOutOfRangeException(); //--------- // Compare //--------- // ArgumentNullException – if the range is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_Compare(callingRange, null, ref isEqual, anEx.GetType(), CheckType.Verification); // ArgumentException – if range is from another container. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_Compare(callingRange, differentTextPattern.DocumentRange, ref isEqual, aeEx.GetType(), CheckType.Verification); //------------------ // CompareEndPoints //------------------ // ArgumentNullException – if the range is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_CompareEndpoints(callingRange, TextPatternRangeEndpoint.Start, null, TextPatternRangeEndpoint.Start, ref results, anEx.GetType(), CheckType.Verification); // ArgumentException – if range is from another container. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_CompareEndpoints(callingRange, TextPatternRangeEndpoint.Start, differentTextPattern.DocumentRange, TextPatternRangeEndpoint.Start, ref results, aeEx.GetType(), CheckType.Verification); //--------------- // FindAttribute //--------------- // ArgumentException – if wrong type is specified. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_FindAttribute(callingRange, ref targetRange, TextPattern.AnimationStyleAttribute, results, true, aeEx.GetType(), CheckType.Verification); // ArgumentNullException – if attribute value is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_FindAttribute(callingRange, ref targetRange, TextPattern.AnimationStyleAttribute, null, true, anEx.GetType(), CheckType.Verification); // ArgumentNullException – if attribute is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_FindAttribute(callingRange, ref targetRange, null, (object)text, true, anEx.GetType(), CheckType.Verification); //---------- // FindText //---------- // ArgumentNullException – if null is applied for search text argument. _tth.Range_FindText( callingRange, ref targetRange, null, true, true, anEx.GetType() , CheckType.Verification ); // ArgumentException –if empty string is applied for search text argument. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_FindText(callingRange, ref targetRange, "", true, true, aeEx.GetType(), CheckType.Verification); //------------------- // GetAttributeValue //------------------- // ArgumentNullException – if attribute is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_GetAttributeValue(callingRange, null, ref nullObject, anEx.GetType(), CheckType.Verification); //--------- // GetText //--------- // Shoduld return ArgumentOutOfRangeException per the spec. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_GetText(callingRange, ref text, Int32.MinValue, aoreEx.GetType(), CheckType.Verification); //--------------------- // MoveEndpointByRange //--------------------- // ArgumentNullException – if targetRange is null. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_MoveEndpointByRange(callingRange, TextPatternRangeEndpoint.Start, null, TextPatternRangeEndpoint.Start, anEx.GetType(), CheckType.Verification); // ArgumentException – if range is from a different container. callingRange = _pattern.DocumentRange.Clone(); _tth.Range_MoveEndpointByRange(callingRange, TextPatternRangeEndpoint.Start, differentTextPattern.DocumentRange, TextPatternRangeEndpoint.Start, aeEx.GetType(), CheckType.Verification); m_TestStep++; }
public void PruebaConstructor() { #region Caso 1: Operación Normal { #region Preparación. // Lee un mapa de prueba. const string archivoDeEntrada = @"..\..\Data\PruebaEscritorFormatoPolish.mp"; IEscuchadorDeEstatus escuchadorDeEstatus = new EscuchadorDeEstatusPorOmisión(); ManejadorDeMapa manejadorDeMapa = new ManejadorDeMapa(escuchadorDeEstatus); LectorDeFormatoPolish lector = new LectorDeFormatoPolish(manejadorDeMapa, archivoDeEntrada); IList<ElementoDelMapa> elementos = lector.ElementosDelMapa; const string archivoDeSalida = @"PruebaEscritorFormatoPolish.Caso1.mp"; #endregion // Llama al constructor. new EscritorDeFormatoPolish(archivoDeSalida, elementos, escuchadorDeEstatus); #region Prueba Archivo de Salida. string[] líneasDeEntrada = LéeArchivo(archivoDeEntrada); string[] líneasDeSalida = LéeArchivo(archivoDeSalida); Assert.That(líneasDeSalida, Is.EqualTo(líneasDeEntrada), "Líneas"); #endregion } #endregion #region Caso 2: Archivo de Salida inválido. { #region Preparación. // Crea elementos. IEscuchadorDeEstatus escuchadorDeEstatus = new EscuchadorDeEstatusPorOmisión(); IList<ElementoDelMapa> elementos = new List<ElementoDelMapa>(); // Archivo inválido. const string archivoDeSalidaInválido = @"ABC::\\&AAAA"; // Excepción esperada. bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "The path is not of a legal form."); #endregion // Llama al constructor en prueba. try { new EscritorDeFormatoPolish(archivoDeSalidaInválido, elementos, escuchadorDeEstatus); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion #region Caso 3: Elemento con Campo Desconocido. { #region Preparación. // Crea elementos. IEscuchadorDeEstatus escuchadorDeEstatus = new EscuchadorDeEstatusPorOmisión(); IList<ElementoDelMapa> elementos = new List<ElementoDelMapa> { new ElementoDesconocido(null, 0, "Clase", new List<Campo> { new CampoDesconocido() })}; const string archivoDeSalida = @"PruebaEscritorFormatoPolish.Caso3.mp"; // Excepción esperada. bool lanzóExcepción = false; ArgumentException excepciónEsperada = new ArgumentException( "Campo desconocido: GpsYv.ManejadorDeMapa.Pruebas.PruebaEscritorFormatoPolish+CampoDesconocido"); #endregion // Llama al constructor en prueba. try { new EscritorDeFormatoPolish(archivoDeSalida, elementos, escuchadorDeEstatus); } catch (Exception e) { // Prueba las propiedades de la excepción. Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción"); Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message"); lanzóExcepción = true; } Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción."); } #endregion }