public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; string testDesc = "PosTest1: Initializes a new instance of FormatException using non-empty message."; string errorDesc; FormatException formatException; string message; message = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(testDesc); try { formatException = new FormatException(message); if(null == formatException || formatException.InnerException != null || !formatException.Message.Contains(message)) { errorDesc = "Failed to initialize instance of FormatException using message \"" + message + "\""; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; string testDesc = "PosTest1: Initializes a new instance of FormatException."; string errorDesc; FormatException formatException; TestLibrary.TestFramework.BeginScenario(testDesc); try { formatException = new FormatException(); if(null == formatException || formatException.InnerException != null) { errorDesc = "Failed to initialize instance of FormatException"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; }
public static void InstantiateException() { int error = 5; string message = "This is an error message."; Exception innerException = new FormatException(); // Test each of the constructors and validate the properties of the resulting instance Win32Exception ex = new Win32Exception(); Assert.Equal(expected: E_FAIL, actual: ex.HResult); ex = new Win32Exception(error); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: error, actual: ex.NativeErrorCode); ex = new Win32Exception(message); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: message, actual: ex.Message); ex = new Win32Exception(error, message); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: error, actual: ex.NativeErrorCode); Assert.Equal(expected: message, actual: ex.Message); ex = new Win32Exception(message, innerException); Assert.Equal(expected: E_FAIL, actual: ex.HResult); Assert.Equal(expected: message, actual: ex.Message); Assert.Same(expected: innerException, actual: ex.InnerException); }
public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); }
public static void Ctor() { string message = "Some Message"; var inner = new FormatException(message); Assert.NotNull(new CryptographicException().Message); Assert.Equal(message, new CryptographicException(message).Message); Assert.Equal(message + " 12345", new CryptographicException(message + " {0}", "12345").Message); Assert.Equal(5, new CryptographicException(5).HResult); Assert.Same(inner, new CryptographicException(message, inner).InnerException); Assert.Equal(message, new CryptographicException(message, inner).Message); }
static void Main() { Console.Write("Enter a number : "); try { int number = int.Parse(Console.ReadLine()); if (number < 0) // check for negative number { FormatException fe = new FormatException(); throw fe; // if it negative throw format exception so it can be catched by next few lines } double squareRoot = Math.Sqrt(number); Console.WriteLine("The square root of the number you entered is : " + squareRoot); } catch (System.FormatException) { Console.WriteLine("Invalid number"); } finally { Console.WriteLine("Good bye"); } }
public RpcResponseFormatException(string message, FormatException innerException) : base(message, innerException) { }
/// <summary> /// Constructs an appropriate FormatException for the given existing exception /// when trying to parse an integer. /// </summary> private FormatException CreateIntegerParseException(FormatException e) { return(CreateFormatException("Couldn't parse integer: " + e.Message)); }
public static void Ctor_Empty() { var exception = new FormatException(); ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_FORMAT, validateMessage: false); }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return(null); } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked ((int)0x800A01C1): case unchecked ((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) { shouldDisplayHR = true; } break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) { shouldDisplayHR = true; } break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) { shouldDisplayHR = true; } break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked ((int)0x800A003E): exception = new System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) { shouldDisplayHR = true; } break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) { shouldDisplayHR = true; } break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked ((int)0x800A793C): case unchecked ((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) { shouldDisplayHR = true; } break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked ((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) { shouldDisplayHR = true; } break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) { shouldDisplayHR = true; } break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) { shouldDisplayHR = true; } break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked ((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked ((int)0x800A01B6): case unchecked ((int)0x800A01BD): case unchecked ((int)0x800A01CA): case unchecked ((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) { shouldDisplayHR = true; } break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked ((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) { shouldDisplayHR = true; } break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked ((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = NotImplemented.ByDesign; break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked ((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) { shouldDisplayHR = true; } break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) { shouldDisplayHR = true; } } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) { shouldDisplayHR = true; } } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) { shouldConstructMessage = true; } } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) { message = hrMessage; } else { message = message + " (" + hrMessage + ")"; } } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } exception.HResult = errorCode; return(exception); }
// Helper methods. private void ParseValue() { int offset = 0; Exception exception = null; try { _mediaType = MailBnfHelper.ReadToken(_type, ref offset, null); if (_mediaType == null || _mediaType.Length == 0 || offset >= _type.Length || _type[offset++] != '/') { exception = new FormatException(SR.ContentTypeInvalid); } if (exception == null) { _subType = MailBnfHelper.ReadToken(_type, ref offset, null); if (_subType == null || _subType.Length == 0) { exception = new FormatException(SR.ContentTypeInvalid); } } if (exception == null) { while (MailBnfHelper.SkipCFWS(_type, ref offset)) { if (_type[offset++] != ';') { exception = new FormatException(SR.ContentTypeInvalid); break; } if (!MailBnfHelper.SkipCFWS(_type, ref offset)) { break; } string paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null); if (paramAttribute == null || paramAttribute.Length == 0) { exception = new FormatException(SR.ContentTypeInvalid); break; } string paramValue; if (offset >= _type.Length || _type[offset++] != '=') { exception = new FormatException(SR.ContentTypeInvalid); break; } if (!MailBnfHelper.SkipCFWS(_type, ref offset)) { exception = new FormatException(SR.ContentTypeInvalid); break; } paramValue = _type[offset] == '"' ? MailBnfHelper.ReadQuotedString(_type, ref offset, null) : MailBnfHelper.ReadToken(_type, ref offset, null); if (paramValue == null) { exception = new FormatException(SR.ContentTypeInvalid); break; } _parameters.Add(paramAttribute, paramValue); } } _parameters.IsChanged = false; } catch (FormatException) { throw new FormatException(SR.ContentTypeInvalid); } if (exception != null) { throw new FormatException(SR.ContentTypeInvalid); } }
private void VisualizarAlocacoesData() { try { if (txtData.Text.Length != 0) { DateTime now = DateTime.Parse(txtData.Text); List<Alocacao> listaAlocacoes = controladorAlocacoes.GetAlocacoesByData(now, (BusinessData.Entities.Calendario)Session["Calendario"]); List<Alocacao> filtradaAtual = new List<Alocacao>(); List<Alocacao> filtradaProx = new List<Alocacao>(); //string horarioAtual = String.Empty; List<string> horarios = new List<string>(); List<TimeSpan> horariosTime = new List<TimeSpan>(); foreach (string hor in Enum.GetNames(typeof(Horarios.HorariosPUCRS))) { horariosTime.Add(Horarios.ParseToDateTime(hor).TimeOfDay); horarios.Add(hor.ToString()); } TimeSpan nowTime = DateTime.Now.TimeOfDay; //nowTime = nowTime.Add(new TimeSpan(2,0,0)); // para testar com outros horarios // Identifica o período de aula atual int pos; if(nowTime < horariosTime[0]) pos = 0; else for(pos = 0; pos < horarios.Count-1; pos++) { if (nowTime >= horariosTime[pos] && nowTime <= horariosTime[pos + 1]) break; } lblAtual.Text = "Horário atual: "+horarios[pos];//+" - "+nowTime.ToString(); string horarioAtual = horarios[pos]; string horarioProx = String.Empty; if(pos < horarios.Count-1) // se nao estivermos ja no ultimo horario... { horarioProx = horarios[pos+1]; lblProximo.Text = "Proximo horario: "+horarioProx; } bool achei = false; foreach(Alocacao aloc in listaAlocacoes) { if(aloc.Horario != horarioAtual && aloc.Horario != horarioProx && achei) // ja achou, ou seja, mudou o horario break; if(aloc.Horario == horarioAtual) { //Alocacao nova = new Alocacao(aloc.Recurso,aloc.Data,aloc.Horario,aloc.Aula,aloc.Evento); //nova.Delta = dif.TotalMinutes.ToString(); filtradaAtual.Add(aloc); achei = true; // indica que ja achou - quando o horario mudar, sai do foreach } if(aloc.Horario == horarioProx) { //Alocacao nova = new Alocacao(aloc.Recurso,aloc.Data,aloc.Horario,aloc.Aula,aloc.Evento); filtradaProx.Add(aloc); achei = true; } } if (filtradaAtual.Count != 0) { dgAlocacoes.DataSource = filtradaAtual; dgAlocacoes.Visible = true; dgAlocacoes.DataBind(); lblStatus.Visible = false; } if(filtradaProx.Count != 0) { dgAlocacoes2.DataSource = filtradaProx; dgAlocacoes2.DataBind(); dgAlocacoes2.Visible = true; lblStatus.Visible = false; } if(filtradaAtual.Count == 0 && filtradaProx.Count == 0) { lblStatus.Text = "Não existem recursos alocados para hoje."; lblStatus.Visible = true; dgAlocacoes.Visible = false; } } else { lblStatus.Visible = true; FormatException excp = new FormatException(); throw excp; } } catch (FormatException) { dgAlocacoes.Visible = false; lblStatus.Text = "Digite uma data válida!"; dgAlocacoes.Visible = false; } }
internal static Exception TryToGuid(string s, out Guid result) { Exception exception = null; result = Guid.Empty; try { result = new Guid(s); } catch (ArgumentException) { exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid")); } catch (FormatException) { exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, "Guid")); } return exception; }
/// <summary> /// Convert a string representation of a FiniteDifference /// </summary> /// <param name="s">A string containing a FiniteDifference to convert</param> /// <exception cref="FormatException">Invalid format of a FiniteDifference</exception> /// <exception cref="OverflowException">The exception is thrown when s contains FiniteDifference /// but can not create FiniteDifference due to too large order or MinimumH</exception> public static FiniteDifference Parse(string s) { FormatException formatException = new FormatException("Input string was not in a correct format"); if (string.IsNullOrWhiteSpace(s)) { return(null); } int order, h; var parts = s.ToLower().Split(new char[] { 'u' }, StringSplitOptions.None); if (parts.Length != 2) { throw formatException; } // parsing order // ************************************************************************************************** string sOrder = parts[0].Trim(); if (string.IsNullOrEmpty(sOrder)) // u(x) { order = 0; } else if (sOrder == "d") // du(x) { order = 1; } else { if (!sOrder.StartsWith("d")) // check for dnu, d^nu { throw formatException; } sOrder = sOrder.Substring(1).TrimStart(); // remove d // now ^n or n if (sOrder.StartsWith("^")) { sOrder = sOrder.Substring(1).TrimStart(); // remove ^ } // parse n order = int.Parse(sOrder); } // parsing argumnet of u // ************************************************************************************************** string sArg = parts[1]; // check if sArg contains two separated numbers because they will be conctatenated after replace(" ", "") int i = 0; // find first number while (i < sArg.Length && !char.IsDigit(sArg[i])) { i++; } // skip first number while (i < sArg.Length && char.IsDigit(sArg[i])) { i++; } // check end of string while (i < sArg.Length) { if (char.IsDigit(sArg[i++])) // if found second number { throw formatException; } } sArg = sArg.Replace(" ", ""); // remove all spaces if (sArg == "(x)") // if h = 0 { h = 0; } else if (!sArg.StartsWith("(x") || !sArg.EndsWith("h)")) // if format error { throw formatException; } else { string arg = sArg.Substring(2, sArg.Length - 4); // remove (x and h) // arg is + or - or +n or -n or +n* or -n* if (arg == "+") { h = 1; } else if (arg == "-") { h = -1; } else // arg is +n or -n or +n* or -n* { if (arg.Length == 0 || (arg[0] != '+' && arg[0] != '-')) // check for (x2*h) { throw formatException; } if (arg.EndsWith("*")) // remove last * { arg = arg.Remove(arg.Length - 1); } // arg is +n or -n // parse n to h h = int.Parse(arg); } } // create FiniteDifference return(GetFiniteDifferenceByOrderAndMinH(order, h)); }
public RouteMatch GetEndPointHandler(RequestContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Request == null) { throw new ArgumentNullException($"{nameof(context)}.{nameof(context.Request)}"); } if (string.IsNullOrWhiteSpace(context.Request.Path)) { throw new ArgumentNullException($"{nameof(context)}.{nameof(context.Request)}.{nameof(context.Request.Path)}"); } string requestPath = context.Request.Path; string[] requestPathSegments = requestPath .Split("/") .Skip(1) .ToArray(); if (requestPathSegments.Length > 0) { string controller = requestPathSegments[0]; if (controller == string.Empty) { //Todo: default e.g.: HomeController } Type controllerType = registeredEndpointHandlerTypes .FirstOrDefault(endPoint => IsRequestedControllerType(controller, endPoint)); if (controllerType == null) { NotFoundException innerException = new NotFoundException( $"Die angeforderte Resource:{controller} konnte nicht gefunden werden."); throw new EndpointHandlerRegisterException( "Error resolving EndpointHandler. See InnerException.", innerException); } string[] actionPathSegments = requestPathSegments .Skip(1) .Where(segment => !string.IsNullOrWhiteSpace(segment)) .ToArray(); try { RouteActionMatch actionMatch = EndpointControllerReflector.SearchRouteActionMatch(actionPathSegments, context.Request.Method, controllerType); return(new RouteMatch(actionMatch, requestPath)); } catch (NotFoundException nfEx) { throw new EndpointHandlerRegisterException($"Die angeforderte Resource:{controllerType} konnte unter dem Pfad:{requestPath} nicht gefunden werden.", nfEx); } } else { FormatException innerException = new FormatException($"Invalid RequestFormat: {context.Request}"); throw new EndpointHandlerRegisterException( "Error resolving EndpointHandler. See InnerException.", innerException); } }
public async override Tasks.Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var exceptionMessage = (string)await v_ExceptionMessage.EvaluateCode(engine); Exception ex; switch (v_ExceptionType) { case "AccessViolationException": ex = new AccessViolationException(exceptionMessage); break; case "ArgumentException": ex = new ArgumentException(exceptionMessage); break; case "ArgumentNullException": ex = new ArgumentNullException(exceptionMessage); break; case "ArgumentOutOfRangeException": ex = new ArgumentOutOfRangeException(exceptionMessage); break; case "DivideByZeroException": ex = new DivideByZeroException(exceptionMessage); break; case "Exception": ex = new Exception(exceptionMessage); break; case "FileNotFoundException": ex = new FileNotFoundException(exceptionMessage); break; case "FormatException": ex = new FormatException(exceptionMessage); break; case "IndexOutOfRangeException": ex = new IndexOutOfRangeException(exceptionMessage); break; case "InvalidDataException": ex = new InvalidDataException(exceptionMessage); break; case "InvalidOperationException": ex = new InvalidOperationException(exceptionMessage); break; case "KeyNotFoundException": ex = new KeyNotFoundException(exceptionMessage); break; case "NotSupportedException": ex = new NotSupportedException(exceptionMessage); break; case "NullReferenceException": ex = new NullReferenceException(exceptionMessage); break; case "OverflowException": ex = new OverflowException(exceptionMessage); break; case "TimeoutException": ex = new TimeoutException(exceptionMessage); break; default: throw new NotImplementedException("Selected exception type " + v_ExceptionType + " is not implemented."); } throw ex; }
/// <summary>Construct an instance.</summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public LexFormatException(string message, FormatException innerException = null) : base(message, innerException) { }
public static void InitilizeUserInfo() { do { Console.Write("Which purpose of your trip? (sea, excursion, shopping, health) : "); try { purposeParameter = Console.ReadLine(); if (!purposeParameter.ToLower().Equals("sea") && !purposeParameter.ToLower().Equals("excursion") && !purposeParameter.ToLower().Equals("shopping") && !purposeParameter.ToLower().Equals("health")) { throw new InvalidUserInputException("Invalid purpose. Try again."); } } catch (InvalidUserInputException e) { Console.WriteLine(e.Message); purposeParameter = null; } }while (purposeParameter == null); do { Console.Write("Which transport you prefer? (plain, bus, train) : "); try { transportParameter = Console.ReadLine(); if (!transportParameter.ToLower().Equals("plain") && !transportParameter.ToLower().Equals("bus") && !transportParameter.ToLower().Equals("train")) { throw new InvalidUserInputException("Invalid transport. Try again."); } } catch (InvalidUserInputException e) { Console.WriteLine(e.Message); transportParameter = null; } }while (transportParameter == null); do { Console.Write("Which food type you prefer? (AI, BC, BB) : "); try { foodTypeParameter = Console.ReadLine(); if (!foodTypeParameter.ToUpper().Equals("AI") && !foodTypeParameter.ToUpper().Equals("BC") && !foodTypeParameter.ToUpper().Equals("BB")) { throw new InvalidUserInputException("Invalid food type. Try again."); } } catch (InvalidUserInputException e) { Console.WriteLine(e.Message); foodTypeParameter = null; } }while (foodTypeParameter == null); do { Console.Write("Enter trip duration : "); try { durationParameter = Convert.ToInt32(Console.ReadLine()); } catch (FormatException e) { e = new FormatException("Duration should be integer value."); Console.WriteLine(e.Message); durationParameter = 0; } }while (durationParameter == 0); }
public void OnInvalidJsonResponse(FormatException exception) { this.Result = new LiveOperationResult(exception, false); }
private void send_Click(object sender, EventArgs e) //send list of shared files to tracker { try { run_program = true; tracker_ip = IPAddress.Parse(textBox1.Text); textBox1.Enabled = false; tracker_port = System.Convert.ToInt32(textBox2.Text); if (tracker_port >= 0 && tracker_port <= 65535) { textBox2.Enabled = false; local_port = System.Convert.ToInt32(textBox6.Text); if (local_port >= 0 && local_port <= 65535) { //make sure port inputs are valid textBox6.Enabled = false; send.Enabled = false; if (dir.Enabled == false) { down.Enabled = true; } Tracker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Tracker.Connect(tracker_ip, tracker_port); local_ip = ((IPEndPoint)Tracker.LocalEndPoint).Address; outbox.AppendText("FileSharerDownloader (IP: " + local_ip.ToString() + ") connected to Tracker (IP: " + tracker_ip.ToString() + ") on port " + tracker_port + "\n"); byte[] code = new byte[1]; code[0] = 100; //inform tracker that this is the first connection to tracker to send shared file names Tracker.Send(code); byte[] many = new byte[4]; many = BitConverter.GetBytes(file_list.Length); Tracker.Send(many); byte[] portN = new byte[4]; portN = BitConverter.GetBytes(local_port); //byte representation Tracker.Send(portN); for (int i = 0; i < file_list.Length; i++) { byte[] file_name_size = new byte[1]; //a file name can be max 256 chars on NTFS, hence 1 byte is enough to state the number of bytes file_name_size[0] = (BitConverter.GetBytes(file_names[i].Length))[0]; Tracker.Send(file_name_size); Tracker.Send(Encoding.Default.GetBytes(file_names[i])); byte[] file_size = new byte[8]; file_size = BitConverter.GetBytes(finfo[i].Length); //byte representation Tracker.Send(file_size); } //all names and sizes are sent outbox.AppendText("List of shared files is sent to Tracker (IP: " + tracker_ip.ToString() + ")\n"); text = new Mutex(); //initialize listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(new IPEndPoint(IPAddress.Any, local_port)); listener.Listen(50); //start listening text.WaitOne(); outbox.AppendText("Started listening on port " + local_port + "\n"); text.ReleaseMutex(); text.WaitOne(); outbox.AppendText("Listening port is sent to Tracker (IP: " + tracker_ip.ToString() + ")\n"); text.ReleaseMutex(); Tracker.Close(); text.WaitOne(); outbox.AppendText("Connection to Tracker (IP: " + tracker_ip.ToString() + ") is closed\n"); text.ReleaseMutex(); inc_files = new List <byte[]>(); // get_files = new List <List <ThreadStart> >(); // get_file = new List <List <Thread> >(); // search_list = new List <string>(); // part_sends = new List <ThreadStart>(); // initializations part_send = new List <Thread>(); // requests = new List <ThreadStart>(); // request = new List <Thread>(); // inc_connections = new List <Socket>(); // inits = new List <ThreadStart>(); init = new List <Thread>(); listens = delegate { thr_lis_acc(); }; listen = new Thread(listens); listen.Start(); //start a thread to accept connecitons } else { FormatException wrong_format = new FormatException("The local port number needs to be between 0 and 65535."); throw wrong_format; } } else { FormatException wrong_format = new FormatException("The tracker port number needs to be between 0 and 65535."); throw wrong_format; } } catch (ArgumentNullException argnullex) { outbox.AppendText(argnullex + "\n" + "Please write an IP Address for Tracker.\n"); } catch (FormatException formatex) { if (textBox1.Enabled == false) { outbox.AppendText(formatex + "\n" + "Please write a valid (integer) port number between 0 and 65535.\n"); } else { outbox.AppendText(formatex + "\n" + "Please write a valid (like a.b.c.d) IP Address for Tracker, where a, b, c and d are integers between 0 and 255.\n"); } } }
public void Parse_Invalid_ThrowsFormatException(string address) { FormatException ex = Assert.Throws <FormatException>(() => PhysicalAddress.Parse(address)); Assert.Contains(address, ex.Message); }
/// <summary> /// This method should be called after the object is created. /// </summary> /// <param name="dirs"> /// collection of strings (directory names) /// for each directory in this collection, its sub-directories /// are scanned for plugin.xml /// </param> public void init(ICollection dirs, ProgressHandler progressHandler, PluginErrorHandler errorHandler) { Set pluginSet = new Set(); Hashtable errorPlugins = new Hashtable(); int errCount = 0; int count = 0; float c_max = dirs.Count * 4; bool errBreak = false; if (errorHandler == null) { errorHandler = new SilentPluginErrorHandler(); } // locate plugins foreach (string dir in dirs) { progressHandler("Searching for plugins...\n" + Path.GetFileName(dir), ++count / c_max); //! progressHandler("プラグインを検索中\n"+Path.GetFileName(dir),++count/c_max); if (!File.Exists(Path.Combine(dir, "plugin.xml"))) { continue; // this directory doesn't have the plugin.xml file. } Plugin p = null; try { p = new Plugin(dir); p.loadContributionFactories(); } catch (Exception e) { errCount++; p = Plugin.loadFailSafe(dir); errorPlugins.Add(p, e); errBreak = errorHandler.OnPluginLoadError(p, e); if (errBreak) { break; } else { continue; } } if (pluginMap.Contains(p.name)) { errCount++; // loaded more than once Exception e = new Exception(string.Format( "Plugin \"{0}\" is loaded from more than one place ({1} and {2})", //! "プラグイン「{0}」は{1}と{2}の二箇所からロードされています", p.name, p.dirName, ((Plugin)pluginMap[p.name]).dirName)); errBreak = errorHandler.OnNameDuplicated(pluginMap[p.name] as Plugin, p, e); errorPlugins.Add(p, e); if (errBreak) { break; } else { continue; } } pluginMap.Add(p.name, p); pluginSet.add(p); } if (errBreak) { Environment.Exit(-1); } { // convert it to an array by sorting them in the order of dependency this.plugins = new Plugin[pluginSet.count]; int ptr = 0; Plugin p = null; while (!pluginSet.isEmpty) { progressHandler("Sorting dependencies...", ++count / c_max); //! progressHandler("依存関係を整理中",++count/c_max); p = (Plugin)pluginSet.getOne(); try { while (true) { Plugin[] deps = p.getDependencies(); int i; for (i = 0; i < deps.Length; i++) { if (pluginSet.contains(deps[i])) { break; } } if (i == deps.Length) { break; } else { p = deps[i]; } } } catch (Exception e) { errCount++; errBreak = errorHandler.OnPluginLoadError(p, e); if (!errorPlugins.ContainsKey(p)) { errorPlugins.Add(p, e); } if (errBreak) { break; } } pluginSet.remove(p); plugins[ptr++] = p; } } if (errBreak) { Environment.Exit(-2); } // load all the contributions foreach (Plugin p in plugins) { progressHandler("Loading contributions...\n" + Path.GetFileName(p.dirName), ++count / c_max); //! progressHandler("コントリビューションをロード中\n"+Path.GetFileName(p.dirName),++count/c_max); try { p.loadContributions(); } catch (Exception e) { errCount++; errBreak = errorHandler.OnPluginLoadError(p, e); if (!errorPlugins.ContainsKey(p)) { errorPlugins.Add(p, e); } if (errBreak) { break; } } } if (errBreak) { Environment.Exit(-3); } // initialize contributions count = (int)c_max; c_max += publicContributions.Length; foreach (Contribution contrib in publicContributions) { progressHandler("Initializing contributions...\n" + contrib.baseUri, ++count / c_max); //! progressHandler("コントリビューションを初期化中\n"+contrib.baseUri,++count/c_max); try { contrib.onInitComplete(); } catch (Exception e) { errCount++; errBreak = errorHandler.OnContributionInitError(contrib, e); Plugin p = contrib.parent; if (!errorPlugins.ContainsKey(p)) { errorPlugins.Add(p, e); } if (errBreak) { break; } } } if (errBreak) { Environment.Exit(-4); } { // make sure there's no duplicate id progressHandler("Checking for duplicate IDs...", 1.0f); //! progressHandler("重複IDのチェック中",1.0f); IDictionary dic = new Hashtable(); foreach (Contribution contrib in publicContributions) { if (dic[contrib.id] != null) { errCount++; Exception e = new FormatException("ID:" + contrib.id + " is not unique"); //! Exception e = new FormatException("ID:"+contrib.id+"が一意ではありません"); errBreak = errorHandler.OnContribIDDuplicated(dic[contrib.id] as Contribution, contrib, e); Plugin p = contrib.parent; if (!errorPlugins.ContainsKey(p)) { errorPlugins.Add(p, e); } if (errBreak) { break; } } else { dic[contrib.id] = contrib; } } } if (errBreak) { Environment.Exit(-5); } if (errCount > 0) { if (errorHandler.OnFinal(errorPlugins, errCount)) { Environment.Exit(errCount); } } }
public async Task Complete_WithException_PropagatesToCompletion() { IChannel<int> c = CreateChannel(); FormatException exc = new FormatException(); c.Complete(exc); Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Completion)); }
private void VisualizarAlocacoesData() { try { if (txtData.Text.Length != 0) { List<Alocacao> listaAlocacoes = controladorAlocacoes.GetAlocacoesByData(DateTime.Parse(txtData.Text), (BusinessData.Entities.Calendario)Session["Calendario"]); if (listaAlocacoes.Count != 0) { dgAlocacoes.DataSource = listaAlocacoes; dgAlocacoes.Visible = true; dgAlocacoes.DataBind(); lblStatus.Visible = false; } else { lblStatus.Text = "Não existem recursos alocados na data informada."; lblStatus.Visible = true; dgAlocacoes.Visible = false; } } else { lblStatus.Visible = true; FormatException excp = new FormatException(); throw excp; } } catch (FormatException) { dgAlocacoes.Visible = false; lblStatus.Text = "Digite uma data válida!"; dgAlocacoes.Visible = false; } }
static string GetArgument(StringBuilder builder, string buf, int startIndex, out int endIndex, out Exception ex) { bool escaped = false; char qchar, c = '\0'; int i = startIndex; builder.Clear(); switch (buf[startIndex]) { case '\'': qchar = '\''; i++; break; case '"': qchar = '"'; i++; break; default: qchar = '\0'; break; } while (i < buf.Length) { c = buf[i]; if (c == qchar && !escaped) { // unescaped qchar means we've reached the end of the argument i++; break; } if (c == '\\') { escaped = true; } else if (escaped) { builder.Append(c); escaped = false; } else if (qchar == '\0' && (c == ' ' || c == '\t')) { break; } else if (qchar == '\0' && (c == '\'' || c == '"')) { string sofar = builder.ToString(); string embedded; if ((embedded = GetArgument(builder, buf, i, out endIndex, out ex)) == null) { return(null); } i = endIndex; builder.Clear(); builder.Append(sofar); builder.Append(embedded); continue; } else { builder.Append(c); } i++; } if (escaped || (qchar != '\0' && c != qchar)) { ex = new FormatException(escaped ? "Incomplete escape sequence." : "No matching quote found."); endIndex = -1; return(null); } endIndex = i; ex = null; return(builder.ToString()); }
public DayOutOfRangeException(string message, FormatException inner) : base(message, inner) { }
public async Task Complete_WithException_PropagatesToNewReader() { IChannel<int> c = CreateChannel(); FormatException exc = new FormatException(); c.Complete(exc); Task<int> read = c.ReadAsync().AsTask(); Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => read)); }
private Collection <AliasInfo> GetAliasesFromFile(bool isLiteralPath) { Collection <AliasInfo> result = new Collection <AliasInfo>(); string filePath = null; using (StreamReader reader = OpenFile(out filePath, isLiteralPath)) { CSVHelper csvHelper = new CSVHelper(','); Int64 lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { ++lineNumber; // Ignore blank lines if (line.Length == 0) { continue; } // Ignore lines that only contain whitespace if (OnlyContainsWhitespace(line)) { continue; } // Ignore comment lines if (line[0] == '#') { continue; } Collection <string> values = csvHelper.ParseCsv(line); if (values.Count != 4) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber); FormatException formatException = new FormatException(message); ErrorRecord errorRecord = new ErrorRecord( formatException, "ImportAliasFileFormatError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); ThrowTerminatingError(errorRecord); } ScopedItemOptions options = ScopedItemOptions.None; try { options = (ScopedItemOptions)Enum.Parse(typeof(ScopedItemOptions), values[3], true); } catch (ArgumentException argException) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber); ErrorRecord errorRecord = new ErrorRecord( argException, "ImportAliasOptionsError", ErrorCategory.ReadError, filePath); errorRecord.ErrorDetails = new ErrorDetails(message); WriteError(errorRecord); continue; } AliasInfo newAlias = new AliasInfo( values[0], values[1], Context, options); if (!String.IsNullOrEmpty(values[2])) { newAlias.Description = values[2]; } result.Add(newAlias); } reader.Dispose(); } return(result); }
public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; string testDesc = "PosTest3: Initializes a new instance of FormatException using string.Empty."; string errorDesc; FormatException formatException; Exception innerException; innerException = new Exception(); TestLibrary.TestFramework.BeginScenario(testDesc); try { formatException = new FormatException(string.Empty, innerException); if (null == formatException || formatException.InnerException != innerException) { errorDesc = "Failed to initialize instance of FormatException using null reference." + "\n Inner exception: " + innerException; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; }
/// <summary> /// Parses the specified path and returns the portion determined by the /// boolean parameters. /// </summary> protected override void ProcessRecord() { StringCollection pathsToParse = new StringCollection(); if (Resolve) { CmdletProviderContext currentContext = CmdletProviderContext; foreach (string path in Path) { // resolve the paths and then parse each one. Collection <PathInfo> resolvedPaths; try { resolvedPaths = SessionState.Path.GetResolvedPSPathFromPSPath(path, currentContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } foreach (PathInfo resolvedPath in resolvedPaths) { try { if (InvokeProvider.Item.Exists(resolvedPath.Path, currentContext)) { pathsToParse.Add(resolvedPath.Path); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } } else { pathsToParse.AddRange(Path); } // Now parse each path for (int index = 0; index < pathsToParse.Count; ++index) { string result = null; switch (ParameterSetName) { case isAbsoluteSet: string ignored; bool isPathAbsolute = SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored); WriteObject(isPathAbsolute); continue; case qualifierSet: int separatorIndex = pathsToParse[index].IndexOf(":", StringComparison.CurrentCulture); if (separatorIndex < 0) { FormatException e = new FormatException( StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); WriteError( new ErrorRecord( e, "ParsePathFormatError", // RENAME ErrorCategory.InvalidArgument, pathsToParse[index])); continue; } else { // Check to see if it is provider or drive qualified if (SessionState.Path.IsProviderQualified(pathsToParse[index])) { // The plus 2 is for the length of the provider separator // which is "::" result = pathsToParse[index].Substring( 0, separatorIndex + 2); } else { result = pathsToParse[index].Substring( 0, separatorIndex + 1); } } break; case parentSet: case literalPathSet: try { result = SessionState.Path.ParseParent( pathsToParse[index], String.Empty, CmdletProviderContext, true); } catch (PSNotSupportedException) { // Since getting the parent path is not supported, // the provider must be a container, item, or drive // provider. Since the paths for these types of // providers can't be split, asking for the parent // is asking for an empty string. result = String.Empty; } break; case leafSet: case leafBaseSet: case extensionSet: try { // default handles leafSet result = SessionState.Path.ParseChildName( pathsToParse[index], CmdletProviderContext, true); if (LeafBase) { result = System.IO.Path.GetFileNameWithoutExtension(result); } else if (Extension) { result = System.IO.Path.GetExtension(result); } } catch (PSNotSupportedException) { // Since getting the leaf part of a path is not supported, // the provider must be a container, item, or drive // provider. Since the paths for these types of // providers can't be split, asking for the leaf // is asking for the specified path back. result = pathsToParse[index]; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } break; case noQualifierSet: result = RemoveQualifier(pathsToParse[index]); break; default: Dbg.Diagnostics.Assert( false, "Only a known parameter set should be called"); break; } // switch if (result != null) { WriteObject(result); } } // for each path } // ProcessRecord
static internal Exception ParameterConversionFailed(object value, Type destType, Exception inner) { Debug.Assert(null != value, "null value on conversion failure"); Debug.Assert(null != inner, "null inner on conversion failure"); Exception e; string message = Res.GetString(Res.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name); if (inner is ArgumentException) { e = new ArgumentException(message, inner); } else if (inner is FormatException) { e = new FormatException(message, inner); } else if (inner is InvalidCastException) { e = new InvalidCastException(message, inner); } else if (inner is OverflowException) { e = new OverflowException(message, inner); } else { e = inner; } return e; }
public LocalStoreCorruptFileStreamEvent(string path, FormatException exception) { this.exception = exception; this.Path = path; }
/// <summary> /// Convert string to int. Get exception if it impossible. /// </summary> /// <param name="convert"></param> /// <returns></returns> public int ConvertToInt(string convert) { if (!IsPossibleStringToInt(convert)) { FormatException formatException = new FormatException(); } int result = 0; int coeff = 1; StringBuilder toIntStringBuilder = new StringBuilder(convert); if (toIntStringBuilder[0] == ASCIICodeOfMinus) { coeff = -1; toIntStringBuilder.Remove(0, 1); } // delete zeros on string start for (int i = 0; i < toIntStringBuilder.Length - 1; i++) { if (toIntStringBuilder[i] == '0' && toIntStringBuilder[i + 1] == '0') { toIntStringBuilder.Remove(i, 1); i--; } else if (toIntStringBuilder[i] == '0' && toIntStringBuilder[i + 1] != '0') { toIntStringBuilder.Remove(i, 1); break; } else { break; } } // check position of commas if (convert.Contains(ASCIICodeOfComma.ToString()) && convert.Contains(ASCIICodeOfPoint.ToString()) && convert.LastIndexOf(ASCIICodeOfComma.ToString()) > convert.LastIndexOf(ASCIICodeOfPoint.ToString())) { if (toIntStringBuilder.ToString().LastIndexOf((char)ASCIICodeOfComma) != toIntStringBuilder.ToString().Length - 1) { for (int i = toIntStringBuilder.ToString().LastIndexOf((char)ASCIICodeOfComma); i < toIntStringBuilder.ToString().Length; i++) { if (toIntStringBuilder[i] == '0') { toIntStringBuilder.Remove(i, 0); i--; } } } } // check position of commas if (convert.Contains(ASCIICodeOfComma.ToString()) && convert.Contains(ASCIICodeOfPoint.ToString()) && convert.LastIndexOf(ASCIICodeOfComma.ToString()) < convert.LastIndexOf(ASCIICodeOfPoint.ToString())) { if (toIntStringBuilder.ToString().LastIndexOf((char)ASCIICodeOfPoint) != toIntStringBuilder.ToString().Length - 1) { for (int i = toIntStringBuilder.ToString().LastIndexOf((char)ASCIICodeOfPoint); i < toIntStringBuilder.ToString().Length; i++) { if (toIntStringBuilder[i] == '0') { toIntStringBuilder.Remove(i, 0); i--; } } } } if (toIntStringBuilder[toIntStringBuilder.Length - 1] == '.' || toIntStringBuilder[toIntStringBuilder.Length - 1] == ',') { toIntStringBuilder.Remove(toIntStringBuilder.Length - 1, 1); } if (toIntStringBuilder.ToString().Contains('.') && toIntStringBuilder.ToString().Contains(',')) { throw new FormatException("Int can not contain so mutch points and commas simultaneously."); } // removing all commas if exist if (toIntStringBuilder.ToString().Contains(',')) { for (int i = 0; i <= (toIntStringBuilder.Length - 1) / 3; i++) { if (toIntStringBuilder[toIntStringBuilder.Length - 1 - i * 3] == ',') { toIntStringBuilder.Remove(toIntStringBuilder.Length - 1 - i * 3, 1); } } } // removing all points if exist if (toIntStringBuilder.ToString().Contains('.')) { for (int i = 0; i <= (toIntStringBuilder.Length - 1) / 3; i++) { if (toIntStringBuilder[toIntStringBuilder.Length - 1 - i * 3] == '.') { toIntStringBuilder.Remove(toIntStringBuilder.Length - 1 - i * 3, 1); } } } if (toIntStringBuilder.ToString().Contains('.') && toIntStringBuilder.ToString().Contains(',')) { throw new FormatException("Int can not contain so mutch points and commas simultaneously."); } for (int i = toIntStringBuilder.Length - 1; i >= 0; i--) { result += (toIntStringBuilder[i] - 48) * (int)Math.Pow(10, (toIntStringBuilder.Length - 1 - i)); Console.WriteLine("toIntStringBuilder[i]={0}.(toIntStringBuilder.Length - 1 - i)={1}.", toIntStringBuilder[i], (int)Math.Pow(10, (toIntStringBuilder.Length - 1 - i))); } return(result * coeff); }
private static bool TryParse(string s, out ExternalRef externalRef, out Exception error) { externalRef = null; if (String.IsNullOrEmpty(s)) { error = new ArgumentNullException("s"); return(false); } var typeName = s; string assemblyName = null; if (s[0] == '[') { var delim2 = s.IndexOf(']'); if (delim2 == -1) { error = new FormatException("The external ref is invalid."); return(false); } assemblyName = s.Substring(1, delim2 - 1); typeName = s.Substring(delim2 + 1); } var delim = typeName.LastIndexOf('.'); if (delim == -1) { error = new FormatException("The input type is invalid."); return(false); } var methodName = typeName.Substring(delim + 1); typeName = typeName.Substring(0, delim); var parenDelim1 = methodName.IndexOf('('); if (parenDelim1 == -1) { error = new FormatException("Method open parenthesis not found."); return(false); } var parenDelim2 = methodName.IndexOf(')'); if (parenDelim2 == -1) { error = new FormatException("Method close parenthesis not found."); return(false); } var argString = methodName.Substring(parenDelim1 + 1, (parenDelim2 - parenDelim1) - 1); methodName = methodName.Substring(0, parenDelim1); var args = new List <string>(); if (!String.IsNullOrEmpty(argString)) { var sp = argString.Split(','); for (int i = 0; i < sp.Length; i++) { var arg = sp[i].Trim(); if (String.IsNullOrEmpty(arg)) { error = new FormatException("One of the arguments is invalid."); return(false); } args.Add(arg); } } externalRef = new ExternalRef(assemblyName, typeName, methodName, args.ToArray()); error = null; return(true); }