public void ConstructorWithMessageAndInnerExceptionWorks() { var inner = new Exception("a"); var ex = new FormatException("The message", inner); Assert.IsTrue((object)ex is FormatException, "is FormatException"); Assert.IsTrue(ReferenceEquals(ex.InnerException, inner), "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
private static void ThrowInformativeException(string when, string[] formats, FormatException e) { var builder = new StringBuilder(); builder.AppendFormat("One of the date fields contained a date/time format which could not be parsed ({0})." + Environment.NewLine, when); builder.Append("This program can parse the following formats: "); foreach (var format in formats) { builder.Append(format + Environment.NewLine); } builder.Append("See: http://en.wikipedia.org/wiki/ISO_8601 for an explanation of these symbols."); throw new ApplicationException(builder.ToString(), e); }
public override string ToString() { int unusedSpace = capacity - count; if (newArray[0].GetType().IsArray) { System.FormatException listTypeIsArray = new System.FormatException("Cannot implicitly convert array to string"); throw listTypeIsArray; } try { StringBuilder BobTheBuilder = new StringBuilder(); for (int i = 0; i < count; i++) { BobTheBuilder.Append(newArray[i]).Append(","); } string newString = BobTheBuilder.ToString().Remove(BobTheBuilder.Length - 1, 1); return(newString); } catch { System.FormatException emptyArray = new System.FormatException("Cannot convert empty list to string"); throw emptyArray; } }
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var stringValue = value as string; if (stringValue != null) { var input = stringValue.Trim(); if (string.IsNullOrEmpty(input)) { return value; } // Try to parse. Use the invariant culture instead of the current one. TimeSpan timeSpan; if (TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out timeSpan)) { return value; } var exception = new FormatException(string.Format(CultureInfo.CurrentCulture, Resources.TimeSpanConverter_InvalidString, stringValue)); throw exception; } return base.ConvertFrom(context, culture, value); }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(FormatException).GetClassName(), "Bridge.FormatException", "Name"); object d = new FormatException(); Assert.True(d is FormatException, "is FormatException"); Assert.True(d is Exception, "is Exception"); }
public void ConstructorWithMessageWorks() { var ex = new FormatException("The message"); Assert.True((object)ex is FormatException, "is FormatException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "The message"); }
internal static string AddParameter (string baseUrl, string parameter, string value) { // this will get our url's properly formatted if (parameter == Constants.UrlParameter.Url) { try { value = new Uri (value).ToString(); } catch (System.FormatException e) //UriFormatException is not supported in the portable libraries { FormatException ufe = new FormatException("Delicious.Net was unable to parse the url \"" + value + "\".\n\n" + e); throw (ufe); } } value = Uri.EscapeDataString(value); //HttpUtility.UrlEncode is not supported in the portable libraries // insert the '?' if needed int qLocation = baseUrl.LastIndexOf ('?'); if (qLocation < 0) { baseUrl += "?"; qLocation = baseUrl.Length - 1; } if (baseUrl.Length > qLocation + 1) baseUrl += "&"; baseUrl += parameter + "=" + value; return baseUrl; }
protected Boolean PinCorrect() { try { string deptname = Session["DepartmentName"].ToString(); int EnteredPin = Convert.ToInt32(PinTextBox.Text); int ActualPin = BusinessLogic.GetDepartmentPin(deptname); if (EnteredPin == ActualPin) { Session["Pin"] = true; AcknowledgeButton.Enabled = true; AcknowledgeButton.BackColor = Color.Green; return(true); } else { Session["Pin"] = false; AcknowledgeButton.Enabled = false; AcknowledgeButton.BackColor = Color.Red; } } catch (FormatException e) { System.FormatException ex = e; //Response.Write("\nPin has to be numeric"); return(false); } catch (Exception e) { Response.Write("\nError occured : " + e); } return(false); }
public void TestWhenAny1_Canceled1_Faulted1() { Exception expectedException = new FormatException(); Action<Task> exceptionSelector = task => { throw expectedException; }; IEnumerable<Task> tasks = new[] { DelayedTask.Delay(TimeSpan.FromMilliseconds(1 * TimingGranularity.TotalMilliseconds)).Then(_ => CompletedTask.Canceled()), DelayedTask.Delay(TimeSpan.FromMilliseconds(3 * TimingGranularity.TotalMilliseconds)).Select(exceptionSelector).ObserveExceptions() }; Task<Task> delayed = DelayedTask.WhenAny(tasks); Assert.IsFalse(delayed.IsCompleted); delayed.Wait(); Assert.IsTrue(delayed.IsCompleted); Assert.AreEqual(TaskStatus.RanToCompletion, delayed.Status); Assert.IsNotNull(delayed.Result); Assert.IsTrue(tasks.Contains(delayed.Result)); // this one was the first to complete Assert.IsTrue(delayed.Result.IsCompleted); Assert.IsTrue(delayed.Result.IsCanceled); Assert.AreEqual(TaskStatus.Canceled, delayed.Result.Status); }
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 DefaultConstructorWorks() { var ex = new FormatException(); Assert.True((object)ex is FormatException, "is FormatException"); Assert.AreEqual(ex.InnerException, null, "InnerException"); Assert.AreEqual(ex.Message, "Invalid format."); }
internal static void DisplayException(FormatException exception) { var title = "Format exception"; StringBuilder content = new StringBuilder(); content.AppendLine("There is a problem with the format of the message:"); content.AppendFormat("Exception: {0}\n\n", exception.Message); MessageDialogHelper.ShowDialogAsync(content.ToString(), title); }
public void InvariantWithLambdaMessageAndInnerThrowsCorrectly() { FormatException inner = new FormatException(); Assert.That(() => Check.Invariant(-1, i => i > 0, InvariantMessage, inner), Throws.TypeOf<InvariantException>() .With.Message.ContainsSubstring(InvariantMessage) .And.Property("InnerException").EqualTo(inner)); }
public void AssertionWithMessageAndInnerThrowsCorrectly() { FormatException inner = new FormatException(); Assert.That(() => Check.Assert(false, AssertionMessage, inner), Throws.TypeOf<AssertionException>() .With.Message.ContainsSubstring(AssertionMessage) .And.Property("InnerException").EqualTo(inner)); }
public void PostconditionWithLambdaMessageAndInnerThrowsCorrectly() { FormatException inner = new FormatException(); Assert.That(() => Check.Ensure(-1, i => i > 0, PostconditionMessage, inner), Throws.TypeOf<PostconditionException>() .With.Message.ContainsSubstring(PostconditionMessage) .And.Property("InnerException").EqualTo(inner)); }
public static void InputNotANumberLog(FormatException e) { List<string> log = new List<string>(); log.Add("InputNotANumberError"); log.Add("Fehlermeldung: " + e.Message); log.Add("Fehler bei der Auswahl des Songs."); log.Add("Fehlerbehebung: Programm mit Song erneut starten, nur 1, 2 oder 3 eingeben."); Errorlogs.PrintLogs(log); }
//adds movie to want movie list private void Add_Movie_Click(object sender, RoutedEventArgs e) { WantMovie movie = new WantMovie(); bool worked = true; try { if (Title_Textbox.Text == "") { System.FormatException fEx = new System.FormatException(); throw fEx; } movie.Title = Title_Textbox.Text; } catch (FormatException) { Title_Textbox.BorderBrush = Brushes.Red; worked = false; } ComboBoxItem cbi = (ComboBoxItem)GenreComboBox.SelectedItem; movie.Genre = cbi.Content.ToString(); if (worked == true) { wantMovieList.Add(movie); Title_Textbox.BorderBrush = SystemColors.ControlDarkBrush; Title_Textbox.Text = ""; GenreComboBox.Text = "Genre"; setModifiedState(); int skip = 0; SkipList1.Clear(); MoviesListView.Items.Clear(); foreach (WantMovie movie1 in wantMovieList) { try { if (movie.Title.ToUpper().Contains(Search1.Text.ToUpper()) || Search1.Text == "") { MoviesListView.Items.Add(new WantMovie { Title = movie1.Title, Genre = movie1.Genre, DateAdded = movie1.DateAdded }); SkipList1.Add(skip); } else { skip++; } } catch { } } CheckSort(); } }
//edit click, edits watched movie information based on new information private void Edit_Click2(object sender, RoutedEventArgs e) { int index = MoviesListView2.SelectedIndex; index = trySkipList2(index); bool worked = true; try { if (Title_Textbox2.Text == "") { System.FormatException fEx = new System.FormatException(); throw fEx; } watchedMovieList[index].Title = Title_Textbox2.Text; } catch (FormatException) { Title_Textbox.BorderBrush = Brushes.Red; worked = false; } try { double rating = double.Parse(Rating.Text); if (rating < 0 || rating > 10) { System.FormatException fEx = new System.FormatException(); throw fEx; } watchedMovieList[index].Rating = rating; } catch (FormatException) { Rating.BorderBrush = Brushes.Red; worked = false; } ComboBoxItem cbi = (ComboBoxItem)GenreComboBox2.SelectedItem; watchedMovieList[index].Genre = cbi.Content.ToString(); if (worked == true) { Title_Textbox.BorderBrush = SystemColors.ControlDarkBrush; Rating.BorderBrush = SystemColors.ControlDarkBrush; Title_Textbox2.Text = ""; Rating.Text = ""; GenreComboBox.Text = "Genre"; printWatchedMovieList(); setModifiedState(); DisableButtons2(); } }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(FormatException).FullName, "ss.FormatException", "Name"); Assert.IsTrue(typeof(FormatException).IsClass, "IsClass"); Assert.AreEqual(typeof(FormatException).BaseType, typeof(Exception), "BaseType"); object d = new FormatException(); Assert.IsTrue(d is FormatException, "is FormatException"); Assert.IsTrue(d is Exception, "is Exception"); var interfaces = typeof(FormatException).GetInterfaces(); Assert.AreEqual(interfaces.Length, 0, "Interfaces length"); }
public void ShouldFindTheSpecifiedException() { var formatException = new FormatException(); var argumentNullException = new ArgumentNullException("", formatException); var exception = new Exception("", argumentNullException); var foundException = exception.Find<ArgumentNullException>(); Assert.IsNotNull(foundException); Assert.IsInstanceOf(typeof(ArgumentNullException), foundException); }
public void ShouldFlattenTheException() { var formatException = new FormatException("FormatException Message"); var argumentNullException = new ArgumentNullException("ArgumentNullException Message", formatException); var exception = new Exception("Exception Message", argumentNullException); var exceptionFlatten = exception.Flatten(); const string messageExpected = "Exception Message\r\nArgumentNullException Message\r\nFormatException Message\r\n"; Assert.AreEqual(messageExpected, exceptionFlatten); }
/// <summary> /// Parses an integer from the input string. /// </summary> /// <param name="str"> the string to parse </param> /// <returns> the parsed value </returns> /// <exception cref="NumberFormatException"> if the string cannot be parsed </exception> public static int parseInteger(string str) { try { return(int.Parse(str)); } catch (System.FormatException ex) { System.FormatException nfex = new System.FormatException("Unable to parse integer from '" + str + "'"); nfex.initCause(ex); throw nfex; } }
/// <summary> /// Parses a double from the input string, converting it from a percentage to a decimal values. /// </summary> /// <param name="str"> the string to parse </param> /// <returns> the parsed value </returns> /// <exception cref="NumberFormatException"> if the string cannot be parsed </exception> public static double parseDoublePercent(string str) { try { return((new decimal(str)).movePointLeft(2).doubleValue()); } catch (System.FormatException ex) { System.FormatException nfex = new System.FormatException("Unable to parse percentage from '" + str + "'"); nfex.initCause(ex); throw nfex; } }
public void InnerExceptions() { Exception inner = new FormatException(); ApplicationException outer = new ApplicationException(null, inner); JsonObject error = JsonRpcError.FromException(ThrowAndCatch(outer)); JsonArray errors = (JsonArray) error["errors"]; Assert.AreEqual(2, errors.Count); error = (JsonObject) errors.Shift(); Assert.AreEqual(outer.Message, error["message"]); Assert.AreEqual("ApplicationException", error["name"]); error = (JsonObject) errors.Shift(); Assert.AreEqual(inner.Message, error["message"]); Assert.AreEqual("FormatException", error["name"]); }
private Collection<AliasInfo> GetAliasesFromFile(bool isLiteralPath) { Collection<AliasInfo> collection = new Collection<AliasInfo>(); string filePath = null; using (StreamReader reader = this.OpenFile(out filePath, isLiteralPath)) { CSVHelper helper = new CSVHelper(','); long num = 0L; string line = null; while ((line = reader.ReadLine()) != null) { num += 1L; if (((line.Length != 0) && !OnlyContainsWhitespace(line)) && (line[0] != '#')) { Collection<string> collection2 = helper.ParseCsv(line); if (collection2.Count != 4) { string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, num); FormatException exception = new FormatException(message); ErrorRecord errorRecord = new ErrorRecord(exception, "ImportAliasFileFormatError", ErrorCategory.ReadError, filePath) { ErrorDetails = new ErrorDetails(message) }; base.ThrowTerminatingError(errorRecord); } ScopedItemOptions none = ScopedItemOptions.None; try { none = (ScopedItemOptions) Enum.Parse(typeof(ScopedItemOptions), collection2[3], true); } catch (ArgumentException exception2) { string str4 = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, num); ErrorRecord record2 = new ErrorRecord(exception2, "ImportAliasOptionsError", ErrorCategory.ReadError, filePath) { ErrorDetails = new ErrorDetails(str4) }; base.WriteError(record2); continue; } AliasInfo item = new AliasInfo(collection2[0], collection2[1], base.Context, none); if (!string.IsNullOrEmpty(collection2[2])) { item.Description = collection2[2]; } collection.Add(item); } } reader.Close(); } return collection; }
public void TestWhenAll1_Canceled1_Faulted1() { Exception expectedException = new FormatException(); Action<Task> exceptionSelector = task => { throw expectedException; }; IEnumerable<Task> tasks = new[] { DelayedTask.Delay(TimeSpan.FromMilliseconds(1 * TimingGranularity.TotalMilliseconds)).Then(_ => CompletedTask.Canceled()), DelayedTask.Delay(TimeSpan.FromMilliseconds(3 * TimingGranularity.TotalMilliseconds)).Select(exceptionSelector) }; Task delayed = DelayedTask.WhenAll(tasks); Assert.IsFalse(delayed.IsCompleted); try { delayed.Wait(); Assert.Fail("Expected an exception"); } catch (AggregateException ex) { Assert.AreEqual(TaskStatus.Faulted, delayed.Status); Assert.AreEqual(1, ex.InnerExceptions.Count); foreach (Exception innerException in ex.InnerExceptions) { Assert.AreSame(expectedException, innerException); } } Assert.IsTrue(delayed.IsCompleted); Assert.IsTrue(delayed.IsFaulted); Assert.AreEqual(TaskStatus.Faulted, delayed.Status); Task firstTask = tasks.ElementAt(0); Assert.IsTrue(firstTask.IsCompleted); Assert.IsTrue(firstTask.IsCanceled); Assert.AreEqual(TaskStatus.Canceled, firstTask.Status); Task secondTask = tasks.ElementAt(1); Assert.IsTrue(secondTask.IsCompleted); Assert.IsTrue(secondTask.IsFaulted); Assert.AreEqual(TaskStatus.Faulted, secondTask.Status); Assert.IsNotNull(secondTask.Exception); Assert.AreEqual(1, secondTask.Exception.InnerExceptions.Count); Assert.AreSame(expectedException, secondTask.Exception.InnerExceptions[0]); }
private void CheckFillPosibility(StringBuilder templateContent, params string[] substitutions) { for (int i = 0; i < substitutions.Length; ++i) { if (!templateContent.ToString().Contains(substitutions[i])) { //LOGGING var ex = new FormatException("Incorrect template format!"); Logger.Error("Incorrect template format!",ex); throw ex; } } //LOGGING Logger.Info("Ability for filling in template was checked"); }
public String RegistrarExcepcion(Exception excepcion, String origen) { string mensaje = ""; try { if (excepcion is System.ApplicationException) { System.ApplicationException exc = (System.ApplicationException)excepcion; mensaje = EscribirApplicationException(exc, origen); } else if (excepcion is System.IO.InvalidDataException) { System.IO.InvalidDataException exc = (System.IO.InvalidDataException)excepcion; mensaje = EscribirInvalidDataException(exc, origen); } else if (excepcion is System.IO.IOException) { System.IO.IOException exc = (System.IO.IOException)excepcion; mensaje = EscribirIOEx(exc, origen); } else if (excepcion is System.FormatException) { System.FormatException exc = excepcion as System.FormatException; mensaje = EscribirFormatException(exc, origen); } else if (excepcion is System.Data.SqlClient.SqlException) { System.Data.SqlClient.SqlException exc = excepcion as System.Data.SqlClient.SqlException; mensaje = EscribirSqlEx(exc, origen); } else if (excepcion is System.Data.OleDb.OleDbException) { System.Data.OleDb.OleDbException exc = excepcion as System.Data.OleDb.OleDbException; mensaje = EscribirOleDbEx(exc, origen); } else { mensaje = EscribirGenericEx(excepcion, origen); } } catch (Exception ex) { mensaje = "Error interno de la Aplicación. Por favor informar a Sopórte Técnico.\n\n"; mensaje = mensaje + EscribirLocalEx(ex, this.ToString() + ".RegistrarExcepcion"); } return(mensaje); }
public Recipient(string name, string address) { if (Regex.IsMatch(address, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")) { this.Name = name; this.Address = address; } else { Exception e = new FormatException(); LogProcess.Error(e, address); throw e; } }
public static void Throws( Func<string, int> fakedDelegate, FormatException expectedException, Exception exception) { "establish" .x(() => fakedDelegate = A.Fake<Func<string, int>>()); "establish" .x(() => { expectedException = new FormatException(); A.CallTo(() => fakedDelegate.Invoke(A<string>._)).Throws(expectedException); }); "when faking a delegate type and invoking with throwing configuration" .x(() => exception = Record.Exception(() => fakedDelegate(null))); "it should throw the configured exception" .x(() => exception.Should().BeSameAs(expectedException)); }
static void Main(string[] args) { System.IO.IOException get = new System.IO.IOException("get some help"); System.IO.IOException bad = new System.IO.IOException("Stop it!", get); System.IO.FileNotFoundException notFound = new System.IO.FileNotFoundException("Cannot fing", "Mongo.js", get); ApplicationException badAplication = new ApplicationException("The site is trash", get); Console.WriteLine(bad.InnerException.Message); System.FormatException k = new System.FormatException("Invalid number"); try { int num = int.Parse(Console.ReadLine()); num = (int)Math.Sqrt(num); Console.WriteLine(num); } finally { Console.WriteLine("Good bye!"); } }
public static void Main() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; TransactionScope tran = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.RepeatableRead }); using (tran) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../simple-books.xml"); string xPathQuery = "/catalog/book"; foreach (XmlNode item in xmlDoc.SelectNodes(xPathQuery)) { string author = item.GetChildText("author"); string title = item.GetChildText("title"); string isbn = item.GetChildText("isbn"); string price = item.GetChildText("price"); string webSite = item.GetChildText("web-site"); if (!string.IsNullOrWhiteSpace(isbn) && isbn.Length != 13) { FormatException up = new FormatException("ISBN is in a wrong format. It must have 13 digits"); throw up; // lol } BookstoreSystemDLA.CreateBook( author, title, isbn, price, webSite); } } }
private void HandleResponse(IAsyncResult result) { ObservableCollection<NewsItem> results = new ObservableCollection<NewsItem>(); Exception exception = null; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); XmlSerializer serializer = new XmlSerializer(typeof(NewsList)); var temp = (NewsList)serializer.Deserialize(response.GetResponseStream()); results = new ObservableCollection<NewsItem>(temp.Channel.News_List); } catch (Exception ex) { exception = new FormatException(ex.Message); } if (Callback != null) { Callback(results, exception); } }
/// <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); }
private static bool TryParse(byte[] array, int offset, out KeyValuePacket result, out int newOffset, out System.Exception exception) { if (offset + 16 > array.Length) { result = new KeyValuePacket(); newOffset = offset; exception = new System.FormatException("Not enough bytes to start."); return(false); } byte[] baHeader = new byte[4]; System.Array.Copy(array, offset + 0, baHeader, 0, 4); if ((baHeader[0] != 0x4B) || (baHeader[1] != 0x56) || (baHeader[2] != 0x50) || (baHeader[3] != 0x01)) { result = new KeyValuePacket(); newOffset = offset; exception = new System.FormatException("Invalid header."); return(false); } byte[] baKeyLengthBE = new byte[4]; System.Array.Copy(array, offset + 4, baKeyLengthBE, 0, 4); byte[] keyLengthLE = new byte[] { baKeyLengthBE[3], baKeyLengthBE[2], baKeyLengthBE[1], baKeyLengthBE[0] }; int keyLength = System.BitConverter.ToInt32(keyLengthLE, 0); int realKeyLength = keyLength; if (realKeyLength == -1) { realKeyLength = 0; } byte[] baValueLengthBE = new byte[4]; System.Array.Copy(array, offset + 8, baValueLengthBE, 0, 4); byte[] valueLengthLE = new byte[] { baValueLengthBE[3], baValueLengthBE[2], baValueLengthBE[1], baValueLengthBE[0] }; int valueLength = System.BitConverter.ToInt32(valueLengthLE, 0); int realValueLength = valueLength; if (realValueLength == -1) { realValueLength = 0; } if (offset + 16 + realKeyLength + realValueLength > array.Length) { result = new KeyValuePacket(); newOffset = offset; exception = new System.FormatException("Not enough bytes."); return(false); } byte[] baXor = new byte[4]; System.Array.Copy(array, offset + 12, baXor, 0, 4); if ((baXor[0] != (byte)(baHeader[0] ^ baKeyLengthBE[1] ^ baValueLengthBE[2])) || (baXor[1] != (byte)(baHeader[1] ^ baKeyLengthBE[2] ^ baValueLengthBE[3])) || (baXor[2] != (byte)(baHeader[2] ^ baKeyLengthBE[3] ^ baValueLengthBE[0])) || (baXor[3] != (byte)(baHeader[3] ^ baKeyLengthBE[0] ^ baValueLengthBE[1]))) { result = new KeyValuePacket(); newOffset = offset; exception = new System.FormatException("Invalid checksum."); return(false); } string key; if (keyLength == -1) { key = null; } else { key = UTF8Encoding.UTF8.GetString(array, offset + 16 + 0, realKeyLength); } byte[] value; if (valueLength == -1) { value = null; } else { value = new byte[realValueLength]; System.Array.Copy(array, offset + 16 + realKeyLength, value, 0, realValueLength); } result = new KeyValuePacket(key, value); newOffset = offset + 16 + realKeyLength + realValueLength; exception = null; return(true); }
/// <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 _paths) { // resolve the paths and then parse each one. Collection<PathInfo> resolvedPaths = null; 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 = null; 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: bool pathStartsWithRoot = pathsToParse[index].StartsWith("\\", StringComparison.CurrentCulture) || pathsToParse[index].StartsWith("/", StringComparison.CurrentCulture); 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: try { result = SessionState.Path.ParseChildName( pathsToParse[index], CmdletProviderContext, true); } 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
public static bool cuDeviceGetFlag(CUdevice_attribute attrib, CUdevice dev) { var value = cuDeviceGetAttribute(attrib, dev); if (value == 0) { return false; } else if (value == 1) { return true; } else { var fex = new FormatException(String.Format("Attribute \"{0}\" has value \"{1}\" which isn't convertible to bool.", attrib, value)); throw new CudaException(CudaError.InvalidValue, fex); } }
internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) { Exception exception; typedValue = null; exception = dateTimeFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; XsdDateTime dateTime; if (!XsdDateTime.TryParse(s, dateTimeFlags, out dateTime)) { exception = new FormatException(Res.GetString(Res.XmlConvert_BadFormat, s, dateTimeFlags.ToString())); goto Error; } DateTime dateTimeValue = DateTime.MinValue; try { dateTimeValue = (DateTime)dateTime; } catch (ArgumentException e) { exception = e; goto Error; } exception = dateTimeFacetsChecker.CheckValueFacets(dateTimeValue, this); if (exception != null) goto Error; typedValue = dateTimeValue; return null; Error: return exception; }
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("XmlConvert_BadFormat", new object[] { s, "Guid" })); } catch (FormatException) { exception = new FormatException(Res.GetString("XmlConvert_BadFormat", new object[] { s, "Guid" })); } return exception; }
public void SetModelError(System.FormatException ex) { SetError(new ModelException(null, ex)); }
//add movie on watched movie page private void Add_Movie_Click2(object sender, RoutedEventArgs e) { WatchedMovie movie = new WatchedMovie(); bool worked = true; try { movie.Title = Title_Textbox2.Text; if (Title_Textbox2.Text == "") { System.FormatException fEx = new System.FormatException(); throw fEx; } } catch (FormatException) { Title_Textbox.BorderBrush = Brushes.Red; worked = false; } try { double rating = double.Parse(Rating.Text); movie.Rating = rating; if (rating < 0 || rating >= 10) { System.FormatException fEx = new System.FormatException(); throw fEx; } } catch (FormatException) { Rating.BorderBrush = Brushes.Red; worked = false; } ComboBoxItem cbi = (ComboBoxItem)GenreComboBox2.SelectedItem; movie.Genre = cbi.Content.ToString(); if (worked == true) { watchedMovieList.Add(movie); Title_Textbox.BorderBrush = SystemColors.ControlDarkBrush; Rating.BorderBrush = SystemColors.ControlDarkBrush; Title_Textbox2.Text = ""; Rating.Text = ""; GenreComboBox.Text = "Genre"; setModifiedState(); int skip = 0; SkipList2.Clear(); MoviesListView2.Items.Clear(); foreach (WatchedMovie movie2 in watchedMovieList) { try { if (movie2.Title.ToUpper().Contains(Search2.Text.ToUpper()) || Search2.Text == "") { if (Favorite_cb.IsChecked == true) { if (movie2.Favorite == "*") { MoviesListView2.Items.Add(new WatchedMovie { Title = movie2.Title, Genre = movie2.Genre, Rating = movie2.Rating, DateAdded = movie2.DateAdded, Favorite = movie2.Favorite }); SkipList2.Add(skip); } } else { MoviesListView2.Items.Add(new WatchedMovie { Title = movie2.Title, Genre = movie2.Genre, Rating = movie2.Rating, DateAdded = movie2.DateAdded, Favorite = movie2.Favorite }); SkipList2.Add(skip); } } else { skip++; } } catch { } } CheckSort2(); } }
void textBox7_DataError(object sender, System.FormatException e) { //data MessageBox.Show("提示"); }
// FIXME: check if digits are group in correct numbers between the group separators internal static bool Parse(string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc) { result = 0; exc = null; if (s == null) { if (!tryParse) { exc = new ArgumentNullException("s"); } return(false); } if (s.Length == 0) { if (!tryParse) { exc = new FormatException(); } return(false); } #if NET_2_0 // yes it's counter intuitive (buggy?) but even TryParse actually throws in this case if ((style & NumberStyles.AllowHexSpecifier) != 0) { string msg = Locale.GetText("Double doesn't support parsing with '{0}'.", "AllowHexSpecifier"); throw new ArgumentException(msg); } #endif if (style > NumberStyles.Any) { if (!tryParse) { exc = new ArgumentException(); } return(false); } NumberFormatInfo format = NumberFormatInfo.GetInstance(provider); if (format == null) { throw new Exception("How did this happen?"); } if (s == format.NaNSymbol) { result = Double.NaN; return(true); } if (s == format.PositiveInfinitySymbol) { result = Double.PositiveInfinity; return(true); } if (s == format.NegativeInfinitySymbol) { result = Double.NegativeInfinity; return(true); } // // validate and prepare string for C // int len = s.Length; string numstr = ""; int didx = 0; int sidx = 0; char c; if ((style & NumberStyles.AllowLeadingWhite) != 0) { while (sidx < len && Char.IsWhiteSpace(c = s[sidx])) { sidx++; } if (sidx == len) { if (!tryParse) { exc = IntParser.GetFormatException(); } return(false); } } bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0); // // Machine state // int state = State_AllowSign; // // Setup // string decimal_separator = null; string group_separator = null; string currency_symbol = null; int decimal_separator_len = 0; int group_separator_len = 0; int currency_symbol_len = 0; if ((style & NumberStyles.AllowDecimalPoint) != 0) { decimal_separator = format.NumberDecimalSeparator; decimal_separator_len = decimal_separator.Length; } if ((style & NumberStyles.AllowThousands) != 0) { group_separator = format.NumberGroupSeparator; group_separator_len = group_separator.Length; } if ((style & NumberStyles.AllowCurrencySymbol) != 0) { currency_symbol = format.CurrencySymbol; currency_symbol_len = currency_symbol.Length; } string positive = format.PositiveSign; string negative = format.NegativeSign; for (; sidx < len; sidx++) { c = s[sidx]; if (c == '\0') { sidx = len; continue; } switch (state) { case State_AllowSign: if ((style & NumberStyles.AllowLeadingSign) != 0) { if (c == positive[0] && s.Substring(sidx, positive.Length) == positive) { state = State_Digits; sidx += positive.Length - 1; continue; } if (c == negative[0] && s.Substring(sidx, negative.Length) == negative) { state = State_Digits; numstr += '-'; sidx += negative.Length - 1; continue; } } state = State_Digits; goto case State_Digits; case State_Digits: if (Char.IsDigit(c)) { numstr += c; break; } if (c == 'e' || c == 'E') { goto case State_Decimal; } if (decimal_separator != null && decimal_separator[0] == c) { if (String.CompareOrdinal(s, sidx, decimal_separator, 0, decimal_separator_len) == 0) { numstr += '.'; sidx += decimal_separator_len - 1; state = State_Decimal; break; } } if (group_separator != null && group_separator[0] == c) { if (s.Substring(sidx, group_separator_len) == group_separator) { sidx += group_separator_len - 1; state = State_Digits; break; } } if (currency_symbol != null && currency_symbol[0] == c) { if (s.Substring(sidx, currency_symbol_len) == currency_symbol) { sidx += currency_symbol_len - 1; state = State_Digits; break; } } if (Char.IsWhiteSpace(c)) { goto case State_ConsumeWhiteSpace; } if (!tryParse) { exc = new FormatException("Unknown char: " + c); } return(false); case State_Decimal: if (Char.IsDigit(c)) { numstr += c; break; } if (c == 'e' || c == 'E') { if ((style & NumberStyles.AllowExponent) == 0) { if (!tryParse) { exc = new FormatException("Unknown char: " + c); } return(false); } numstr += c; state = State_ExponentSign; break; } if (Char.IsWhiteSpace(c)) { goto case State_ConsumeWhiteSpace; } if (!tryParse) { exc = new FormatException("Unknown char: " + c); } return(false); case State_ExponentSign: if (Char.IsDigit(c)) { state = State_Exponent; goto case State_Exponent; } if (c == positive[0] && s.Substring(sidx, positive.Length) == positive) { state = State_Digits; sidx += positive.Length - 1; continue; } if (c == negative[0] && s.Substring(sidx, negative.Length) == negative) { state = State_Digits; numstr += '-'; sidx += negative.Length - 1; continue; } if (Char.IsWhiteSpace(c)) { goto case State_ConsumeWhiteSpace; } if (!tryParse) { exc = new FormatException("Unknown char: " + c); } return(false); case State_Exponent: if (Char.IsDigit(c)) { numstr += c; break; } if (Char.IsWhiteSpace(c)) { goto case State_ConsumeWhiteSpace; } if (!tryParse) { exc = new FormatException("Unknown char: " + c); } return(false); case State_ConsumeWhiteSpace: if (allow_trailing_white && Char.IsWhiteSpace(c)) { state = State_ConsumeWhiteSpace; break; } if (!tryParse) { exc = new FormatException("Unknown char"); } return(false); } if (state == State_Exit) { break; } } double retVal; try { retVal = Native.Global.parseFloat(numstr); } catch { if (!tryParse) { exc = IntParser.GetFormatException(); } return(false); } //if (!ParseImpl(p, out retVal)) //{ // if (!tryParse) // exc = IntParser.GetFormatException(); // return false; //} if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal)) { if (!tryParse) { exc = new OverflowException(); } return(false); } result = retVal; return(true); }
internal InvalidFilterSpecification(string message, System.FormatException cause) : base(message, cause) { }