private void OnFacebookLinkClicked(object sender, RoutedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered"); try { Process.Start("https://www.facebook.com/home.php?sk=group_186300551397797"); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private void NextButton_OnClick(object sender, RoutedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered"); try { NextControl(); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
public void Save() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { var lib = new Database.Library(); lib.UpdateChemistry(ID, Name, XML, Formula); Dirty = false; } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
private void OnRichTextBoxLinkClicked(object sender, LinkClickedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; _telemetry.Write(module, "Action", "Triggered"); try { Process.Start(e.LinkText); } catch (Exception ex) { using (var form = new ReportError(_telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private void SendCallback(IAsyncResult ar) { var name = ""; try { // Retrieve the socket from the state object. TConnection C = AllConnections[(string)ar.AsyncState]; name = C.Address; // Complete sending the data to the remote device. int bytesSent = C.ConnectionSocket.EndSend(ar); } catch { ReportError?.Invoke("EndSend failed during SendCallback", name); } }
private void OnSourceCodeLinkClicked(object sender, RoutedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered"); try { Process.Start("https://github.com/Chem4Word/Version3"); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private void OnYouTubeLinkClicked(object sender, RoutedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered"); try { Process.Start("https://www.youtube.com/channel/UCKX2kG9kZ3zoX0nCen5lfpQ"); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private SQLiteDataReader GetAllChemistry(SQLiteConnection conn, string filter) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { StringBuilder sb = new StringBuilder(); if (string.IsNullOrWhiteSpace(filter)) { sb.AppendLine("SELECT Id, Chemistry, Name, Formula"); sb.AppendLine("FROM Gallery"); sb.AppendLine("ORDER BY Name"); SQLiteCommand command = new SQLiteCommand(sb.ToString(), conn); return(command.ExecuteReader()); } else { sb.AppendLine("SELECT Id, Chemistry, Name, Formula"); sb.AppendLine("FROM Gallery"); sb.AppendLine("WHERE Name LIKE @filter"); sb.AppendLine("OR"); sb.AppendLine("Id IN"); sb.AppendLine("(SELECT ChemistryID"); sb.AppendLine(" FROM ChemicalNames"); sb.AppendLine(" WHERE Name LIKE @filter)"); sb.AppendLine("ORDER BY Name"); SQLiteCommand command = new SQLiteCommand(sb.ToString(), conn); command.Parameters.Add("@filter", DbType.String).Value = $"%{filter}%"; return(command.ExecuteReader()); } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } return(null); } }
/// <summary> /// Makes the prediction request. /// </summary> /// <param name="file">The file.</param> /// <returns></returns> private async Task MakePredictionRequest(StorageFile file) { try { var client = new HttpClient(); // Request headers - replace this example key with your valid subscription key. client.DefaultRequestHeaders.Add("Prediction-Key", "4b013eec09d5460cb3cbd3178a91dbe0"); // Prediction URL - replace this example URL with your valid prediction URL. string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/08cbc22c-7aa3-43f3-8363-d4895ee306aa/image?iterationId=f635df50-9c4a-4ed2-ad62-1875f2402139"; HttpResponseMessage response; // Request body. Try this sample with a locally stored image. byte[] byteData = await ConvertToImage(file); JToken[] memberName; using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(url, content); var stuff = (await response.Content.ReadAsStringAsync()); var test3 = JObject.Parse(stuff); memberName = test3["Predictions"].ToArray(); } Text = "Bilde inneholder følgende dyr: "; foreach (JToken jt in memberName) { if (Double.Parse(jt["Probability"].ToString()) >= 0.95) { Text += jt["Tag"] + " "; } } } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); Error = true; } }
private void Tags_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { if (Initializing) { return; } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
public override string Translate(string inputText, string defaultNamespace, VsInterop::IVsGeneratorProgress generateProgress) { afh.Text.MultilineString line_column = new afh.Text.MultilineString(inputText); ReportError report = delegate(string msg, int index){ int line, column; line_column.GetLineAndColumn(index, out line, out column); generateProgress.GeneratorError(1, 0, msg, (uint)line, (uint)column); }; ResolveInclude(ref inputText, report); DeleteDirective.Resolve(ref inputText, report); ResolveTemplate(ref inputText, report); ResolveDefine(ref inputText, report); return(NormalizeCrlf(Header + inputText)); }
public static void ChdManCheck(RvFile tFile, string directory, ThreadWorker thWrk, ref bool fileErrorAbort) { string filename = Path.Combine(directory, tFile.Name); if (tFile.FileStatusIs(FileStatus.AltSHA1FromHeader | FileStatus.AltSHA1Verified)) { return; } thWrk.Report(new bgwText2(filename)); CHD.CHDManCheck res = CHD.ChdmanCheck(filename, thWrk, out string error); switch (res) { case CHD.CHDManCheck.Good: tFile.FileStatusSet( (tFile.AltSHA1 != null ? FileStatus.AltSHA1Verified : 0) | (tFile.AltMD5 != null ? FileStatus.AltMD5Verified : 0) ); return; case CHD.CHDManCheck.Corrupt: thWrk.Report(new bgwShowError(filename, error)); tFile.GotStatus = GotStatus.Corrupt; return; case CHD.CHDManCheck.CHDReturnError: case CHD.CHDManCheck.CHDUnknownError: thWrk.Report(new bgwShowError(filename, error)); return; case CHD.CHDManCheck.ChdmanNotFound: return; case CHD.CHDManCheck.CHDNotFound: ReportError.Show("File: " + filename + " Error: Not Found scan Aborted."); fileErrorAbort = true; return; default: ReportError.UnhandledExceptionHandler(error); return; } }
private void RemoveExplicitHydrogens_OnClick(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { if (_eventsEnabled) { ExecuteJavaScript("RemoveHydrogens"); } } catch (Exception ex) { using (var form = new ReportError(Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private static bool VerifySymbol(string str, ReportError error) { if (str.Length < 1) { error("An attribute name cannot be empty."); return(false); } switch (Char.GetUnicodeCategory(str[0])) { case UnicodeCategory.LowercaseLetter: case UnicodeCategory.OtherLetter: break; default: error(String.Format("The name “{0}” is unbecoming of an attribute; it cannot start with “{1}”.", str, str[0])); return(false); } for (var it = 1; it < str.Length; it++) { if (str[it] == '_') { continue; } switch (Char.GetUnicodeCategory(str[it])) { case UnicodeCategory.DecimalDigitNumber: case UnicodeCategory.LetterNumber: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.OtherNumber: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.UppercaseLetter: continue; default: error(String.Format("The name “{0}” is unbecoming of an attribute; it cannot contain “{1}”.", str, str[it])); return(false); } } return(true); }
public bool FindChild(RvBase lName, out int index) { if (ChildNameSearch(lName, out index) != 0) { ReportError.UnhandledExceptionHandler("Could not find self in Parent " + FullName); return(false); } do { if (_children[index] == lName) { return(true); } index++; } while ((index < _children.Count) && (DBHelper.CompareName(lName, _children[index]) == 0)); return(false); }
public override void DatAdd(RvBase file) { RvFile tFile = file as RvFile; if (tFile == null) { ReportError.SendAndShow("Error setting Dat Set Got"); return; } if (Size == null && tFile.Size != null) { Size = tFile.Size; } if (CRC == null && tFile.CRC != null) { CRC = tFile.CRC; } if (SHA1 == null && tFile.SHA1 != null) { SHA1 = tFile.SHA1; } if (MD5 == null && tFile.MD5 != null) { MD5 = tFile.MD5; } if (SHA1CHD == null && tFile.SHA1CHD != null) { SHA1CHD = tFile.SHA1CHD; } if (MD5CHD == null && tFile.MD5CHD != null) { MD5CHD = tFile.MD5CHD; } FileStatusSet( FileStatus.SizeFromDAT | FileStatus.CRCFromDAT | FileStatus.SHA1FromDAT | FileStatus.MD5FromDAT | FileStatus.SHA1CHDFromDAT | FileStatus.MD5CHDFromDAT, tFile); Merge = tFile.Merge; Status = tFile.Status; base.DatAdd(file); }
private void BondLength_ValueChanged(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { if (_eventsEnabled) { ExecuteJavaScript("ReScale", nudBondLength.Value); AverageBondLength = (double)nudBondLength.Value; } } catch (Exception ex) { using (var form = new ReportError(Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private void MirrorButton_OnClick(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { if (_eventsEnabled) { //Telemetry.Write(module, "Action", "Triggered"); ExecuteJavaScript("Mirror"); } } catch (Exception ex) { using (var form = new ReportError(Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
public AutomaticUpdate(IChem4WordTelemetry telemetry) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { _telemetry = telemetry; InitializeComponent(); _telemetry.Write(module, "AutomaticUpdate", "Shown"); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
public Chemistry() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { OtherNames = new List <string>(); Dirty = false; Tags = new ObservableCollection <UserTag>(); Tags.CollectionChanged += Tags_CollectionChanged; HasOtherNames = false; } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
private void ClearButton_OnClick(object sender, RoutedEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { SearchBox.Clear(); SearchButton.IsEnabled = true; ClearButton.IsEnabled = false; ICollectionView filteredView = CollectionViewSource.GetDefaultView((this.MainGrid.DataContext as LibraryViewModel).ChemistryItems); filteredView.Filter = null; } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
private static void SetMissingStatus(RvFile dbChild) { if (dbChild.FileRemove() == EFile.Delete) { ReportError.SendAndShow("Error is Set Missing Status in DatUpdate"); return; } FileType ft = dbChild.FileType; if (ft == FileType.Zip || ft == FileType.SevenZip || ft == FileType.Dir) { RvFile dbDir = dbChild; for (int i = 0; i < dbDir.ChildCount; i++) { SetMissingStatus(dbDir.Child(i)); } } }
private void EditLabelsHost_Load(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { using (new WaitCursor()) { MinimumSize = new Size(900, 600); if (!PointHelper.PointIsEmpty(TopLeft)) { Left = (int)TopLeft.X; Top = (int)TopLeft.Y; } // Fix bottom panel int margin = Buttons.Height - Save.Bottom; splitContainer1.SplitterDistance = splitContainer1.Height - Save.Height - margin * 2; splitContainer1.FixedPanel = FixedPanel.Panel2; splitContainer1.IsSplitterFixed = true; var editor = new LabelsEditor(_options); editor.InitializeComponent(); elementHost1.Child = editor; editor.TopLeft = TopLeft; editor.Used1D = Used1D; editor.PopulateTreeView(Cml); Warning.Text = Message; } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex)) { form.ShowDialog(); } } }
private void TagEditor_PreviewKeyDown(object sender, KeyEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { //Debug.WriteLine($"Keydown code = {e.Key} "); if (e.Key == Key.Return) { //swallow the keystroke e.Handled = true; } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { var animalList = await ApiCall.Get <ObservableCollection <Animal> >("HuntedAnimal/Hunter/1"); if (animalList == null) { animalList = await ApiCall.Get <ObservableCollection <Animal> >("HuntedAnimal/Hunter/1"); if (animalList == null) { await Task.Run(() => ReportError.ErrorAsync("User cannot connect")); } } else { await NavigationService.NavigateAsync(typeof(Views.HunterPage)); } // TODO: add your long-running task here }
public static void ClearSettings() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { RegistryKey key = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey); if (key != null) { key.DeleteValue(Constants.RegistryValueNameLastCheck, false); key.DeleteValue(Constants.RegistryValueNameVersionsBehind, false); } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
/// <summary> /// Starts the asynchronous. /// </summary> public async void StartAsync() { Error = true; HttpClient client = new HttpClient(); //Convert to parent or child from a json string try { HuntedAnimals.Clear(); var jArray = JArray.Parse(await client.GetStringAsync(new Uri("http://localhost:61604/api/HuntedAnimal/Hunter/1"))); for (var i = 0; i < jArray.Count; i++) { if ((bool)jArray[i]["Animal"]["IsPointsAnimal"]) { HuntedAnimals.Add((jArray[i] as JObject).ToObject <HuntedAnimalPoints>()); } else { HuntedAnimals.Add((jArray[i] as JObject).ToObject <HuntedAnimal>()); } } } //Send the Excepetion to a file catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } //Get animal Animals = await ApiCall.Get <ObservableCollection <Animal> >("Animals"); if (HuntedAnimals != null && Animals != null) { Error = false; TotalLength = HuntedAnimals.Count(); } }
// Called by ImportCml(), ImportCml() private long AddChemistry(SQLiteConnection conn, Model model, string chemistryName, string formula) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { long lastId; StringBuilder sb = new StringBuilder(); model.RemoveExplicitHydrogens(); Byte[] blob = Encoding.UTF8.GetBytes(_cmlConverter.Export(model, true)); //Byte[] blob = Encoding.UTF8.GetBytes(_sdFileConverter.Export(model)); sb.AppendLine("INSERT INTO GALLERY"); sb.AppendLine(" (Chemistry, Name, Formula)"); sb.AppendLine("VALUES"); sb.AppendLine(" (@blob, @name, @formula)"); SQLiteCommand command = new SQLiteCommand(sb.ToString(), conn); command.Parameters.Add("@blob", DbType.Binary, blob.Length).Value = blob; command.Parameters.Add("@name", DbType.String, chemistryName.Length).Value = chemistryName; command.Parameters.Add("@formula", DbType.String, formula.Length).Value = formula; command.ExecuteNonQuery(); string sql = "SELECT last_insert_rowid()"; SQLiteCommand cmd = new SQLiteCommand(sql, conn); lastId = (Int64)cmd.ExecuteScalar(); return(lastId); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } return(-1); } }
public static int CompareName(RvFile var1, RvFile var2) { FileType f1 = var1.FileType; FileType f2 = var2.FileType; int res = 0; if (f1 == FileType.ZipFile || f2 == FileType.ZipFile) { if (f1 != f2) { ReportError.SendAndShow("Incompatible Compare type"); } res = Math.Sign(DatSort.TrrntZipStringCompare(var1.Name, var2.Name)); return(res != 0 ? res : Math.Sign(string.Compare(var1.Name, var2.Name, StringComparison.Ordinal))); } if (f1 == FileType.SevenZipFile || f2 == FileType.SevenZipFile) { if (f1 != f2) { ReportError.SendAndShow("Incompatible Compare type"); } return(Math.Sign(DatSort.Trrnt7ZipStringCompare(var1.Name, var2.Name))); } res = DatSort.TrrntZipStringCompare(var1.Name, var2.Name); if (res != 0) { return(res); } #if ZipFile if (f1 == FileType.File && f2 == FileType.Zip) { f2 = FileType.File; } #endif return(f1.CompareTo(f2)); }
private SQLiteDataReader GetAllUserTags(SQLiteConnection conn) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { StringBuilder sb = new StringBuilder(); sb.AppendLine("SELECT Id, UserTag, Lock"); sb.AppendLine("FROM UserTags"); SQLiteCommand command = new SQLiteCommand(sb.ToString(), conn); return(command.ExecuteReader()); } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } return(null); } }
static void ExecuteClientCommandSet(string command) { string[] commandComponents = command.Split (new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); if (commandComponents.Length < 2) { Console.WriteLine ("Invalid number of components in client command 'SET'"); } else { string key = commandComponents [0]; string value = commandComponents [1]; switch (key.ToUpperInvariant ()) { case "HEADING": { GqlEngineState.HeadingEnum heading; if (Enum.TryParse<GqlEngineState.HeadingEnum> (value, true, out heading)) gqlEngine.GqlEngineState.Heading = heading; else Console.WriteLine ("Unknown SET HEADING value '{0}'", value); break; } case "REPORTERROR": { ReportError reportError; if (Enum.TryParse<ReportError> (value, true, out reportError)) MainClass.reportError = reportError; else Console.WriteLine ("Unknown SET REPORTERROR value '{0}'", value); break; } case "VERBOSE": { OnOffEnum onOff; if (Enum.TryParse<OnOffEnum> (value, true, out onOff)) verbose = (onOff == OnOffEnum.On); else Console.WriteLine ("Unknown SET VERBOSE value '{0}'", value); break; } #if _DEBUG case "BREAKONEXCEPTION": { OnOffEnum onOff; if (Enum.TryParse<OnOffEnum> (value, true, out onOff)) breakOnExeption = (onOff == OnOffEnum.On); else Console.WriteLine ("Unknown SET BREAKONEXCEPTION value '{0}'", value); break; } #endif case "AUTOSIZE": { OnOffEnum onOff; if (Enum.TryParse<OnOffEnum> (value, true, out onOff)) { autoSize = (onOff == OnOffEnum.On); if (autoSize) gqlEngine.GqlEngineState.AutoSize = autoSizeRows; else gqlEngine.GqlEngineState.AutoSize = 0; } else { Console.WriteLine ("Unknown SET AUTOSIZE value '{0}'", value); } break; } case "AUTOSIZEROWS": { if (int.TryParse (value, out autoSizeRows)) { if (autoSize) gqlEngine.GqlEngineState.AutoSize = autoSizeRows; else gqlEngine.GqlEngineState.AutoSize = 0; } else { Console.WriteLine ("Unknown SET AUTOSIZEROWS value '{0}'", value); } break; } case "COLUMNDELIMITER": if (value.Length >= 2 && value.StartsWith ("\'") && value.EndsWith ("\'")) value = value.Substring (1, value.Length - 2); gqlEngine.GqlEngineState.ColumnDelimiter = Regex.Unescape (value); break; case "CULTURE": if (value.Length >= 2 && value.StartsWith ("\'") && value.EndsWith ("\'")) value = value.Substring (1, value.Length - 2); try { CultureInfo cultureInfo = CultureInfo.GetCultureInfo (value); gqlEngine.CultureInfo = cultureInfo; } catch (Exception) { Console.WriteLine ("Unknown SET CULTURE value '{0}'", value); } break; case "CASEINSENSITIVE": { OnOffEnum onOff; if (Enum.TryParse<OnOffEnum> (value, true, out onOff)) gqlEngine.CaseInsensitive = (onOff == OnOffEnum.On); else Console.WriteLine ("Unknown SET CASEINSENSITIVE value '{0}'", value); break; } default: Console.WriteLine ("Unknown SET command '{0}'", key); break; } } }
public Argument(ArgumentAttribute attribute, FieldInfo field, ReportError reporter) { longName = Parser.LongName(attribute, field); explicitShortName = Parser.ExplicitShortName(attribute); shortName = Parser.ShortName(attribute, field); hasHelpText = Parser.HasHelpText(attribute); helpText = Parser.HelpText(attribute, field); defaultValue = Parser.DefaultValue(attribute, field); elementType = ElementType(field); flags = Flags(attribute, field); this.field = field; seenValue = false; this.reporter = reporter; isDefault = attribute != null && attribute is DefaultArgumentAttribute; if (IsCollection) { collectionValues = new ArrayList(); } Debug.Assert(longName != null && longName.Length > 0); Debug.Assert(!isDefault || !ExplicitShortName); Debug.Assert(!IsCollection || AllowMultiple, "Collection arguments must have allow multiple"); Debug.Assert(!Unique || IsCollection, "Unique only applicable to collection arguments"); Debug.Assert(IsValidElementType(Type) || IsCollectionType(Type)); Debug.Assert((IsCollection && IsValidElementType(elementType)) || (!IsCollection && elementType == null)); Debug.Assert(!(IsRequired && HasDefaultValue), "Required arguments cannot have default value"); Debug.Assert(!HasDefaultValue || (defaultValue.GetType() == field.FieldType), "Type of default value must match field type"); }
/// <summary> /// Parses Command Line Arguments. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <param name="reporter"> The destination for parse errors. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArguments(string[] arguments, object destination, ReportError reporter) { Parser parser = new Parser(destination.GetType(), reporter); return parser.Parse(arguments, destination); }
/// <summary> /// Creates a new command line argument parser. /// </summary> /// <param name="argumentSpecification"> The type of object to parse. </param> /// <param name="reporter"> The destination for parse errors. </param> public Parser(Type argumentSpecification, ReportError reporter) { this.reporter = reporter; arguments = new ArrayList(); argumentMap = new Hashtable(); foreach (FieldInfo field in argumentSpecification.GetFields()) { if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral) { ArgumentAttribute attribute = GetAttribute(field); if (attribute is DefaultArgumentAttribute) { Debug.Assert(defaultArgument == null); defaultArgument = new Argument(attribute, field, reporter); } else { arguments.Add(new Argument(attribute, field, reporter)); } } } // add explicit names to map foreach (Argument argument in arguments) { Debug.Assert(!argumentMap.ContainsKey(argument.LongName)); argumentMap[argument.LongName] = argument; if (argument.ExplicitShortName) { if (argument.ShortName != null && argument.ShortName.Length > 0) { Debug.Assert(!argumentMap.ContainsKey(argument.ShortName)); argumentMap[argument.ShortName] = argument; } else { argument.ClearShortName(); } } } // add implicit names which don't collide to map foreach (Argument argument in arguments) { if (!argument.ExplicitShortName) { if (argument.ShortName != null && argument.ShortName.Length > 0 && !argumentMap.ContainsKey(argument.ShortName)) { argumentMap[argument.ShortName] = argument; } else { argument.ClearShortName(); } } } }
internal static void ReportError(Exception exceptionObj) { if (exceptionObj == null) return; ReportError reportError = new ReportError(exceptionObj); reportError.ShowDialog(); }