コード例 #1
0
 public void default_header_formatter_is_null()
 {
     var field = new Header("teste", "number(6)", null);
     var bag = new ValueBag();
     field.Read(new StringWalker("123"), bag);
     bag["teste"].Formatter.Should().Be.OfType<NullFormatter>();
 }
コード例 #2
0
        /// <inheritdoc />
        public override async Task GetAsync()
        {
            long id = 0;

            //if (!long.TryParse(request.PathSegments.Last(), out id))
            if (!ValueBag.TryGet("id", out id))
            {
                await Request.RespondAsync("Invalid block ID", HttpStatusCode.BadRequest);

                return;
            }

            TerminalBlock block = null;
            await Torch.InvokeAsync(() =>
            {
                MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity);
                if (entity is IMyTerminalBlock terminalBlock)
                {
                    block = new TerminalBlock(terminalBlock, false);
                }
            });

            if (block != null)
            {
                await Request.RespondAsync(block, HttpStatusCode.OK);

                return;
            }

            await Request.RespondAsync("Block not found", HttpStatusCode.NotFound);
        }
コード例 #3
0
 public void can_create_field_with_null_formatter()
 {
     var field = new Field("teste", "number(6)", "null");
     var bag = new ValueBag();
     field.Read(new StringWalker("123"), bag);
     bag["teste"].Formatter.Should().Be.OfType<NullFormatter>();
 }
コード例 #4
0
        public override void Import(ValueBag data, int rowNumber)
        {
            var labResult    = new LabResult();
            var targetValues = new ValueBag(labResult);

            //                labResult.EquipmentID = asset.EquipmentID;

            // perform the value assignments
            foreach (var setter in setters)
            {
                try {
                    setter.Assign(data, targetValues);
                } catch (Exception ex) {
                    log.Error(ex.Message);
                }
            }

            log.Info("{0:0000#}: {1} (ResultID: {2})", rowNumber, labResult.Name, labResult.ResultID);
            //// update the lab result using control number as index if it already exists
            //// otherwise just insert it into the database
            //try {
            //    LabManager.ImportLabResult(labResult);
            //    log.Info(string.Format("{0:00000#}: Imported lab result {1}: {2} {3} @ {4}",
            //        rowNumber, labResult.ControlNum, labResult.EquipType, asset.Name, asset.LocationName));
            //} catch (Exception ex) {
            //    log.Error(string.Format("{0:00000#}: Lab result {1}: import failed. {2} {3} @ {4}",
            //        rowNumber, labResult.ControlNum, labResult.EquipType, asset.Name, asset.LocationName));
            //    log.Error(ex.Message);
            //}
        }
コード例 #5
0
 public void default_field_formatter_is_direct()
 {
     var field = new Field("teste", "number(6)", null);
     var bag = new ValueBag();
     field.Read(new StringWalker("123"), bag);
     bag["teste"].Formatter.Should().Be.OfType<DirectFormatter>();
 }
コード例 #6
0
        private void ImportSites(List <Action <ValueBag> > actions, XElement dataSource)
        {
            // Prepare to read the source data
            int        rowNumber = 0;
            DataReader reader    = DataReader.Load(dataSource);

            // TODO: reduce the data into a distinct set of company/region names

            // import each row in the data source using the defined let statements
            foreach (var row in reader.DataEnumerator())
            {
                //Equipment asset = assetFinder.Find(row);
                var sourceValues = new ValueBag(row);

                rowNumber++;

                var labResult    = new LabResult();
                var targetValues = new ValueBag(labResult);

                var data = new ValueBag(new { Source = row, sourceValues = sourceValues, Target = labResult, targetValues = targetValues });

                foreach (var act in actions)
                {
                    try {
                        act(data);
                    } catch (Exception ex) {
                        this.log.Error(ex.Message);
                    }
                }
            }
        }
コード例 #7
0
 public ValueBag Act(RecordContext context)
 {
     var bag = new ValueBag(context.GetBags());
     bag.Set("tipoOperacao", TipoOperacao);
     bag.Set("parteCobrada", ParteCobrada);
     return bag;
 }
コード例 #8
0
        public (long Id, string Property) GetValues()
        {
            ValueBag.TryGet("property", out string prop);
            ValueBag.TryGet("id", out long id);

            return(id, prop);
        }
コード例 #9
0
ファイル: FsxController.cs プロジェクト: tunstek/hexi
        public bool Connect()
        {
            if (ValueBag.Connected)
            {
                return(false);
            }
            try
            {
                FSUIPCConnection.Open();
                ValueBag.Clear();
                ValueBag.Connected = true;
                FsxiConnected?.Invoke(this, EventArgs.Empty);
                FsxiValueBagUpdated?.Invoke(this, EventArgs.Empty);

                updateThread = new Thread(new ParameterizedThreadStart(ThreadFunc));
                updateThread.Start(this);
                return(true);
            }
            catch (FSUIPCException)
            {
                return(false);
            }
            catch (Exception e)
            {
                log.Error(e);
                return(false);
            }
        }
コード例 #10
0
        /// <inheritdoc />
        public override async Task GetAsync()
        {
            long id = 0;

            //if (!long.TryParse(request.PathSegments.Last(), out id))
            if (!ValueBag.TryGet("id", out id))
            {
                await Request.RespondAsync("Invalid grid ID", HttpStatusCode.BadRequest);

                return;
            }

            Grid grid = null;
            await Torch.InvokeAsync(() =>
            {
                MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity);
                if (entity is IMyCubeGrid cubeGrid)
                {
                    grid = new Grid(cubeGrid);
                }
            });

            if (grid != null)
            {
                await Request.RespondAsync(grid, HttpStatusCode.OK);

                return;
            }

            await Request.RespondAsync("Grid not found", HttpStatusCode.NotFound);
        }
コード例 #11
0
        /// <summary>
        /// Clears the underlying foreign key and lookup data.
        /// </summary>
        public void ClearValue()
        {
            var valueBag = ValueBag.Clone();

            valueBag.ResetValues();
            EndLookup(valueBag);
        }
コード例 #12
0
 void IRowElement.Cleanup(RowPresenter rowPresenter)
 {
     Command    = null;
     ForeignKey = null;
     Lookup     = null;
     ValueBag.Clear();
     this.CleanupCommandEntries();
 }
コード例 #13
0
        public void field_of_datetime_format_culture()
        {
            var field = new Field("teste", "date(HH-dd/MM/yyyy)", "string(ddMMyyyyHH)");
            var bag = new ValueBag();
            field.Read(new StringWalker("22-15/01/2009"), bag);

            bag["teste"].Value.Should().Be(new DateTime(2009, 1, 15, 22, 0, 0));
            bag["teste"].Format().Should().Be("1501200922");
        }
コード例 #14
0
        public void field_of_int_format_culture()
        {
            var field = new Field("teste", "number(6,1)", "string(F3,pt-br)");
            var bag = new ValueBag();
            field.Read(new StringWalker("12345678"), bag);

            bag.GetAs<decimal>("teste").Should().Be(123456.7m);
            bag["teste"].Value.Should().Be(123456.7m);
            bag["teste"].Format().Should().Be("123456,700");
        }
コード例 #15
0
        public void field_of_constant_datetime_format_culture()
        {
            var field = new Field("teste", "constant(2009-11-25, date)", "string(dd/MM/yyyy)");
            var bag = new ValueBag();
            var str = new StringWalker("12345678");
            field.Read(str, bag);

            bag["teste"].Value.Should().Be(new DateTime(2009, 11, 25));
            bag["teste"].Format().Should().Be("25/11/2009");
        }
コード例 #16
0
 /// <summary>
 /// Clear all EngineState collection properties associated with the Engine class
 /// </summary>
 public void Clear()
 {
     ValueBag.Clear();
     EngineResourceFile.ClearAll();
     Tilesheet.ClearAllTilesheets();
     Cycle.ClearAllAnimationCycles();
     GridPointMatrixes.ClearAllGridPointMatrixes();
     GridPointMatrix.ClearAllGridPointMatrix();
     Gondwana.Common.Drawing.Sprites.Sprites.Clear();
     MediaFile.DisposeAll();
 }
コード例 #17
0
 public RecordContext(RecordContext header, string row, ValueBag record, long count, long estimatedTotal, long streamPosition, long streamSize, TimeSpan elapsed)
 {
     this.HeaderContext = header;
     this.Record = record ?? new ValueBag();
     this.Count = count;
     this.StreamPosition = streamPosition;
     this.StreamSize = streamSize;
     this.EstimatedTotal = estimatedTotal;
     this.Elapsed = elapsed;
     this.Row = row;
 }
コード例 #18
0
        static public string Interpolate(string text, ValueBag values, Func <string, dynamic, dynamic> evaluator = null)
        {
            // {colA} -- {colB} ==> colA}, -- , colB}
            var tokens = new Dictionary <string, dynamic>();

            evaluator = evaluator ?? ((source, value) => value);

            // find all of the source names delimited within {} braces.
            foreach (Match match in Interpolations(text))
            {
                var token = match.Value.Trim('{', '}');

                if (!tokens.ContainsKey(token))
                {
                    tokens.Add(token, null);
                }
            }

            // If no braces present, no interpolations detected, return the text as is.
            if (tokens.Count == 0)
            {
                return(text);
            }

            // bind the source values to our sources
            foreach (var token in tokens.Keys.ToList())
            {
                // if this is a literal assignment the source will begin with a single quote
                var tokenValue = token.StartsWith("'")
                    ? token.Trim("'".ToCharArray())
                    : values[token] ?? "";

                // finally bind the result of the evaluator to our sources
                tokens[token] = evaluator(token, tokenValue);   // ?? this.default
            }

            // perform the interpolation
            foreach (var token in tokens.Keys)
            {
                text = text.Replace(string.Concat("{", token, "}"), string.Format("{0}", tokens[token]));
            }

            return(text);
        }
コード例 #19
0
        private List <Action <ValueBag> > CompileImportActions(XElement statement, ValueBag validAssignments)
        {
            List <Action <ValueBag> > actions = new List <Action <ValueBag> >();

            foreach (var stmt in statement.Elements())
            {
                switch (stmt.Name.LocalName.ToLower())
                {
                case "console.print":
                    actions.Add((data) => this.console.Print(stmt.Value, data));
                    break;

                case "console.warn":
                    actions.Add((data) => this.console.Warn(stmt.Value, data));
                    break;

                case "console.error":
                    actions.Add((data) => this.console.Error(stmt.Value, data));
                    break;

                case "console.debug":
                    actions.Add((data) => this.console.Debug(stmt.Value, data));
                    break;

                case "let":
                    // a setter takes the form of
                    //   <let propertyname="column name" default="default value"><values><add text="if this" value="then this value" /></values></let>
                    // we need to validate that the setters propertyname is valid
                    var assignment = new Setter(stmt);

                    if (validAssignments.ContainsKey(assignment.Target))
                    {
                        actions.Add((data) => assignment.Assign(data["sourceValues"], data["targetValues"]));
                    }
                    else
                    {
                        this.log.Warn(string.Format("'{0}' is not a valid assignment attribute. Assignment skipped.", assignment.Target));
                    }
                    break;
                }
            }

            return(actions);
        }
コード例 #20
0
ファイル: FsxController.cs プロジェクト: tunstek/hexi
 public bool Disconnect()
 {
     if (!ValueBag.Connected)
     {
         return(false);
     }
     try
     {
         FSUIPCConnection.Close();
         updateThread.Abort();
         updateThread = null;
         ValueBag.Clear();
         ValueBag.Connected = false;
         FsxiDisconnected?.Invoke(this, EventArgs.Empty);
         FsxiValueBagUpdated?.Invoke(this, EventArgs.Empty);
         return(true);
     }
     catch (FSUIPCException)
     {
         return(false);
     }
 }
コード例 #21
0
        private void ImportCompanies(List <Action <ValueBag> > actions, XElement dataSource)
        {
            // Prepare to read the source data
            int                 rowNumber = 0;
            DataReader          reader    = DataReader.Load(dataSource);
            List <LocationPath> locations = new List <LocationPath>();

            // collect each row in the data source using the defined let statements
            foreach (var row in reader.DataEnumerator())
            {
                //Equipment asset = assetFinder.Find(row);
                var sourceValues = new ValueBag(row);

                rowNumber++;

                var path         = new LocationPath();
                var targetValues = new ValueBag(path);

                var data = new ValueBag(new { Source = row, sourceValues = sourceValues, Target = path, targetValues = targetValues });

                foreach (var act in actions)
                {
                    try {
                        act(data);
                    } catch (Exception ex) {
                        this.log.Error(ex.Message);
                    }
                }

                locations.Add(path);
            }

            // reduce the collected company locations into a distinct set of data and import
            foreach (var location in locations.Select((loc) => loc.CompanyName).Distinct())
            {
                ;
            }
        }
コード例 #22
0
        /// <inheritdoc />
        public override async Task PostAsync()
        {
            long   id;
            string actionName;

            if (!(ValueBag.TryGet("id", out id) && ValueBag.TryGet("action", out actionName)))
            {
                await Request.RespondAsync("Invalid parameters.", HttpStatusCode.BadRequest);

                return;
            }

            await Torch.InvokeAsync(() =>
            {
                MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity);
                if (entity is IMyTerminalBlock terminalBlock && terminalBlock.HasAction(actionName))
                {
                    terminalBlock.ApplyAction(actionName);
                }
            });

            await Request.RespondAsync(null, HttpStatusCode.OK);
        }
コード例 #23
0
        public TokenMatchResult(ICommandToken token, string matchedTokensText, string fullMatchText, MatchOutcome matchOutcome, int charsMatched, int tokensMatched)
        {
            if (matchedTokensText == null)
            {
                throw new ArgumentNullException(nameof(matchedTokensText));
            }
            if (fullMatchText == null)
            {
                throw new ArgumentNullException(nameof(fullMatchText));
            }
            if (charsMatched < 0 || charsMatched > matchedTokensText.Length)
            {
                throw new ArgumentOutOfRangeException($"{nameof(charsMatched)} should be <= {nameof(matchedTokensText)}.Length");
            }
            ArgumentValues = new ValueBag <ArgumentToken>();

            Token             = token;
            MatchedTokensText = matchedTokensText;
            FullMatchText     = fullMatchText;
            MatchOutcome      = matchOutcome;
            CharsMatched      = charsMatched;
            TokensMatched     = tokensMatched;
        }
コード例 #24
0
 private void Assert(ValueBag bag, int prop, string tipo, string parte)
 {
     bag["prop"].Should().Be(new ValueItem(prop));
     bag["tipoOperacao"].Should().Be(new ValueItem(tipo));
     bag["parteCobrada"].Should().Be(new ValueItem(parte));
 }
コード例 #25
0
 private void AssertRow(ValueBag bag, params object[] values)
 {
     for (int i = 0; i < columns.Length; i++)
         bag[columns[i]].Value.Should().Be(values[i]);
 }
コード例 #26
0
 public ImportedFile(ValueBag header, IList<ValueBag> fields)
 {
     this.Header = header;
     this.Records = fields;
 }
コード例 #27
0
 /// <summary>
 /// Prints the specified text.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="values">The values.</param>
 public void Print(string text, ValueBag values)
 {
     Terminal.Print(text, values, this.logger);
 }
コード例 #28
0
        private void ImportLocations(List <Action <ValueBag> > actions, XElement dataSource)
        {
            // Prepare to read the source data
            int                 rowNumber = 0;
            DataReader          reader    = DataReader.Load(dataSource);
            List <LocationPath> locations = new List <LocationPath>();

            // collect each row in the data source using the defined let statements
            foreach (var row in reader.DataEnumerator())
            {
                //Equipment asset = assetFinder.Find(row);
                var sourceValues = new ValueBag(row);

                rowNumber++;

                var path         = new LocationPath();
                var targetValues = new ValueBag(path);

                var data = new ValueBag(new { Source = row, sourceValues = sourceValues, Target = path, targetValues = targetValues });

                foreach (var act in actions)
                {
                    try {
                        act(data);
                    } catch (Exception ex) {
                        this.log.Error(ex.Message);
                    }
                }

                locations.Add(path);
            }

            int          currentSiteID    = 0;
            int          currentRegionID  = 0;
            int          currentCompanyID = 0;
            LocationPath currentLocation  = new LocationPath();

            // reduce the collected locations into a distinct ordered set of data and import
            log.Info("Collected: {0} items into a distinct count of {1} items", locations.Count, locations.Distinct().Count());
            foreach (var location in locations.Distinct().OrderBy(x => x.CompanyName).ThenBy(x => x.RegionName).ThenBy(x => x.SiteName))
            {
                log.Info("{0} / {1} / {2}", location.CompanyName, location.RegionName, location.SiteName);

                if (!(currentLocation.CompanyName ?? "").Equals(location.CompanyName ?? "", StringComparison.CurrentCultureIgnoreCase))
                {
                    currentLocation.CompanyName = location.CompanyName ?? "";
                    // Location.OrganizationID = context.OrganizationID
                    // Location.LocationTypeID = COMPANY_LOCATION_TYPE    // (1)
                    // Location.Name = currentLocation.CompanyName
                    // currentCompanyID = ConfigurationSystem.SaveLocation(Location).LocationID
                }

                if (!(currentLocation.RegionName ?? "").Equals(location.RegionName ?? "", StringComparison.CurrentCultureIgnoreCase))
                {
                    currentLocation.RegionName = location.RegionName ?? "";
                    // Location.OrganizationID = context.OrganizationID
                    // Location.LocationTypeID = REGION_LOCATION_TYPE    // (2)
                    // Location.Name = currentLocation.RegionName
                    // Location.ParentLocations = new int[] { currentCompanyID }
                    // currentRegionID = ConfigurationSystem.SaveLocation(Location).LocationID
                }

                if (!(currentLocation.SiteName ?? "").Equals(location.SiteName ?? "", StringComparison.CurrentCultureIgnoreCase))
                {
                    currentLocation.SiteName = location.SiteName ?? "";
                    // Location.OrganizationID = context.OrganizationID
                    // Location.LocationTypeID = SITE_LOCATION_TYPE    // (4)
                    // Location.Name = currentLocation.SiteName
                    // Location.ParentLocations = new int[] { currentRegionID }
                    // currentSiteID = ConfigurationSystem.SaveLocation(Location).LocationID
                }
            }
        }
コード例 #29
0
 /// <summary>
 /// Prints the specified error text.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="values">The values.</param>
 public void Error(string text, ValueBag values)
 {
     Terminal.Error(text, values, this.logger);
 }
コード例 #30
0
 /// <summary>
 /// Prints the specified text.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="values">The values.</param>
 /// <param name="logger">The logger.</param>
 static public void Print(string text, ValueBag values, Action <int, string> logger)
 {
     logger.Info(Interpolator.Interpolate(text, values));
 }
コード例 #31
0
 /// <summary>
 /// Prints the specified text warning.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="values">The values.</param>
 public void Warn(string text, ValueBag values)
 {
     Terminal.Warn(text, values, this.logger);
 }
コード例 #32
0
 /// <summary>
 /// Prints the specified debug text.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="values">The values.</param>
 public void Debug(string text, ValueBag values)
 {
     Terminal.Debug(text, values, this.logger);
 }
コード例 #33
0
        /// <summary>
        /// Imports the specified data using the specified intructions.
        /// </summary>
        /// <param name="instructions">The instructions.</param>
        /// <param name="data">The data.</param>
        /// <param name="log">The log.</param>
        /// <param name="context">The import context information.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Import(XElement instructions, XElement[] data, Action <int, string> log = null, dynamic context = null)
        {
            log.Info("Running ...");
            if (instructions == null)
            {
                throw new ArgumentNullException("instructions");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            var console = new Terminal(log);

            // compile into an actionable list
            List <Action> actions = new List <Action>();

            foreach (var statement in instructions.Elements())
            {
                switch (statement.Name.LocalName.ToLower())
                {
                case "console.print":
                    actions.Add(() => console.Print(statement.Value));
                    break;

                case "console.warn":
                    actions.Add(() => console.Warn(statement.Value));
                    break;

                case "console.error":
                    actions.Add(() => console.Error(statement.Value));
                    break;

                case "console.debug":
                    actions.Add(() => console.Debug(statement.Value));
                    break;

                case "foreach":
                    actions.Add(() => {
                        List <Action> forEachActions = new List <Action>();
                        List <Importer> importers    = new List <Importer>();

                        // the "foreach" statment is a fairly complex definition to parse
                        // it contains the instructions on which fields and method are to be used to lookup the thing
                        // it also specifies the data element to be used as input

                        //// the "asset" attribute specifies which fields and method to use to lookup the equipment item
                        //if (foreachStatement.Attribute("asset") == null) {
                        //    log.Error("Missing asset attribute. A foreach element must contain an asset attribute.");
                        //    continue;
                        //}

                        //var assetFinder = new EquipmentFinder(foreachStatement.Attribute("asset").Value, organizationID);

                        // the "in" or "rowIn" attribute specifies which data element contains the source data to update from
                        var inAttribute = statement.Attribute("in", "rowIn");

                        if (inAttribute == null)
                        {
                            log.Warn("Missing 'in' attribute. Defaulting to first data element");
                        }

                        // locate the data element that contains the source data to update from
                        XElement dataSource = null;

                        if (inAttribute != null)
                        {
                            foreach (var item in data)
                            {
                                if (item.Attribute("id") != null && item.Attribute("id").Value.ToLower() == inAttribute.Value.ToLower())
                                {
                                    dataSource = item;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            dataSource = data.FirstOrDefault();
                        }

                        if (dataSource == null)
                        {
                            log.Error(string.Format("Unable to determine the data set to use. '{0}'", inAttribute != null ? inAttribute.Value : ""));
                            return;     // continue;
                        }

                        // A foreach element contains a collection of import elements that provide instructions to perform an import operation
                        foreach (var stmt in statement.Elements("console.print", "console.warn", "console.error", "console.debug", "import"))
                        {
                            switch (stmt.Name.LocalName.ToLower())
                            {
                            case "console.print":
                                forEachActions.Add(() => console.Print(stmt.Value));
                                break;

                            case "import":
                                forEachActions.Add(() => {
                                    var importStatement = stmt;
                                    // every import element must minimally define an into attribute
                                    var intoAttribute = importStatement.Attribute("into");

                                    if (intoAttribute == null)
                                    {
                                        log.Error("Missing into attribute. An import element must contain an 'into' attribute.");
                                        return;         // continue;
                                    }

                                    switch (intoAttribute.Value.ToLower())
                                    {
                                    case "alarm":
                                    case "labresult":
                                        // import lab result
                                        // An import element contains a collection of let elements that provide instructions as to which data columns
                                        // are to be assigned to which lab result properties
                                        var setters = new List <Setter>();

                                        // a setter takes the form of
                                        //   <let propertyname="column name" default="default value"><values><add text="if this" value="then this value" /></values></let>
                                        // we need to validate that the setters propertyname is valid for a lab result
                                        // review each setter and ensure that the setter is within the vocabulary of a lab result definition
                                        var labResultAttributes = new ValueBag(new LabResult());

                                        foreach (var item in importStatement.Elements("let"))
                                        {
                                            var assignment = new Setter(item);

                                            if (labResultAttributes.ContainsKey(assignment.Target))
                                            {
                                                setters.Add(new Setter(item));
                                            }
                                            else
                                            {
                                                log.Warn(string.Format("'{0}' is not a valid lab result attribute. Assignment skipped.", assignment.Target));
                                            }
                                        }

                                        importers.Add(new LabResultImporter(setters, log));
                                        break;

                                    //case "values":
                                    //    // import gassing values
                                    //    importers.Add(new ValuesImporter(ValueHarvester.Load(importStatement), log));
                                    //    break;

                                    default:
                                        log.Warn(string.Format("'{0}' is not a recognized import subject. Ignoring import operation.", intoAttribute.GetValueOrDefault()));
                                        break;
                                    }
                                });
                                break;
                            }
                        }

                        foreach (var act in forEachActions)
                        {
                            act();
                        }

                        // Prepare to read the source data
                        int rowNumber     = 0;
                        DataReader reader = DataReader.Load(dataSource);

                        // import each row in the data source using the defined let statements
                        foreach (var row in reader.DataEnumerator())
                        {
                            //Equipment asset = assetFinder.Find(row);
                            var sourceValues = new ValueBag(row);

                            rowNumber++;

                            ////if (asset == null)
                            ////    log.Warn(string.Format("RowNumber: {1:00000#} equipment not found. Failed to resolve {0}.", assetFinder.Statement(row) as string, rowNumber));
                            ////else
                            foreach (var importer in importers)
                            {
                                try {
                                    importer.Import(sourceValues, rowNumber);
                                } catch (Exception ex) {
                                    log.Error(ex.Message);
                                }
                            }
                        }
                    });
                    break;

                default:
                    break;
                }
            }

            foreach (var action in actions)
            {
                action();
            }

            // first up, parse the instructions into something actionable here
            // execute the instructions

            foreach (var foreachStatement in instructions.Elements("foreach"))
            {
            }

            log.Info("Running ... Done.");
        }
コード例 #34
0
 public virtual void Import(ValueBag data, int rowNumber)
 {
     throw new NotImplementedException();
 }
コード例 #35
0
        /// <summary>
        /// Sets the value of the targetValues.Target attribute equal to the value of the sourceValues.Source attribute.
        /// </summary>
        /// <param name="sourceValues">The source values to assign from.</param>
        /// <param name="targetValues">The target values to assin to.</param>
        /// <param name="evaluator">An evaluator function providing an opportunity to inspect or modify the final value to assign.</param>
        public void Assign(ValueBag sourceValues, ValueBag targetValues, Func <string, string, dynamic, dynamic> evaluator = null)
        {
            evaluator = evaluator ?? ((source, target, value) => value);

            // find all of the source names delimited within {} braces.
            // scan the tokens, if source element ends in } then we have a column source value
            if (Interpolator.Interpolations(this.Source).Count == 0)
            {
                // if this is a literal assignment the source will begin with a single quote
                var sourceValue = this.Source.StartsWith("'")
                    ? this.Source.Trim("'".ToCharArray())
                    : sourceValues.GetValue(this.Source) ?? this.Default;

                // if we have a global values clause resolve the sourceValue to a value in the list
                sourceValue = ResolveToConstrainedValue("*", sourceValue);

                // if we have a source specific values clause; resolve the sourceValue to a value in the list
                sourceValue = ResolveToConstrainedValue(this.Source, sourceValue);

                // finally bind the result of the evaluator to our sources
                targetValues.SetValue(this.Target, evaluator(this.Source, this.Target, sourceValue));
            }
            else
            {
                targetValues.SetValue(this.Target, evaluator(this.Source, this.Target,
                                                             Interpolator.Interpolate(this.Source, sourceValues, (src, value) => {
                    // if we have a global values clause resolve the sourceValue to a value in the list
                    value = ResolveToConstrainedValue("*", value ?? this.Default);

                    // if we have a source specific values clause; resolve the sourceValue to a value in the list
                    value = ResolveToConstrainedValue(src, value);

                    // finally bind the result of the evaluator
                    return(evaluator(src, this.Target, value));
                })));
            }

            //// {colA} -- {colB} ==> colA}, -- , colB}
            //var sources = new Dictionary<string, dynamic>();
            //var results = expression.Matches(this.Source);
            //foreach (Match match in results) {
            //    var token = match.Value.Trim('{', '}');

            //    if (!sources.ContainsKey(token))
            //        sources.Add(token, null);
            //}

            //// If no braces present then use the source statement as is
            //if (sources.Count == 0)
            //    sources.Add(this.Source, null);

            //// bind the source values to our sources
            //foreach (var source in sources.Keys.ToList()) {
            //    // if this is a literal assignment the source will begin with a single quote
            //    var sourceValue = source.StartsWith("'")
            //        ? source.Trim("'".ToCharArray())
            //        : sourceValues.GetValue(source) ?? this.Default;

            //    // if we have a global values clause resolve the sourceValue to a value in the list
            //    sourceValue = ResolveToConstrainedValue("*", sourceValue);

            //    // if we have a source specific values clause; resolve the sourceValue to a value in the list
            //    sourceValue = ResolveToConstrainedValue(source, sourceValue);

            //    // finally bind the result of the evaluator to our sources
            //    sources[source] = evaluator(source, this.Target, sourceValue);
            //}

            //// assign the value
            //if (sources.Count > 1) {
            //    string interpolation = this.Source;

            //    foreach (var source in sources.Keys)
            //        interpolation = interpolation.Replace(string.Concat("{", source, "}"), string.Format("{0}", sources[source]));

            //    targetValues.SetValue(this.Target, interpolation);
            //} else
            //    targetValues.SetValue(this.Target, sources[this.Source]);

            //targetValues.SetValue(this.Target, Console.Interpolate(this.Source, sourceValues, (src, value) => {
            //        // if we have a global values clause resolve the sourceValue to a value in the list
            //        value = ResolveToConstrainedValue("*", value ?? this.Default);

            //        // if we have a source specific values clause; resolve the sourceValue to a value in the list
            //        value = ResolveToConstrainedValue(src, value);

            //        // finally bind the result of the evaluator
            //        return evaluator(src, this.Target, value);
            //    }));
        }
コード例 #36
0
        public void field_of_int_format_direct()
        {
            var field = new Field("teste", "number(6)", null);
            var bag = new ValueBag();
            field.Read(new StringWalker("1234567"), bag);

            bag.GetAs<decimal>("teste").Should().Be(123456m);
            bag["teste"].Value.Should().Be(123456);
            bag["teste"].Format().Should().Be(123456);
        }
コード例 #37
0
 public RecordContext(RecordContext header, ValueBag record)
     : this(header, string.Empty, record, 0, 0, 0, 0, TimeSpan.Zero)
 {
 }