Ejemplo n.º 1
0
        public static IEnumerable <MethodDef> GetVisibleExtensionMethods(this MetadataTables tables)
        {
            MetadataRecord eaCtor = GetExtensionAttributeCtor(tables);

            if (!eaCtor.IsNull)
            {
                foreach (CustomAttributeDef ca in tables.CustomAttributes)
                {
                    if (ca.Constructor.Equals(eaCtor) && ca.Parent.IsMethodDef)
                    {
                        MethodDef mdef   = ca.Parent.MethodDef;
                        var       mattrs = mdef.Attributes;
                        if ((mattrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Public && (mattrs & MethodAttributes.Static) != 0)
                        {
                            var declType = mdef.FindDeclaringType();
                            var tattrs   = declType.Attributes;
                            if (((tattrs & TypeAttributes.VisibilityMask) == TypeAttributes.Public ||
                                 (tattrs & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) &&
                                (tattrs & TypeAttributes.Abstract) != 0 &&
                                (tattrs & TypeAttributes.Sealed) != 0)
                            {
                                yield return(mdef);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Computes the length of a data array in a HDU.
        /// </summary>
        /// <param name="Header">The header for which to compute the array length.</param>
        /// <returns>Array length in bytes.</returns>
        public static int ComputeDataArrayLength(Dictionary <string, MetadataRecord> Header)
        {
            try
            {
                MetadataRecord bp   = Header["BITPIX"];
                MetadataRecord naxr = Header["NAXIS"];
                int            nax  = naxr.Int;
                if (nax != 2)
                {
                    if (nax == 0)
                    {
                        return(0);
                    }
                    else
                    {
                        throw new NotSupportedException("Umbrella2 can only read 2D images.");
                    }
                }
                MetadataRecord n1 = Header["NAXIS1"];
                MetadataRecord n2 = Header["NAXIS2"];

                return(Math.Abs(bp.Int) * n1.Int * n2.Int / 8);
            }
            catch (Exception ex)
            { throw new FITSFormatException("Missing or malformed FITS header entries.", ex); }
        }
Ejemplo n.º 3
0
        private static string MethodToString(MetadataRecord record)
        {
            if (record.IsNull)
            {
                return("<none>");
            }

            switch (record.Type)
            {
            case MetadataRecordType.MethodDef:
                var methodDef = record.MethodDef;
                var parent    = methodDef.FindDeclaringType();
                return(String.Format("def({0}.{1}::{2})", parent.Namespace, parent.Name, methodDef.Name));

            case MetadataRecordType.MemberRef:
                var memberRef = record.MemberRef;
                return(String.Format("ref({0}::{1}|{2})", TypeToString(memberRef.Class), memberRef.Name, SignatureToString(memberRef.Signature)));

            case MetadataRecordType.MethodSpec:
                var methodSpec = record.MethodSpec;
                return(String.Format("spec({0})", SignatureToString(methodSpec.Signature)));
            }

            throw new InvalidOperationException("Unknown method token");
        }
Ejemplo n.º 4
0
        public async Task Set(MetadataRecord record, CancellationToken token = default)
        {
            record.VerifyNotNull(nameof(record));

            IMetadataRecordActor actor = _actorHost !.GetActor <IMetadataRecordActor>((ActorKey)record.Id);
            await actor.Set(record, token);
        }
        public void CouldIncrementCounter()
        {
            var path    = TestUtils.GetPath(clear: true);
            var storage = new SQLiteStorage($@"Filename={Path.Combine(path, "metadatastorage.db")}");

            var md1 = new MetadataRecord()
            {
                PK          = "test1:/md1",
                Metadata    = new Metadata("md1"),
                RepoId      = 2,
                ContainerId = 1
            };

            var insertResult = storage.InsertMetadataRow(md1);

            Assert.IsTrue(insertResult);

            var result  = storage.IncrementCounter("test1:/md1");
            var result1 = storage.IncrementCounter("test1:/md1");

            Assert.AreEqual(result1, result + 1);

            var mdExact = storage.GetExactMetadata("test1:/md1");

            Assert.AreEqual(result1, mdExact.Counter);
            storage.Dispose();
        }
Ejemplo n.º 6
0
        public static JObject ToDto(this MetadataRecord record)
        {
            var result       = new JObject();
            var translations = new JArray();
            var children     = new JArray();

            foreach (var translation in record.Translations)
            {
                translations.Add(new JObject
                {
                    { translation.Language, translation.Value }
                });
            }

            if (record.Children != null)
            {
                foreach (var child in record.Children)
                {
                    children.Add(new JObject
                    {
                        { child.Key, child.Value.ToDto() }
                    });
                }
            }

            result.Add("translations", translations);
            result.Add("children", children);
            return(result);
        }
Ejemplo n.º 7
0
        public void MetadataUnitTest_3()
        {
            var source = new FileMetadata();

            using (var ms = new MemoryStream())
            {
                ms.Write(new byte[] { 2, 3 }, 0, 2);

                var sourceRecords = new MetadataRecord[3]
                {
                    new MetadataRecord(3, 5, 10, 0),
                    new MetadataRecord(5, 24252525, 23425, 58581758),
                    new MetadataRecord(long.MaxValue, int.MaxValue, long.MaxValue, int.MaxValue),
                };

                foreach (var record in sourceRecords)
                {
                    source.AddRecord(record);
                }

                source.Write(ms);

                var target = new FileMetadata();
                target.Read(ms);

                var targetRecords = target.Records.ToArray();

                sourceRecords.Should().BeEquivalentTo(targetRecords);
            }
        }
Ejemplo n.º 8
0
        public async Task GivenMetadataRecord_WhenFullLifeCycle_ShouldComplete()
        {
            TestWebsiteHost host = await TestApplication.DefaultHost.GetHost();

            const string id = "meta0001";

            var record = new MetadataRecord
            {
                Id         = id,
                Properties = new[]
                {
                    new KeyValue("key1", "value1"),
                    new KeyValue("key2", "value2"),
                },
            };

            await host.PathFinderClient.Metadata.Delete(record.Id);

            MetadataRecord?response = await host.PathFinderClient.Metadata.Get(record.Id);

            response.Should().BeNull();

            await host.PathFinderClient.Metadata.Set(record);

            MetadataRecord?readResponse = await host.PathFinderClient.Metadata.Get(record.Id);

            readResponse.Should().NotBeNull();

            await host.PathFinderClient.Metadata.Delete(record.Id);

            readResponse = await host.PathFinderClient.Metadata.Get(record.Id);

            readResponse.Should().BeNull();
        }
Ejemplo n.º 9
0
 public static void Write(this NativeWriter writer, MetadataRecord record)
 {
     if (record != null)
         writer.WriteUnsigned((uint)record.HandleType | (uint)(record.HandleOffset << 8));
     else
         writer.WriteUnsigned(0);
 }
Ejemplo n.º 10
0
        private static string MethodToString(MetadataRecord record)
        {
            if (record.IsNull)
            {
                return("<none>");
            }

            switch (record.Type)
            {
            case MetadataRecordType.MethodDef:
                var methodDef = record.MethodDef;
                var parent    = methodDef.FindDeclaringType();
                return($"def({parent.Namespace}.{parent.Name}::{methodDef.Name})");

            case MetadataRecordType.MemberRef:
                var memberRef = record.MemberRef;
                return
                    ($"ref({TypeToString(memberRef.Class)}::{memberRef.Name}|{SignatureToString(memberRef.Signature)})");

            case MetadataRecordType.MethodSpec:
                var methodSpec = record.MethodSpec;
                return($"spec({SignatureToString(methodSpec.Signature)})");
            }

            throw new InvalidOperationException("Unknown method token");
        }
Ejemplo n.º 11
0
        public async Task Set(MetadataRecord metadataRecord)
        {
            metadataRecord.VerifyNotNull(nameof(metadataRecord));

            HttpResponseMessage response = await _httpClient.PostAsJsonAsync("api/metadata", metadataRecord);

            response.EnsureSuccessStatusCode();
        }
Ejemplo n.º 12
0
 public Metadata(MetadataRecord metadata)
 {
     MetadataRecord   = metadata;
     Instance         = metadata.PlantCode;
     PointID          = metadata.HistorianID;
     PointName        = metadata.Name;
     PointDescription = metadata.Description;
 }
Ejemplo n.º 13
0
        public async Task <IActionResult> Post([FromBody] MetadataRecord record)
        {
            record.Prepare();

            await _metadataPathService.Set(record);

            return(Ok());
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Returns an <see cref="MetadataRecord"/> object for this <see cref="SerializableMetadataRecord"/>.
        /// </summary>
        /// <returns>An <see cref="MetadataRecord"/> object.</returns>
        public MetadataRecord Deflate()
        {
            MetadataRecord metadataRecord = new MetadataRecord(HistorianID, MetadataFileLegacyMode.Enabled);

            metadataRecord.GeneralFlags.DataType = (DataType)DataType;
            metadataRecord.Name                         = Name;
            metadataRecord.Synonym1                     = Synonym1;
            metadataRecord.Synonym2                     = Synonym2;
            metadataRecord.Synonym3                     = Synonym3;
            metadataRecord.Description                  = Description;
            metadataRecord.HardwareInfo                 = HardwareInfo;
            metadataRecord.Remarks                      = Remarks;
            metadataRecord.PlantCode                    = PlantCode;
            metadataRecord.UnitNumber                   = UnitNumber;
            metadataRecord.SystemName                   = SystemName;
            metadataRecord.SourceID                     = SourceID;
            metadataRecord.GeneralFlags.Enabled         = Enabled;
            metadataRecord.ScanRate                     = ScanRate;
            metadataRecord.CompressionMinTime           = CompressionMinTime;
            metadataRecord.CompressionMaxTime           = CompressionMaxTime;
            metadataRecord.SecurityFlags.ChangeSecurity = ChangeSecurity;
            metadataRecord.SecurityFlags.AccessSecurity = AccessSecurity;
            metadataRecord.GeneralFlags.StepCheck       = StepCheck;
            metadataRecord.GeneralFlags.AlarmEnabled    = AlarmEnabled;
            metadataRecord.AlarmFlags.Value             = AlarmFlags;
            metadataRecord.GeneralFlags.AlarmToFile     = AlarmToFile;
            metadataRecord.GeneralFlags.AlarmByEmail    = AlarmByEmail;
            metadataRecord.GeneralFlags.AlarmByPager    = AlarmByPager;
            metadataRecord.GeneralFlags.AlarmByPhone    = AlarmByPhone;
            metadataRecord.AlarmEmails                  = AlarmEmails;
            metadataRecord.AlarmPagers                  = AlarmPagers;
            metadataRecord.AlarmPhones                  = AlarmPhones;
            if (DataType == 0)
            {
                // Analog properties.
                metadataRecord.AnalogFields.EngineeringUnits = EngineeringUnits;
                metadataRecord.AnalogFields.LowWarning       = LowWarning;
                metadataRecord.AnalogFields.HighWarning      = HighWarning;
                metadataRecord.AnalogFields.LowAlarm         = LowAlarm;
                metadataRecord.AnalogFields.HighAlarm        = HighAlarm;
                metadataRecord.AnalogFields.LowRange         = LowRange;
                metadataRecord.AnalogFields.HighRange        = HighRange;
                metadataRecord.AnalogFields.CompressionLimit = CompressionLimit;
                metadataRecord.AnalogFields.ExceptionLimit   = ExceptionLimit;
                metadataRecord.AnalogFields.DisplayDigits    = DisplayDigits;
                metadataRecord.AnalogFields.AlarmDelay       = AlarmDelay;
            }
            else if (DataType == 1)
            {
                // Digital properties.
                metadataRecord.DigitalFields.SetDescription   = SetDescription;
                metadataRecord.DigitalFields.ClearDescription = ClearDescription;
                metadataRecord.DigitalFields.AlarmState       = AlarmState;
                metadataRecord.DigitalFields.AlarmDelay       = AlarmDelay;
            }

            return(metadataRecord);
        }
Ejemplo n.º 15
0
        public async Task Set(MetadataRecord metadataRecord, CancellationToken token = default)
        {
            _logger.LogTrace($"{nameof(Set)}: Id={metadataRecord.Id}");

            metadataRecord
            .VerifyNotNull(nameof(metadataRecord))
            .Prepare();

            await _httpClient.PostAsJsonAsync("api/metadata", metadataRecord, token);
        }
Ejemplo n.º 16
0
        byte[] IArchive.ReadMetaData(int historianID)
        {
            MetadataRecord record = ReadMetadataRecord(historianID);

            if (record != null)
            {
                return(record.BinaryImage());
            }

            return(null);
        }
Ejemplo n.º 17
0
        public async Task Set(MetadataRecord record, CancellationToken token)
        {
            record
            .VerifyNotNull(nameof(record))
            .VerifyAssert(x => x.Id == base.ActorKey.Value, "Id mismatch");

            _logger.LogTrace($"{nameof(Set)}: Writing {record}");
            await _container.Set(record, token);

            _recordCache.Set(record);
        }
Ejemplo n.º 18
0
        byte[] IArchive.ReadMetaDataSummary(int historianID)
        {
            MetadataRecord record = ReadMetadataRecord(historianID);

            if ((object)record != null)
            {
                return(record.Summary.BinaryImage());
            }

            return(null);
        }
Ejemplo n.º 19
0
        public bool InsertMetadataRow(MetadataRecord record)
        {
            var qs = RentQueries();

            try
            {
                return(qs.InsertMetadataRow(record));
            }
            finally
            {
                ReturnQueries(qs);
            }
        }
Ejemplo n.º 20
0
        protected override void ComputeMetadata(NodeFactory factory,
                                                out byte[] metadataBlob,
                                                out List <MetadataMapping <MetadataType> > typeMappings,
                                                out List <MetadataMapping <MethodDesc> > methodMappings,
                                                out List <MetadataMapping <FieldDesc> > fieldMappings,
                                                out List <MetadataMapping <MethodDesc> > stackTraceMapping)
        {
            var ms     = new MemoryStream();
            var writer = new MetadataWriter();

            // Run an empty transform pass. This doesn't matter. We just need an instance of the MetadataTransform.
            var transformed             = MetadataTransform.Run(new Policy(), Array.Empty <ModuleDesc>());
            MetadataTransform transform = transformed.Transform;

            // Generate entries in the blob for methods that will be necessary for stack trace purposes.
            var stackTraceRecords = new List <KeyValuePair <MethodDesc, MetadataRecord> >();

            foreach (var methodBody in GetCompiledMethodBodies())
            {
                MethodDesc method = methodBody.Method;

                MethodDesc typicalMethod = method.GetTypicalMethodDefinition();

                if (!_stackTraceEmissionPolicy.ShouldIncludeMethod(method))
                {
                    continue;
                }

                MetadataRecord record = CreateStackTraceRecord(transform, method);

                stackTraceRecords.Add(new KeyValuePair <MethodDesc, MetadataRecord>(
                                          method,
                                          record));

                writer.AdditionalRootRecords.Add(record);
            }

            writer.Write(ms);
            metadataBlob = ms.ToArray();

            typeMappings      = new List <MetadataMapping <MetadataType> >();
            methodMappings    = new List <MetadataMapping <MethodDesc> >();
            fieldMappings     = new List <MetadataMapping <FieldDesc> >();
            stackTraceMapping = new List <MetadataMapping <MethodDesc> >();

            // Generate stack trace metadata mapping
            foreach (var stackTraceRecord in stackTraceRecords)
            {
                stackTraceMapping.Add(new MetadataMapping <MethodDesc>(stackTraceRecord.Key, writer.GetRecordHandle(stackTraceRecord.Value)));
            }
        }
Ejemplo n.º 21
0
        private void EnsureMetadataGenerated()
        {
            if (_metadataBlob != null)
            {
                return;
            }

            var transformed = MetadataTransform.Run(new DummyMetadataPolicy(this), _modulesSeen);

            // TODO: DeveloperExperienceMode: Use transformed.Transform.HandleType() to generate
            //       TypeReference records for _typeDefinitionsGenerated that don't have metadata.
            //       (To be used in MissingMetadataException messages)

            // Generate metadata blob
            var writer = new MetadataWriter();

            writer.ScopeDefinitions.AddRange(transformed.Scopes);
            var ms = new MemoryStream();

            writer.Write(ms);
            _metadataBlob = ms.ToArray();

            // Generate type definition mappings
            foreach (var definition in _typeDefinitionsGenerated)
            {
                MetadataRecord record = transformed.GetTransformedTypeDefinition(definition);

                // Reflection requires that we maintain type identity. Even if we only generated a TypeReference record,
                // if there is an EEType for it, we also need a mapping table entry for it.
                if (record == null)
                {
                    record = transformed.GetTransformedTypeReference(definition);
                }

                if (record != null)
                {
                    _typeMappings.Add(new MetadataMapping <MetadataType>(definition, writer.GetRecordHandle(record)));
                }
            }

            foreach (var method in _methodsGenerated)
            {
                MetadataRecord record = transformed.GetTransformedMethodDefinition(method.GetTypicalMethodDefinition());

                if (record != null)
                {
                    _methodMappings.Add(new MetadataMapping <MethodDesc>(method, writer.GetRecordHandle(record)));
                }
            }
        }
Ejemplo n.º 22
0
        private void CreateMetadataTemplate(int index, string file)
        {
            var record = new MetadataRecord
            {
                Id         = $"Metadata_{index}",
                Properties = new[]
                {
                    new KeyValue("key1", "value1"),
                    new KeyValue("key2", "value2"),
                },
            };

            File.WriteAllText(file, _json.Serialize(record));
            _logger.LogInformation($"Create json template {file} for Metadata");
        }
Ejemplo n.º 23
0
Archivo: Program.cs Proyecto: zuvys/dlr
        private static string ImplementationToString(MetadataRecord impl)
        {
            if (impl.IsFileDef)
            {
                return("file(" + impl.FileDef.Name + ")");
            }

            if (impl.IsAssemblyRef)
            {
                return("assembly(" + impl.AssemblyRef.Name + ")");
            }

            Debug.Assert(impl.IsNull);
            return("<no-impl>");
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Formats an <see cref="MetadataRecord"/> as an 80-byte field ready to be written to disk.
 /// </summary>
 /// <param name="record">Instance to be formatted.</param>
 /// <returns>A byte array containing the binary representation of the record.</returns>
 internal static byte[] ToRawRecord(MetadataRecord record)
 {
     byte[] Record = Encoding.UTF8.GetBytes(new string(' ', 80));
     if (record.Name.Length > 8)
     {
         throw new FITSFormatException("Keyword names must be at most 8 characters long.");
     }
     if (record.DataString.Length > 71)
     {
         throw new FITSFormatException("Keyword values must be at most 71 characters long.");
     }
     Encoding.UTF8.GetBytes(record.Name, 0, record.Name.Length, Record, 0);
     Record[8] = (byte)'=';
     Encoding.UTF8.GetBytes(record.DataString, 0, record.DataString.Length, Record, 9);
     return(Record);
 }
        public void CouldInsertAndSelectMetadata()
        {
            var path    = TestUtils.GetPath(clear: true);
            var storage = new SQLiteStorage($@"Filename={Path.Combine(path, "metadatastorage.db")}");

            var md1 = new MetadataRecord()
            {
                PK          = "test1:/md1",
                Metadata    = new Metadata("md1"),
                RepoId      = 2,
                ContainerId = 1
            };

            var md2 = new MetadataRecord()
            {
                PK          = "test1:/md2",
                Metadata    = new Metadata("md2"),
                RepoId      = 2,
                ContainerId = 2
            };

            var txn = storage.BeginConcurrent();

            var result = storage.InsertMetadataRow(md1);

            Assert.IsTrue(result);
            result = storage.InsertMetadataRow(md2);
            Assert.IsTrue(result);
            result = storage.InsertMetadataRow(md2);
            Assert.IsFalse(result);

            txn.RawCommit();

            var mdList = storage.FindMetadata("test1:/md");

            Assert.AreEqual(2, mdList.Count);
            Assert.AreEqual("md1", mdList[0].Metadata.Description);
            Assert.AreEqual(2, mdList[0].RepoId);
            Assert.AreEqual(1, mdList[0].ContainerId);

            var mdExact = storage.GetExactMetadata("test1:/md2");

            Assert.AreEqual("md2", mdExact.Metadata.Description);

            storage.Dispose();
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Updates the chart after changes have been made to the chart boundaries or the data displayed in the chart.
        /// </summary>
        public void UpdateChart()
        {
            Cursor   windowCursor = Cursor;
            int      colorIndex   = 0;
            DateTime startTime    = m_xAxis.Minimum ?? TimeTag.MinValue.ToDateTime();
            DateTime endTime      = m_xAxis.Maximum ?? TimeTag.MaxValue.ToDateTime();

            Cursor = Cursors.Wait;

            m_chart.Series.Clear();

            foreach (Tuple <ArchiveReader, MetadataRecord> visiblePoint in m_visiblePoints)
            {
                if (m_chartResolution > 0 && colorIndex < m_lineColors.Count)
                {
                    ArchiveReader            reader = visiblePoint.Item1;
                    MetadataRecord           record = visiblePoint.Item2;
                    IEnumerable <IDataPoint> data   = reader.ReadData(record.HistorianID, startTime, endTime, false);

                    LineSeries series     = new LineSeries();
                    int        interval   = (data.Count() / m_chartResolution) + 1;
                    int        pointCount = 0;

                    // Change how data points are displayed.
                    series.DataPointStyle = new Style(typeof(LineDataPoint));
                    series.DataPointStyle.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(m_lineColors[colorIndex])));
                    series.DataPointStyle.Setters.Add(new Setter(TemplateProperty, new ControlTemplate()));
                    colorIndex++;

                    // Set the title of the series as it will appear in the legend.
                    series.Title = record.Name;

                    // Filter the data to 100 data points.
                    series.ItemsSource          = data.Where(point => (pointCount++ % interval) == 0).Select(point => new DataPointWrapper(point));
                    series.IndependentValuePath = "Time";
                    series.DependentValuePath   = "Value";

                    // Add the series to the chart.
                    m_chart.Series.Add(series);
                }
            }

            UpdateLayout();
            Cursor = windowCursor;
            OnChartUpdated();
        }
Ejemplo n.º 27
0
        // openHistorian 2.0 currently uses the database for its metadata repository - so we just update the database using the
        // provided metadata record as received from the metadata web service interface
        void IArchive.WriteMetaData(int historianID, byte[] metadata)
        {
            MetadataRecord record = new MetadataRecord(historianID, MetadataFileLegacyMode.Enabled, metadata, 0, metadata.Length);

            using (AdoDataConnection database = new AdoDataConnection("systemSettings"))
            {
                IDbConnection connection = database.Connection;

                // TODO: To enable update signal type, associated device, destination historian, etc. - look up key ID values in advance of measurement record update

                // Only updating readily available fields - to make this more useful in the future, will need to update (or add a new) web service metadata format...
                string query = database.ParameterizedQueryString("UPDATE Measurement SET PointTag={0}, SignalReference={1}, AlternateTag={2}, Enabled={3} WHERE HistorianID = {4}", "pointTag", "signalReference", "alternateTag", "enabled", "historianID");

                // Update metadata fields
                connection.ExecuteNonQuery(query, record.Name, record.Synonym1, record.Synonym3, record.GeneralFlags.Enabled, historianID);
            }
        }
        internal void LoadMetadata()
        {
            List<MetadataRecord> metadata = new List<MetadataRecord>();

            MetadataRecord record1 = new MetadataRecord();
            record1.User = "******";
            record1.ComputerName = "PCName";
            DateTime time = DateTime.Now;
            time = time.Date.AddHours(time.Hour).AddMinutes(time.Minute).AddSeconds(time.Second);
            record1.Time = time;
            record1.Arguments.Add(new Tuple<string, string>("input1", "value1"));
            record1.Operation = "TestOperation";
            metadata.Add(record1);

            MetadataRecord record2 = new MetadataRecord();
            record2.User = "******";
            record2.ComputerName = "PCName2";
            record2.Time = time;
            record2.Arguments.Add(new Tuple<string, string>("input12", "value12"));
            record2.Arguments.Add(new Tuple<string, string>("input22", "value22"));
            record2.Operation = "TestOperation2";
            metadata.Add(record2);

            string fileName = FileFunctions.TempoaryOutputFileName(".txt");
            MetadataFunctions.Save(fileName, metadata);

            List<MetadataRecord> loadedMetadata = MetadataFunctions.Load(fileName);

            if (loadedMetadata.Count != 2)
            {
                throw new Exception();
            }

            MetadataRecord loadedRecord1 = loadedMetadata[0];
            MetadataRecord loadedRecord2 = loadedMetadata[1];

            if (!Equal(record1, loadedRecord1))
            {
                throw new Exception();
            }

            if (!Equal(record2, loadedRecord2))
            {
                throw new Exception();
            }
        }
Ejemplo n.º 29
0
 private static void DumpGenericParameters(MetadataTableView genericParams, MetadataRecord owner)
 {
     foreach (GenericParamDef gp in genericParams)
     {
         _output.WriteLine("  generic parameter #{0}: {1}({2})", gp.Index, gp.Name, gp.Attributes);
         Debug.Assert(gp.Owner.Equals(owner));
         foreach (GenericParamConstraint gpc in gp.Constraints)
         {
             _output.WriteLine("    constraint {0}", TypeToString(gpc.Constraint));
             Debug.Assert(gpc.Owner.Record.Equals(gp.Record));
         }
         if (Detailed)
         {
             DumpCustomAttributes(gp.CustomAttributes, "    ");
         }
     }
 }
Ejemplo n.º 30
0
        private List <MetadataRecord> GetMetadata()
        {
            Ticks operationTime;
            Ticks operationStartTime;

            // Load historian meta-data
            ShowMessage(">>> Loading source connection metadata...");

            operationStartTime = DateTime.UtcNow.Ticks;
            List <MetadataRecord> metadata = MetadataRecord.Query(m_settings.HostAddress, m_settings.MetadataPort, m_settings.MetadataTimeout);

            operationTime = DateTime.UtcNow.Ticks - operationStartTime;

            ShowMessage("*** Metadata Load Complete ***");
            ShowMessage($"Total metadata load time {operationTime.ToElapsedTimeString(3)}...");

            // Parse meta-data expression
            ShowMessage(">>> Processing filter expression for metadata...");
            operationStartTime = DateTime.UtcNow.Ticks;
            MeasurementKey[]      inputKeys   = AdapterBase.ParseInputMeasurementKeys(MetadataRecord.Metadata, false, m_settings.PointList, "MeasurementDetail");
            List <ulong>          pointIDList = inputKeys.Select(key => (ulong)key.ID).ToList();
            List <MetadataRecord> records     = new List <MetadataRecord>();

            foreach (ulong pointID in pointIDList)
            {
                MetadataRecord record = metadata.FirstOrDefault(md => md.PointID == pointID);

                if ((object)record != null)
                {
                    records.Add(record);
                }
            }

            operationTime = DateTime.UtcNow.Ticks - operationStartTime;

            ShowMessage($">>> Historian read will be for {pointIDList.Count:N0} points based on provided meta-data expression.");

            ShowMessage("*** Filter Expression Processing Complete ***");
            ShowMessage($"Total filter expression processing time {operationTime.ToElapsedTimeString(3)}...");

            return(records);
        }
Ejemplo n.º 31
0
        private async Task WriteRecord(string recordType, string json, CancellationToken token)
        {
            switch (recordType)
            {
            case nameof(LinkRecord):
                LinkRecord linkRecord = _json.Deserialize <LinkRecord>(json);
                await _linkContainer.Set(linkRecord, token);

                break;

            case nameof(MetadataRecord):
                MetadataRecord metadataRecord = _json.Deserialize <MetadataRecord>(json);
                await _metadataContainer.Set(metadataRecord, token);

                break;

            default:
                throw new ArgumentException($"Unknown record type for importing, recordType={recordType}");
            }
        }
Ejemplo n.º 32
0
        private TypeReference GetNestedReferenceParent(Cts.MetadataType entity)
        {
            // This special code deals with the metadata format requirement saying that
            // nested type *references* need to have a type *reference* as their containing type.
            // This is potentially in conflict with our other rule that says to always resolve
            // references to their definition records (we are avoiding emitting references
            // to things that have a definition within the same blob to save space).

            Cts.MetadataType containingType        = (Cts.MetadataType)entity.ContainingType;
            MetadataRecord   parentRecord          = HandleType(containingType);
            TypeReference    parentReferenceRecord = parentRecord as TypeReference;

            if (parentReferenceRecord != null)
            {
                // Easy case - parent type doesn't have a definition record.
                return(parentReferenceRecord);
            }

            // Parent has a type definition record. We need to make a new record that's a reference.
            // We don't bother with interning these because this will be rare and metadata writer
            // will do the interning anyway.
            Debug.Assert(parentRecord is TypeDefinition);

            parentReferenceRecord = new TypeReference
            {
                TypeName = HandleString(containingType.Name),
            };

            if (containingType.ContainingType != null)
            {
                parentReferenceRecord.ParentNamespaceOrType = GetNestedReferenceParent(containingType);
            }
            else
            {
                parentReferenceRecord.ParentNamespaceOrType = HandleNamespaceReference(containingType.Module, containingType.Namespace);
            }

            return(parentReferenceRecord);
        }
        private static bool Equal(MetadataRecord left, MetadataRecord right)
        {
            if (false
                || right.User != left.User
                || right.ComputerName != left.ComputerName
                || right.Time != left.Time
                || right.Operation != left.Operation
                || right.Arguments.Count != left.Arguments.Count
                )
            {
                throw new Exception();
            }

            for (int argumentIndex = 0; argumentIndex < right.Arguments.Count; argumentIndex++)
            {
                Tuple<string, string> record1Argument = left.Arguments[argumentIndex];
                Tuple<string, string> loadedRecord1Argument = right.Arguments[argumentIndex];
                if (loadedRecord1Argument.Item1 != record1Argument.Item1 || loadedRecord1Argument.Item2 != record1Argument.Item2)
                {
                    throw new Exception();
                }
            }

            return true;
        }
        internal void ValuesWritten()
        {
            // also the operation

            /// verifies that the user name, and pc are included in the metadata
            /// this includes the user name,
            /// pc name,
            /// anything else that looks interesting
            ///

            MetadataRecord record = new MetadataRecord();
            record.User = "******";
            record.ComputerName = "PCName";
            DateTime time = DateTime.Now;
            string timeString = time.ToShortDateString() + " " + time.ToLongTimeString();
            record.Time = time;
            record.Arguments.Add(new Tuple<string, string>("input1", "value1"));
            record.Operation = "TestOperation";

            List<MetadataRecord> metadata = new List<MetadataRecord>();
            metadata.Add(record);

            string fileName = FileFunctions.TempoaryOutputFileName(".txt");
            MetadataFunctions.Save(fileName, metadata);

            string metadataFileName = MetadataFunctions.FileName(fileName);
            if (!File.Exists(metadataFileName))
            {
                throw new Exception();
            }
            string text = File.ReadAllText(metadataFileName);

            if (!text.Contains("TestUser")
                || !text.Contains("PCName")
                || !text.Contains(timeString)
                || !text.Contains("input1")
                || !text.Contains("value1")
                || !text.Contains("TestOperation")
                )
            {
                throw new Exception();
            }
        }