public OrderLinesViewModel() { DisplayName = "Сводный заказ"; InitFields(); Lines = new NotifyValue <ObservableCollection <OrderLine> >(new ObservableCollection <OrderLine>()); SentLines = new NotifyValue <List <SentOrderLine> >(new List <SentOrderLine>()); IsCurrentSelected = new NotifyValue <bool>(true); Begin = new NotifyValue <DateTime>(DateTime.Today.AddMonths(-3).FirstDayOfMonth()); End = new NotifyValue <DateTime>(DateTime.Today); AddressSelector = new AddressSelector(this); FilterItems = new List <Selectable <Tuple <string, string> > >(); FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("InFrozenOrders", "Позиции присутствуют в замороженных заказах"))); FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsMinCost", "Позиции по мин.ценам"))); FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsNotMinCost", "Позиции не по мин.ценам"))); FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("OnlyWarning", "Только позиции с корректировкой"))); CanDelete = CurrentLine.CombineLatest(IsCurrentSelected, (l, s) => l != null && s).ToValue(); BeginEnabled = IsSentSelected.ToValue(); EndEnabled = IsSentSelected.ToValue(); IsCurrentSelected.Subscribe(_ => NotifyOfPropertyChange(nameof(CanPrint))); IsCurrentSelected.Subscribe(_ => NotifyOfPropertyChange(nameof(CanExport))); Sum = new NotifyValue <decimal>(() => { if (IsCurrentSelected) { return(Lines.Value.Sum(l => l.MixedSum)); } return(SentLines.Value.Sum(l => l.MixedSum)); }, SentLines, Lines, IsCurrentSelected); OrderWarning = new InlineEditWarning(UiScheduler, Manager); QuickSearch = new QuickSearch <OrderLine>(UiScheduler, s => Lines.Value.FirstOrDefault(l => l.ProductSynonym.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0), CurrentLine); QuickSearch2 = new QuickSearch <SentOrderLine>(UiScheduler, s => SentLines.Value.FirstOrDefault(l => l.ProductSynonym.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0), SelectedSentLine); Editor = new Editor(OrderWarning, Manager, CurrentLine, Lines.Cast <IList>().ToValue()); var currentLinesChanged = this.ObservableForProperty(m => m.CurrentLine.Value.Count) .Throttle(Consts.RefreshOrderStatTimeout, UiScheduler) .Select(e => new Stat(Address)); OnCloseDisposable.Add(Bus.RegisterMessageSource(currentLinesChanged)); OnCloseDisposable.Add(currentLinesChanged.Subscribe(_ => Sum.Recalculate())); Settings.Subscribe(_ => CalculateOrderLine()); if (Session != null) { Prices = Session.Query <Price>().OrderBy(p => p.Name).ToList() .Select(p => new Selectable <Price>(p)) .ToList(); } else { Prices = new List <Selectable <Price> >(); } MatchedWaybills = new MatchedWaybills(this, SelectedSentLine, IsSentSelected); IsCurrentSelected .Select(v => v ? "Lines" : "SentLines") .Subscribe(ExcelExporter.ActiveProperty); Observable.Merge(IsCurrentSelected.Select(x => (object)x), Lines, SentLines, currentLinesChanged) .Select(_ => { if (IsCurrentSelected) { return(Lines.Value?.Count ?? 0); } return(SentLines.Value?.Count ?? 0); }) .Subscribe(LinesCount); IsLoading = new NotifyValue <bool>(); IsCurrentSelected.Where(v => v) .Select(_ => false) .Subscribe(IsLoading); SessionValue(Begin, GetType().Name + ".Begin"); SessionValue(End, GetType().Name + ".End"); SessionValue(IsSentSelected, GetType().Name + ".IsSentSelected"); Persist(IsExpanded, "IsExpanded"); PrintMenuItems = new ObservableCollection <MenuItem>(); IsView = true; }
public void NewLine() { lines.Add(CurrentLine.ToString()); CurrentLine.Clear(); }
public void Update() { #region reset states _oskPreviousState.Clear(); _oskPreviousState.AddRange(_oskCurrentState); _oskCurrentState.Clear(); foreach (var k in Enum.GetValues(typeof(Keys))) { if ((Keys)k == Keys.None) { continue; } if (Keyboard.GetState().IsKeyDown((Keys)k) && !_oskCurrentState.Contains((Keys)k)) { _oskCurrentState.Add((Keys)k); } } #endregion Typed.Clear(); foreach (var t in _keys) { if (!TypedKey(t)) { continue; } var l = t.ToString(); if (l == "Tab") { l = "\t"; } else if (l.Length == 1) { //if (Released(Keys.LeftShift) && Released(Keys.RightShift)) // l = l.ToLower(); if (Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) && IsCapsLock) { l = l.ToUpper(); } else if (IsCapsLock) { l = l.ToUpper(); } else { l = l.ToLower(); } } else { #region Name Numbers if (l.StartsWith(D) & !l.Equals(DecimalStr) & !l.Equals(Divide)) { l = l.Substring(1); if (Pressed(Keys.LeftShift) || Pressed(Keys.RightShift)) { switch (l) { case Zero: { l = ZeroShift; break; } case One: { l = OneShift; break; } case Two: { l = TwoShift; break; } case Three: { l = ThreeShift; break; } case Four: { l = FourShift; break; } case Five: { l = FiveShift; break; } case Six: { l = SixShift; break; } case Seven: { l = SevenShift; break; } case Eight: { l = EightShift; break; } case Nine: { l = NineShift; break; } } } } #endregion else if (l.StartsWith(NumPad)) { l = l.Substring(6); } else { switch (l) { case OemCommaStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemCommaShift : OemComma; break; } case OemPeriodStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemPeriodShift : OemPeriod; break; } case OemQuestionStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemQuestionShift : OemQuestion; break; } case OemSemicolonStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemSemicolonShift : OemSemicolon; break; } case OemQuotesStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemQuotesShift : OemQuotes; break; } case OemOpenBracketsStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemOpenBracketsShift : OemOpenBrackets; break; } case OemCloseBracketsStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemCloseBracketsShift : OemCloseBrackets; break; } case OemPipeStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemPipeShift : OemPipe; break; } case OemPlusStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemPlusShift : OemPlus; break; } case OemMinusStr: { l = Pressed(Keys.LeftShift) || Pressed(Keys.RightShift) ? OemMinusShift : OemMinus; break; } case TabStr: { l = Tab; break; } case MultiplyStr: { l = Multiply; break; } case DivideStr: { l = Divide; break; } case SubtractStr: { l = Subtract; break; } case AddStr: { l = Add; break; } case DecimalStr: { l = Dot; break; } } } } Typed.Add(l); CurrentLine += l; } // Check input for spacebar if (TypedKey(Keys.Space) && CurrentLine != string.Empty && CurrentLine[CurrentLine.Length - 1].ToString() != Space) { CurrentLine += Space; } // Check input for backspace if (TypedKey(Keys.Back) && CurrentLine != string.Empty) { CurrentLine = CurrentLine.Remove(CurrentLine.Length - 1, 1); } // Check input for enter if (TypedKey(Keys.Enter)) { PreviousLine = CurrentLine; CurrentLine = string.Empty; Typed.Add("\n"); } if (_oskCurrentState == _oskPreviousState) { return; } var remove = new List <Action <KeyboardInput> >(); foreach (var keyboardListener in _keyboardListeners) { try { keyboardListener(this); } catch { remove.Add(keyboardListener); } } _keyboardListeners.RemoveAll(remove.Contains); }
//--------------------------------------------------------------------- protected override IParameters Parse() { ReadLandisDataVar(); EditableParameters parameters = new EditableParameters(SpeciesDataset.Count); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; // Table of reclass coefficients InputVar <string> speciesName = new InputVar <string>("Species"); InputVar <double> reclassCoeff = new InputVar <double>("Reclass Coefficient"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string ReclassMaps = "ReclassMaps"; while (!AtEndOfInput && CurrentName != ReclassMaps) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(speciesName, currentLine); ISpecies species = GetSpecies(speciesName.Value); CheckForRepeatedName(speciesName.Value, "species", lineNumbers); ReadValue(reclassCoeff, currentLine); parameters.ReclassCoefficients[species.Index] = reclassCoeff.Value; CheckNoDataAfter(string.Format("the {0} column", reclassCoeff.Name), currentLine); GetNextLine(); } // Read definitions of reclass maps ReadName(ReclassMaps); InputVar <string> mapName = new InputVar <string>("Map Name"); InputVar <string> forestType = new InputVar <string>("Forest Type"); lineNumbers.Clear(); Dictionary <string, int> forestTypeLineNumbers = new Dictionary <string, int>(); const string MapFileNames = "MapFileNames"; const string nameDelimiter = "->"; // delimiter that separates map name and forest type IEditableMapDefinition mapDefn = null; while (!AtEndOfInput && CurrentName != MapFileNames) { StringReader currentLine = new StringReader(CurrentLine); // If the current line has the delimiter, then read the map // name. if (CurrentLine.Contains(nameDelimiter)) { ReadValue(mapName, currentLine); CheckForRepeatedName(mapName.Value, "map name", lineNumbers); mapDefn = new EditableMapDefinition(); mapDefn.Name = mapName.Value; parameters.ReclassMaps.Add(mapDefn); TextReader.SkipWhitespace(currentLine); string word = TextReader.ReadWord(currentLine); if (word != nameDelimiter) { throw NewParseException("Expected \"{0}\" after the map name {1}.", nameDelimiter, mapName.Value.String); } forestTypeLineNumbers.Clear(); } else { // If there is no name delimiter and we don't have the // name for the first map yet, then it's an error. if (mapDefn == null) { throw NewParseException("Expected a line with map name followed by \"{0}\"", nameDelimiter); } } ReadValue(forestType, currentLine); CheckForRepeatedName(forestType.Value, "forest type", forestTypeLineNumbers); IEditableForestType currentForestType = new EditableForestType(SpeciesDataset.Count); currentForestType.Name = forestType.Value; mapDefn.ForestTypes.Add(currentForestType); // Read species for forest types List <string> speciesNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(speciesName, currentLine); string name = speciesName.Value.Actual; bool negativeMultiplier = name.StartsWith("-"); if (negativeMultiplier) { name = name.Substring(1); if (name.Length == 0) { throw new InputValueException(speciesName.Value.String, "No species name after \"-\""); } } ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String)); if (speciesNames.Contains(species.Name)) { throw NewParseException("The species {0} appears more than once.", species.Name); } speciesNames.Add(species.Name); currentForestType[species.Index] = negativeMultiplier ? -1 : 1; TextReader.SkipWhitespace(currentLine); } if (speciesNames.Count == 0) { throw NewParseException("At least one species is required."); } GetNextLine(); } // Template for filenames of reclass maps InputVar <string> mapFileNames = new InputVar <string>(MapFileNames); ReadVar(mapFileNames); parameters.MapFileNames = mapFileNames.Value; CheckNoDataAfter(string.Format("the {0} parameter", MapFileNames)); return(parameters.GetComplete()); }
//--------------------------------------------------------------------- /// <summary> /// Reads a list of species and their cohorts that should be removed. /// </summary> protected ICohortSelector ReadSpeciesAndCohorts(params string[] names) { List <string> namesThatFollow; if (names == null) { namesThatFollow = new List <string>(); } else { namesThatFollow = new List <string>(names); } cohortSelector = new MultiSpeciesCohortSelector(); SpeciesLineNumbers.Clear(); while (!AtEndOfInput && !namesThatFollow.Contains(CurrentName)) { StringReader currentLine = new StringReader(CurrentLine); // Species name ISpecies species = ReadSpecies(currentLine); // Cohort keyword, cohort age or cohort age range // keyword = (All, Youngest, AllExceptYoungest, Oldest, // AllExceptOldest, 1/{N}) TextReader.SkipWhitespace(currentLine); int indexOfDataAfterSpecies = currentLine.Index; string word = TextReader.ReadWord(currentLine); if (word == "") { throw NewParseException("No cohort keyword, age or age range after the species name"); } bool foundKeyword = false; if (keywordsEnabled) { if (word == "All") { cohortSelector[species] = SelectCohorts.All; foundKeyword = true; } else if (word == "Youngest") { cohortSelector[species] = SelectCohorts.Youngest; foundKeyword = true; } else if (word == "AllExceptYoungest") { cohortSelector[species] = SelectCohorts.AllExceptYoungest; foundKeyword = true; } else if (word == "Oldest") { cohortSelector[species] = SelectCohorts.Oldest; foundKeyword = true; } else if (word == "AllExceptOldest") { cohortSelector[species] = SelectCohorts.AllExceptOldest; foundKeyword = true; } else if (word.StartsWith("1/")) { InputVar <ushort> N = new InputVar <ushort>("1/N"); N.ReadValue(new StringReader(word.Substring(2))); if (N.Value.Actual == 0) { throw NewParseException("For \"1/N\", N must be > 0"); } cohortSelector[species] = new EveryNthCohort(N.Value.Actual).SelectCohorts; foundKeyword = true; } } if (foundKeyword) { CheckNoDataAfter("the keyword \"" + word + "\"", currentLine); } else { // Read one or more ages or age ranges List <ushort> ages = new List <ushort>(); List <AgeRange> ranges = new List <AgeRange>(); currentLine = new StringReader(CurrentLine.Substring(indexOfDataAfterSpecies)); InputVar <AgeRange> ageOrRange = new InputVar <AgeRange>("Age or Age Range"); while (currentLine.Peek() != -1) { ReadValue(ageOrRange, currentLine); ValidateAgeOrRange(ageOrRange.Value, ages, ranges); TextReader.SkipWhitespace(currentLine); } CreateCohortSelectionMethodFor(species, ages, ranges); } GetNextLine(); } if (SpeciesLineNumbers.Count == 0) { throw NewParseException("Expected a line starting with a species name"); } return(cohortSelector); }
/// <summary> /// Process the current line and extract out values /// </summary> private void ProcessLine() { // Standalone (special case for DC dats) if (CurrentLine.StartsWith("Name:")) { string temp = CurrentLine.Substring("Name:".Length).Trim(); CurrentLine = $"Name: {temp}"; } // Comment if (CurrentLine.StartsWith("#")) { Internal = null; InternalName = null; RowType = CmpRowType.Comment; Standalone = null; } // Top-level else if (Regex.IsMatch(CurrentLine, Constants.HeaderPatternCMP)) { GroupCollection gc = Regex.Match(CurrentLine, Constants.HeaderPatternCMP).Groups; string normalizedValue = gc[1].Value.ToLowerInvariant(); Internal = null; InternalName = null; RowType = CmpRowType.TopLevel; Standalone = null; TopLevel = normalizedValue; } // Internal else if (Regex.IsMatch(CurrentLine, Constants.InternalPatternCMP)) { GroupCollection gc = Regex.Match(CurrentLine, Constants.InternalPatternCMP).Groups; string normalizedValue = gc[1].Value.ToLowerInvariant(); string[] linegc = SplitLineAsCMP(gc[2].Value); Internal = new Dictionary <string, string>(); for (int i = 0; i < linegc.Length; i++) { string key = linegc[i].Replace("\"", string.Empty); if (string.IsNullOrWhiteSpace(key)) { continue; } string value = string.Empty; // Special case for DC-style dats, only a few known fields if (DosCenter) { // If we have a name if (key == "name") { while (++i < linegc.Length && linegc[i] != "size" && linegc[i] != "date" && linegc[i] != "crc") { value += $" {linegc[i]}"; } value = value.Trim(); i--; } // If we have a date (split into 2 parts) else if (key == "date") { value = $"{linegc[++i].Replace("\"", string.Empty)} {linegc[++i].Replace("\"", string.Empty)}"; } // Default case else { value = linegc[++i].Replace("\"", string.Empty); } } // Special case for assumed unquoted values (only affects `name`) else if (!Quotes && key == "name") { while (++i < linegc.Length && linegc[i] != "merge" && linegc[i] != "size" && linegc[i] != "crc" && linegc[i] != "md5" && linegc[i] != "sha1") { value += $" {linegc[i]}"; } value = value.Trim(); i--; } else { // Special cases for standalone statuses if (key == "baddump" || key == "good" || key == "nodump" || key == "verified") { value = key; key = "status"; } // Special case for standalone sample else if (normalizedValue == "sample") { value = key; key = "name"; } // Default case else { value = linegc[++i].Replace("\"", string.Empty); } } Internal[key] = value; RowType = CmpRowType.Internal; Standalone = null; } InternalName = normalizedValue; } // Standalone else if (Regex.IsMatch(CurrentLine, Constants.ItemPatternCMP)) { GroupCollection gc = Regex.Match(CurrentLine, Constants.ItemPatternCMP).Groups; string itemval = gc[2].Value.Replace("\"", string.Empty); Internal = null; InternalName = null; RowType = CmpRowType.Standalone; Standalone = new KeyValuePair <string, string>(gc[1].Value, itemval); } // End section else if (Regex.IsMatch(CurrentLine, Constants.EndPatternCMP)) { Internal = null; InternalName = null; RowType = CmpRowType.EndTopLevel; Standalone = null; TopLevel = null; } // Invalid (usually whitespace) else { Internal = null; InternalName = null; RowType = CmpRowType.None; Standalone = null; } }
void ReadINI() { bool CompileError; if (!File.Exists(InPath)) { Debug.Log("Did not find INI!!!"); return; } bool firstBlock = true; List <Block> ReadBlocks = new List <Block>(); int BlockTracker = 0; InputFile = new StreamReader(InPath); string CurrentLine; string[] ParseLine; #region ReadingFile while ((CurrentLine = InputFile.ReadLine()) != null) { if (CurrentLine.ToLower().Contains("block")) { ReadBlocks.Add(new Block(1)); if (!firstBlock) { BlockTracker++; } else { firstBlock = false; } } else { if (CurrentLine.ToLower().Contains("chairtypes")) { ParseLine = MiniParse(CurrentLine); foreach (string element in ParseLine) { ReadBlocks[BlockTracker].ChairType.Add(int.Parse(element)); } } else if (CurrentLine.ToLower().Contains("chairpos")) { ParseLine = MiniParse(CurrentLine); foreach (string element in ParseLine) { ReadBlocks[BlockTracker].ChairPos.Add(float.Parse(element)); } } else if (CurrentLine.ToLower().Contains("balldist")) { ParseLine = MiniParse(CurrentLine); foreach (string element in ParseLine) { ReadBlocks[BlockTracker].BallDist.Add(float.Parse(element)); } } else if (CurrentLine.ToLower().Contains("ballangle")) { ParseLine = MiniParse(CurrentLine); foreach (string element in ParseLine) { ReadBlocks[BlockTracker].BallAngle.Add(float.Parse(element)); } } } } #endregion #region Setup Blocks blockList = new Blocks[ReadBlocks.Count]; BlockTracker = 0; System.Random rand = new System.Random(); foreach (Block element in ReadBlocks) { #region CP=1 if (element.ChairPos.Count == 1 && element.ChairType.Count == 1) { List <Vector2> BallSets = new List <Vector2>(); foreach (float value in element.BallAngle) { foreach (float value2 in element.BallDist) { BallSets.Add(new Vector2(value2, value)); } } blockList[BlockTracker].BallSetups = new Vector2[BallSets.Count]; blockList[BlockTracker].ChairSetups = new Vector2[BallSets.Count]; float v1 = element.ChairType[0]; for (int i = 0; i < blockList[BlockTracker].BallSetups.Length; i++) { int temp = rand.Next(BallSets.Count); blockList[BlockTracker].BallSetups[i] = BallSets[temp]; BallSets.RemoveAt(temp); blockList[BlockTracker].ChairSetups[i] = new Vector2(v1, 0); } } else if (element.ChairPos.Count == 1 && element.ChairType.Count != 1) { Debug.Log(element.ChairType.Count); Debug.Log(string.Format("Not setup to handle to current configuration of Block{0}. Too many ChairTypes.", BlockTracker)); } #endregion #region CP > 1 else { do { CompileError = false; List <Vector2> BallSets = new List <Vector2>(); foreach (float value in element.BallAngle) { foreach (float value2 in element.BallDist) { BallSets.Add(new Vector2(value2, value)); } } List <Vector2> ChairSets = new List <Vector2>(); foreach (float value in element.ChairPos) { foreach (float value2 in element.ChairType) { ChairSets.Add(new Vector2(value2, value)); } } List <Vector4> tempList = new List <Vector4>(); foreach (Vector2 value in ChairSets) { foreach (Vector2 value2 in BallSets) { tempList.Add(new Vector4(value.x, value.y, value2.x, value2.y)); } } blockList[BlockTracker].BallSetups = new Vector2[tempList.Count]; blockList[BlockTracker].ChairSetups = new Vector2[tempList.Count]; //val.y can never be the same two trials in a row for (int k = 0; k < blockList[BlockTracker].BallSetups.Length; k++) { int temp = 0; temp = rand.Next(tempList.Count); int safetyRunner = 0; while (k > 0 && blockList[BlockTracker].ChairSetups[k - 1][1] == tempList[temp].y)//verify no repeat here { if (safetyRunner > tempList.Count) { //do something CanvasError(); Debug.LogError("Error (SafetyRunner) MainScript"); CompileError = true; break; } if (temp < tempList.Count - 1) { temp++; } else if (temp == tempList.Count - 1) { temp = 0; } safetyRunner++; } blockList[BlockTracker].BallSetups[k] = new Vector2(tempList[temp].z, tempList[temp].w); blockList[BlockTracker].ChairSetups[k] = new Vector2(tempList[temp].x, tempList[temp].y); tempList.RemoveAt(temp); } } while (CompileError); } #endregion BlockTracker++; } #endregion Debug.Log(blockList.Length); Debug.Log(blockList[0].ChairSetups.Length); Debug.Log(blockList[0].BallSetups.Length); Debug.Log(blockList[1].ChairSetups.Length); Debug.Log(blockList[1].BallSetups.Length); Debug.Log(blockList[2].ChairSetups.Length); Debug.Log(blockList[2].BallSetups.Length); }
/// <summary> /// Initialize the serializer for reading /// </summary> private void InitialiseRead() { Initialise(); _readBuffer = new Queue <string>(SkipFooterRows); if (_inputStream == null && _fileName == null) { throw new InvalidOperationException("Expected input stream or file name"); } if (_inputStream == null && _fileName != null) { _inputStream = new FileStream(_fileName, FileMode.Open); } _readStream = new StreamReader(_inputStream); LineNo = 0; if (_readStream.BaseStream.CanSeek) { _readStream.BaseStream.Position = 0; } for (int i = 0; i < SkipHeaderRows; i++) { if (_readStream.EndOfStream) { throw new ArgumentException($"SkipRows ({SkipHeaderRows}) contains more rows than there are lines in the file"); } _readStream.ReadLine(); LineNo++; } if (FirstRowHeader) { LineNo++; var headerRow = _readStream.ReadLine(); if (string.IsNullOrWhiteSpace(headerRow)) { throw new InvalidOperationException($"No header row found but one was expected"); } MetaData = SplitLine(headerRow) .Select((a, i) => new ColumnMetaData <T>() { ColumnHeader = a.Trim(), Ordinal = i }) .ToArray(); } if (_readStream.EndOfStream) { return; // file is empty, nothing to do } ReadNext(); if (!FirstRowHeader) { MetaData = CurrentLine .Select((a, i) => new ColumnMetaData <T>() { ColumnHeader = null, Ordinal = i }) .ToArray(); } foreach (var mapping in MappingAttributes) { var matchedMeta = MetaData.Where(a => a.IsMatch(mapping.Mapping)); if (!matchedMeta.Any()) { throw new ArgumentException($"For mapping attribute on column {(mapping.Mapping.InternalColumnOrdinal.HasValue ? mapping.Mapping.ColumnOrdinal.ToString() : $"\"{mapping.Mapping.ColumnName}\"")}, no match was found in the file");
public ScriptError ParseScriptFile() { #region Initialization string CurrentLine, CurrentLineLessComments; char[] charsToTrim = { '\t', ' ' }; int commentIndex; hasSecSerialPort = false; hasSecInit = false; hasSecMeasure = false; hasSecStop = false; currentSection = ScriptSections.NoSectionFound; secInitCommands = new List <string>(); secMeasureCommands = new List <string>(); secStopCommands = new List <string>(); lineCount = 0; #endregion try { StreamReader InputFile = new StreamReader(scriptFileName); while ((CurrentLine = InputFile.ReadLine()) != null) { lineCount++; #region Empty_Line_Processing if (CurrentLine.Length <= 0) { continue; } #endregion #region Comment_Processing columnCount = 1; commentIndex = CurrentLine.IndexOf(commentString); if (commentIndex == 0) { continue; } else if (commentIndex > 0) { CurrentLineLessComments = CurrentLine.Substring(0, commentIndex); } else { CurrentLineLessComments = CurrentLine; } CurrentLineLessComments = CurrentLineLessComments.TrimEnd(charsToTrim); #endregion #region Section_Processing if (CurrentLineLessComments.Contains(sectionString)) { if (CurrentLine.IndexOf(sectionString) != 0) { columnCount = CurrentLineLessComments.IndexOf(sectionString); InputFile.Close(); return(ScriptError.SecBegOfLineErr); } int sectionStringIndex = CurrentLineLessComments.IndexOf(sectionString); CurrentLineLessComments = CurrentLineLessComments.Remove(sectionStringIndex, sectionString.Length); ScriptSections identifiedSection = ScriptSections.NoSectionFound; foreach (ScriptSections currentScriptSection in Enum.GetValues(typeof(ScriptSections))) { if (CurrentLineLessComments.Contains(currentScriptSection.ToString())) { int sectionNameIndex = CurrentLineLessComments.IndexOf(currentScriptSection.ToString()); if (sectionNameIndex != 0) { columnCount = sectionString.Length; InputFile.Close(); return(ScriptError.UnknownSecErr); } if (CurrentLineLessComments.Length > currentScriptSection.ToString().Length) { if (CurrentLineLessComments[currentScriptSection.ToString().Length] != ' ' && CurrentLineLessComments[currentScriptSection.ToString().Length] != '\t') { columnCount = sectionString.Length; InputFile.Close(); return(ScriptError.UnknownSecErr); } } identifiedSection = currentScriptSection; break; } } if (identifiedSection == ScriptSections.NoSectionFound) { InputFile.Close(); return(ScriptError.UnknownSecErr); } if (identifiedSection == ScriptSections.SerialPort) { if (hasSecSerialPort == false) { hasSecSerialPort = true; } else { InputFile.Close(); columnCount = sectionString.Length; return(ScriptError.SecRepeatErr); } } else if (identifiedSection == ScriptSections.Init) { if (hasSecInit == false) { hasSecInit = true; } else { InputFile.Close(); columnCount = sectionString.Length; return(ScriptError.SecRepeatErr); } } else if (identifiedSection == ScriptSections.Measure) { if (hasSecMeasure == false) { hasSecMeasure = true; } else { InputFile.Close(); columnCount = sectionString.Length; return(ScriptError.SecRepeatErr); } } else if (identifiedSection == ScriptSections.Stop) { if (hasSecStop == false) { hasSecStop = true; } else { InputFile.Close(); columnCount = sectionString.Length; return(ScriptError.SecRepeatErr); } } currentSection = identifiedSection; continue; } #endregion #region Section_Statement_Processing CurrentLineLessComments = CurrentLineLessComments.Trim(charsToTrim); #region Section_Serial_Port if (currentSection == ScriptSections.SerialPort) { //CurrentLineLessComments = Regex.Replace(CurrentLineLessComments, @"\s+", ""); if (CurrentLineLessComments.Contains("PortName")) { if ((CurrentLineLessComments.IndexOf("PortName") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("PortName")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } serialPortName = CurrentLineLessComments.Remove(0, "PortName=".Length); } else if (CurrentLineLessComments.Contains("BaudRate")) { if ((CurrentLineLessComments.IndexOf("BaudRate") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("BaudRate")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } CurrentLineLessComments = CurrentLineLessComments.Remove(0, "BaudRate=".Length); if (Int32.TryParse(CurrentLineLessComments, out spBaudRate) == false) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); InputFile.Close(); return(ScriptError.BaudRateResolutionErr); } } else if (CurrentLineLessComments.Contains("Parity")) { if ((CurrentLineLessComments.IndexOf("Parity") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("Parity")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } CurrentLineLessComments = CurrentLineLessComments.Remove(0, "Parity=".Length); try { spParity = (Parity)Enum.Parse(typeof(Parity), CurrentLineLessComments, true); } catch (Exception ex) { if ((ex is ArgumentException) || (ex is OverflowException)) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); } InputFile.Close(); return(ScriptError.ParityResolutionErr); } } else if (CurrentLineLessComments.Contains("DataBits")) { if ((CurrentLineLessComments.IndexOf("DataBits") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("DataBits")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } CurrentLineLessComments = CurrentLineLessComments.Remove(0, "DataBits=".Length); if (Int32.TryParse(CurrentLineLessComments, out spDataBits) == false) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); InputFile.Close(); return(ScriptError.DataBitsResolutionErr); } if ((spDataBits > 8) || (spDataBits < 5)) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); InputFile.Close(); return(ScriptError.DataBitsResolutionErr); } } else if (CurrentLineLessComments.Contains("StopBits")) { if ((CurrentLineLessComments.IndexOf("StopBits") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("StopBits")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } CurrentLineLessComments = CurrentLineLessComments.Remove(0, "StopBits=".Length); try { spStopBits = (StopBits)Enum.Parse(typeof(StopBits), CurrentLineLessComments, true); } catch (Exception ex) { if ((ex is ArgumentException) || (ex is OverflowException)) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); } InputFile.Close(); return(ScriptError.StopBitsResolutionErr); } } else if (CurrentLineLessComments.Contains("Handshake")) { if ((CurrentLineLessComments.IndexOf("Handshake") != 0) && (CurrentLineLessComments[CurrentLineLessComments.IndexOf("Handshake")] != '=')) { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } CurrentLineLessComments = CurrentLineLessComments.Remove(0, "Handshake=".Length); try { spHandshake = (Handshake)Enum.Parse(typeof(Handshake), CurrentLineLessComments, true); } catch (Exception ex) { if ((ex is ArgumentException) || (ex is OverflowException)) { columnCount = CurrentLine.IndexOf(CurrentLineLessComments); } InputFile.Close(); return(ScriptError.HandShakeResolutionErr); } } else { InputFile.Close(); return(ScriptError.UnknownSerialPortSetting); } } #endregion #region Section_Others else { if (CurrentLineLessComments.Contains("SendString")) { //string processedString; if (Regex.IsMatch(CurrentLineLessComments, @"\s*SendString\s*\(\s*"".*""\s*\)\s*") == false) { InputFile.Close(); return(ScriptError.SyntaxErr); } //processedString = Regex.Replace(CurrentLineLessComments, @"\s*SendString\s*\(\s*""", ""); //processedString = Regex.Replace(processedString, @"""\s*\)\s*", ""); if (currentSection == ScriptSections.Init) { secInitCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Measure) { secMeasureCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Stop) { secStopCommands.Add(CurrentLineLessComments); } } else if (CurrentLineLessComments.Contains("DelayMS")) { //string processedString; if (Regex.IsMatch(CurrentLineLessComments, @"\s*DelayMS\s*\(\s*\d+\s*\)\s*") == false) { InputFile.Close(); return(ScriptError.SyntaxErr); } //processedString = Regex.Replace(CurrentLineLessComments, @"\s*SendString\s*\(\s*""", ""); //processedString = Regex.Replace(processedString, @"""\s*\)\s*", ""); if (currentSection == ScriptSections.Init) { secInitCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Measure) { secMeasureCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Stop) { secStopCommands.Add(CurrentLineLessComments); } } else if (CurrentLineLessComments.Contains("ReceiveString")) { //string processedString; if (Regex.IsMatch(CurrentLineLessComments, @"\s*ReceiveString\s*\(\s*"",*%[dlfxsc],*""\s*\)\s*") == false) { InputFile.Close(); return(ScriptError.SyntaxErr); } //processedString = Regex.Replace(CurrentLineLessComments, @"\s*SendString\s*\(\s*""", ""); //processedString = Regex.Replace(processedString, @"""\s*\)\s*", ""); if (currentSection == ScriptSections.Init) { secInitCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Measure) { secMeasureCommands.Add(CurrentLineLessComments); } else if (currentSection == ScriptSections.Stop) { secStopCommands.Add(CurrentLineLessComments); } } else { InputFile.Close(); return(ScriptError.UnknownCmdErr); } } #endregion #endregion } InputFile.Close(); if (lineCount == 0) { return(ScriptError.FileEmpty); } } catch (Exception ex) { if (ex is ArgumentException) { return(ScriptError.CannotOpenFile); } else if (ex is ArgumentNullException) { return(ScriptError.FileDoesNotExist); } } scriptParsed = true; return(ScriptError.NoError); }
//.*?\(.*?\).*?\[.*?\] /// <summary> /// Parse a raw callstack into a pattern /// </summary> /// <param name="CurrentCrash">The crash with a raw callstack to parse.</param> private void ParseCallStack(Crash CurrentCrash) { // Everything is disabled by default bDisplayUnformattedCallStack = false; bDisplayModuleNames = false; bDisplayFunctionNames = false; bDisplayFileNames = false; bDisplayFilePathNames = false; bool bSkipping = false; string LineToSkipUpto = ""; switch (CurrentCrash.CrashType) { case 2: bSkipping = true; LineToSkipUpto = "FDebug::AssertFailed"; break; case 3: bSkipping = true; LineToSkipUpto = "FDebug::"; break; } if (string.IsNullOrEmpty(CurrentCrash.RawCallStack)) { return; } CallStackEntries.Clear(); // Store off a pre split array of call stack lines string[] RawCallStackLines = CurrentCrash.RawCallStack.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); int Middle = RawCallStackLines.Length / 2; // Support older callstacks uploaded before UE4 upgrade if (!NewCallstackFormat.Match(RawCallStackLines[Middle]).Success) { foreach (string CurrentLine in RawCallStackLines) { // Exit if we've hit the max number of lines we want if (CallStackEntries.Count >= MaxLinesToParse) { break; } ParseUE3FormatCallstackLine(CurrentLine); } return; } foreach (string CurrentLine in RawCallStackLines) { // Exit if we've hit the max number of lines we want if (CallStackEntries.Count >= MaxLinesToParse) { break; } if (bSkipping) { if (CurrentLine.Contains(LineToSkipUpto)) { bSkipping = false; } } if (bSkipping) { continue; } string ModuleName = "<Unknown>"; string FuncName = "<Unknown>"; string FilePath = ""; int LineNumber = 0; // // Generic sample line "UE4_Engine!UEngine::Exec() {+ 21105 bytes} [d:\depot\ue4\engine\source\runtime\engine\private\unrealengine.cpp:2777]" // // Mac // thread_start() Address = 0x7fff87ae141d (filename not found) [in libsystem_pthread.dylib] // // Linux // Unknown!AFortPlayerController::execServerSaveLoadoutData(FFrame&, void*) + some bytes int ModuleSeparator = CurrentLine.IndexOf('!'); int PlusOffset = CurrentLine.IndexOf(" + "); int OpenFuncSymbol = CurrentLine.IndexOf('('); int CloseFuncSymbol = CurrentLine.IndexOf(')'); int OpenBracketOffset = CurrentLine.IndexOf('['); int CloseBracketOffset = CurrentLine.LastIndexOf(']'); int MacModuleStart = CurrentLine.IndexOf("[in "); int MacModuleEnd = MacModuleStart > 0 ? CurrentLine.IndexOf("]", MacModuleStart) : 0; bool bLinux = CurrentCrash.PlatformName.Contains("Linux"); bool bMac = CurrentCrash.PlatformName.Contains("Mac"); bool bWindows = CurrentCrash.PlatformName.Contains("Windows"); // Parse out the juicy info from the line of the callstack if (ModuleSeparator > 0) { ModuleName = CurrentLine.Substring(0, ModuleSeparator).Trim(); if (OpenFuncSymbol > ModuleSeparator && CloseFuncSymbol > OpenFuncSymbol) { // Grab the function name if it exists FuncName = CurrentLine.Substring(ModuleSeparator + 1, OpenFuncSymbol - ModuleSeparator - 1).Trim(); FuncName += "()"; // Grab the source file if (OpenBracketOffset > CloseFuncSymbol && CloseBracketOffset > OpenBracketOffset && bWindows) { string FileLinePath = CurrentLine.Substring(OpenBracketOffset + 1, CloseBracketOffset - OpenBracketOffset - 1).Trim(); FilePath = FileLinePath.TrimEnd("0123456789:".ToCharArray()); int SourceLine = 0; Debug.Assert(FilePath.Length < FileLinePath.Length, "WRONG SIZE"); if (int.TryParse(FileLinePath.Substring(FilePath.Length + 1), out SourceLine)) { LineNumber = SourceLine; } } } } else if (bWindows) { // Grab the module name if there is no function name int WhiteSpacePos = CurrentLine.IndexOf(' '); ModuleName = WhiteSpacePos > 0 ? CurrentLine.Substring(0, WhiteSpacePos) : CurrentLine; } if (bMac && MacModuleStart > 0 && MacModuleEnd > 0) { int AddressOffset = CurrentLine.IndexOf("Address ="); int OpenFuncSymbolMac = AddressOffset > 0 ? CurrentLine.Substring(0, AddressOffset).LastIndexOf('(') : 0; if (OpenFuncSymbolMac > 0) { FuncName = CurrentLine.Substring(0, OpenFuncSymbolMac).Trim(); FuncName += "()"; } ModuleName = CurrentLine.Substring(MacModuleStart + 3, MacModuleEnd - MacModuleStart - 3).Trim(); } // Remove callstack entries that match any of these functions. var FuncsToRemove = new HashSet <string>(new string[] { "RaiseException", "FDebug::", "Error::Serialize", "FOutputDevice::Logf", "FMsg::Logf", "ReportCrash", "NewReportEnsure", "EngineCrashHandler", // Generic crash handler for all platforms }); bool Contains = FuncsToRemove.Contains(FuncName, new CustomFuncComparer()); if (!Contains) { CallStackEntries.Add(new CallStackEntry(CurrentLine, ModuleName, FilePath, FuncName, LineNumber)); } } }
public WaybillDetails(uint id) { DisplayName = "Детализация накладной"; this.id = id; InitFields(); CurrentWaybillLine = CurrentLine.OfType <WaybillLine>().ToValue(); Settings.Subscribe(_ => Calculate()); CurrentTax.Subscribe(v => { if (Lines.Value == null) { return; } if (v == null || v.Value == -1) { Lines.Value.Filter = null; } else { Lines.Value.Filter = o => ((WaybillLine)o).Nds == v.Value; } }); Lines.Select(v => v == null ? Observable.Empty <EventPattern <NotifyCollectionChangedEventArgs> >() : v.ToCollectionChanged()) .Switch() .Subscribe(e => { if (e.EventArgs.Action == NotifyCollectionChangedAction.Remove) { e.EventArgs.OldItems.OfType <WaybillLine>().Each(l => Waybill.RemoveLine(l)); } else if (e.EventArgs.Action == NotifyCollectionChangedAction.Add) { e.EventArgs.NewItems.OfType <WaybillLine>().Each(l => Waybill.AddLine(l)); } }); OrderLines = CurrentWaybillLine .Throttle(Consts.ScrollLoadTimeout, UiScheduler) .Select(v => { if (v == null) { return(new List <SentOrderLine>()); } var lineId = v.Id; var orderLineIds = Session.Query <WaybillOrder>().Where(l => l.DocumentLineId == lineId) .Select(l => (uint?)l.OrderLineId) .ToArray(); var line = Session.Query <SentOrderLine>().FirstOrDefault(l => orderLineIds.Contains(l.ServerId)); if (line != null) { CurrentOrderLine.Value = line; line.Order.Lines.Each(l => l.Configure(User)); return(line.Order.Lines.OrderBy(l => l.ProductSynonym).ToList()); } return(new List <SentOrderLine>()); }) .ToValue(CloseCancellation); EmptyLabelVisibility = OrderLines .Select(v => v == null || v.Count == 0 ? Visibility.Visible : Visibility.Collapsed) .ToValue(); OrderDetailsVisibility = EmptyLabelVisibility .Select(v => v == Visibility.Collapsed ? Visibility.Visible : Visibility.Collapsed) .ToValue(); }
private void _btnConfigure_Click(object sender, EventArgs e) { CurrentLine.Config(this.Handle, null); }