partial void Start() { this.accelerometer = new Meter { TimeBetweenUpdates = TimeSpan.FromMilliseconds((long)this.Interval) }; this.accelerometer.CurrentValueChanged += this.AccelerometerOnCurrentValueChanged; this.accelerometer.Start(); }
public object Post(Meter request) { // Retrieve PK. var unitNumber = request.UnitNumber; // Retrieve obj from IMDB based on PK. var imdb = (InMemoryDB) Session[unitNumber]; if (imdb == null) { imdb = new InMemoryDB(); } if (request.MeterReading > 0) { imdb.CurrentMeterReading = request.MeterReading; } if (request.FuelPurchaseAmount > 0) { imdb.TotalFuelPurchaseAmount += request.FuelPurchaseAmount; } // Save obj to IMDB. Session[unitNumber] = imdb; // Return repsonse obj. return new MeterResponse {Id = 1}; }
public Parser(Meter meter) { // Add the regex patterns and the callback functions for a succesfull match filters = new List<Filter>(); // damage filters filters.Add(new Filter(Properties.Resources.FILTER_DIRECT_DAMAGE_SKILL, new Filter.delegate_callback(meter.commit_damage), true)); filters.Add(new Filter(Properties.Resources.FILTER_DIRECT_DAMAGE, new Filter.delegate_callback(meter.commit_damage), true)); // damage overtime-effects filters filters.Add(new Filter(Properties.Resources.FILTER_DOT, new Filter.delegate_callback(meter.commit_dot_effect), true)); // healing filters filters.Add(new Filter(Properties.Resources.FILTER_DIRECT_HEALING_SKILL, new Filter.delegate_callback(meter.commit_healing), true)); filters.Add(new Filter(Properties.Resources.FILTER_DIRECT_HEALING, new Filter.delegate_callback(meter.commit_healing), true)); // healing over-time effects filters.Add(new Filter(Properties.Resources.FILTER_HOT_1, new Filter.delegate_callback(meter.commit_hot_effect), true)); filters.Add(new Filter(Properties.Resources.FILTER_HOT_2, new Filter.delegate_callback(meter.commit_hot_effect), true)); // pet summons filters.Add(new Filter(Properties.Resources.FILTER_SUMMON_1, new Filter.delegate_callback(meter.summon_pet), true)); filters.Add(new Filter(Properties.Resources.FILTER_SUMMON_2, new Filter.delegate_callback(meter.summon_pet), true)); // Group-awareness filters filters.Add(new Filter(Properties.Resources.FILTER_PLAYER_JOIN_GROUP, new Filter.delegate_callback(meter.group_message))); filters.Add(new Filter(Properties.Resources.FILTER_PLAYER_LEFT_GROUP, new Filter.delegate_callback(meter.member_left))); filters.Add(new Filter(Properties.Resources.FILTER_PLAYER_KICKED, new Filter.delegate_callback(meter.member_left))); filters.Add(new Filter(Properties.Resources.FILTER_GROUP_DISBAND, new Filter.delegate_callback(meter.group_disbanded))); filters.Add(new Filter(Properties.Resources.FILTER_GROUP_MESSAGE, new Filter.delegate_callback(meter.group_message))); filters.Add(new Filter(Properties.Resources.FILTER_SELF_MESSAGE, new Filter.delegate_callback(meter.self_message))); }
public void TestUnitConversion() { Velocity<Meter, Second> tenMetersPerSecond = new Meter(20) / new Second(2); Assert.AreEqual(10, tenMetersPerSecond.Value); Acceleration<Meter, Second> fiveMetersPerSecondPerSecond = tenMetersPerSecond / new Second(2); Assert.AreEqual(5, fiveMetersPerSecondPerSecond.Value); }
partial void Stop() { if (this.accelerometer != null) { this.accelerometer.CurrentValueChanged -= this.AccelerometerOnCurrentValueChanged; this.accelerometer.Stop(); this.accelerometer = null; } }
private void FromMeter_Load(object sender, EventArgs e) { meter = FormMain.meter; if (threadReadMeter != null) { threadReadMeter.Abort(); } threadReadMeter = new Thread(new ThreadStart(ProcReadMeterVal)); threadReadMeter.IsBackground = true; threadReadMeter.Start(); }
public StreamCopier(IStreamProvider streamProvider, bool autoCloseSource, bool autoCloseDestination, int bufferSize) { this.streamProvider = streamProvider; this.autoCloseSource = autoCloseSource; this.autoCloseDestination = autoCloseDestination; buffer = new byte[bufferSize > 0 ? bufferSize : DefaultBufferSize]; bytesReadMeter = new BytesReadMeter(this); bytesWrittenMeter = new BytesReadMeter(this); sourceLength = this.streamProvider.GetSourceLength(); }
protected override void ImplementUserControl() { Meter meter = new Meter(); meter.Border = NationalInstruments.UI.Border.ThinFrame3D; meter.Location = new System.Drawing.Point(59, 65); meter.Name = "meter"; meter.Size = new System.Drawing.Size(214, 100); meter.TabIndex = 0; controlHandle = meter; InitControl(controlHandle); initContextMenuStrip(); }
private List <D3Series> QueryAnalyticData(Meter meter, Event evt, string analytic, int order, double Trc, int harmonic) { DataGroup dataGroup = OpenSEEBaseController.QueryDataGroup(evt.ID, meter); VICycleDataGroup viCycleDataGroup = OpenSEEBaseController.QueryVICycleDataGroup(evt.ID, meter); AnalyticController controller = new AnalyticController(); if (analytic == "FirstDerivative") { return(controller.GetFirstDerivativeLookup(dataGroup, viCycleDataGroup)); } if (analytic == "ClippedWaveforms") { return(controller.GetClippedWaveformsLookup(dataGroup)); } if (analytic == "Frequency") { return(controller.GetFrequencyLookup(new VIDataGroup(dataGroup))); } if (analytic == "Impedance") { return(controller.GetImpedanceLookup(viCycleDataGroup)); } if (analytic == "Power") { return(controller.GetPowerLookup(viCycleDataGroup)); } if (analytic == "RemoveCurrent") { return(controller.GetRemoveCurrentLookup(dataGroup)); } if (analytic == "MissingVoltage") { return(controller.GetMissingVoltageLookup(dataGroup)); } if (analytic == "LowPassFilter") { return(controller.GetLowPassFilterLookup(dataGroup, order)); } if (analytic == "HighPassFilter") { return(controller.GetHighPassFilterLookup(dataGroup, order)); } if (analytic == "SymmetricalComponents") { return(controller.GetSymmetricalComponentsLookup(viCycleDataGroup)); } if (analytic == "Unbalance") { return(controller.GetUnbalanceLookup(viCycleDataGroup)); } if (analytic == "Rectifier") { return(controller.GetRectifierLookup(new VIDataGroup(dataGroup), Trc)); } if (analytic == "RapidVoltageChange") { return(controller.GetRapidVoltageChangeLookup(viCycleDataGroup)); } if (analytic == "THD") { return(controller.GetTHDLookup(dataGroup, true)); } if (analytic == "SpecifiedHarmonic") { return(controller.GetSpecifiedHarmonicLookup(dataGroup, harmonic, true)); } if (analytic == "OverlappingWaveform") { return(controller.GetOverlappingWaveformLookup(dataGroup)); } return(new List <D3Series>()); }
public ActionResult Save(int?id, string meterId, decimal?amount, string SerialNUM) { int rc; Meter[] meter = Meter.GetMeters(new MeterParameters { Meterid = meterId }, out rc); //user of meter Customer customer = (Session["customer"] as Customer); CashCard [] cashCards = CashCard.GetCashCards(new CashCardParameters { SerialNumber = SerialNUM }, out rc); CashCard cashCard = new CashCard(cashCards[0].Id); Customer customer1 = new Customer(meter[0].UserId.Value); if (Session["customer"] != null) { if (customer.Id == meter[0].UserId && customer.CardId == cashCard.Id)//for himself from his card { SMS sms = new SMS(); sms.To_number = customer.Telephone; sms.Msg = $"أهلا وسهلا بك أنت تقوم بشحن {amount} الى عدادك الان"; string status = sms.Send(); sms.SaveData(); if (status == "OK") { Topup topup = new Topup(id, meterId, amount, SerialNUM); int result; result = topup.SaveData(); ViewBag.result = result; } else { return(RedirectToAction("Save", "Tpoups")); } } else if (customer.Id == meter[0].UserId && customer.CardId != cashCard.Id) //for himself from another card { Customer[] customer2 = Customer.GetCustomers(new CustomerParameters { CardId = cashCard.Id }, out rc); SMS sms = new SMS(); sms.To_number = customer2[0].Telephone; sms.Msg = $" يحاول {customer.Name} شحن عداده باستخدام البطاقة الخاصة بك بقيمة {amount}"; string status = sms.Send(); sms.SaveData(); if (status == "OK") { Topup topup = new Topup(id, meterId, amount, SerialNUM); int result; result = topup.SaveData(); ViewBag.result = result; } else { return(RedirectToAction("Save", "Topups")); } } else if (customer.Id != meter[0].UserId && customer.CardId == cashCard.Id)//for another from his card { SMS sms = new SMS(); sms.To_number = customer1.Telephone; sms.Msg = $"يحاول {customer.Name} شحن عدادك بقيمة {amount}"; string status = sms.Send(); sms.SaveData(); SMS sms1 = new SMS(); sms1.To_number = customer.Telephone; sms1.Msg = $"يحاول {customer1.Name} شحن عداده باستخدام بطاقتك بقيمة {amount}"; string status1 = sms1.Send(); sms1.SaveData(); if (status == "OK" && status1 == "OK") { Topup topup = new Topup(id, meterId, amount, SerialNUM); int result; result = topup.SaveData(); ViewBag.result = result; } else { return(RedirectToAction("Save", "Topups")); } } else if (customer.Id != meter[0].UserId && customer.CardId != cashCard.Id && customer1.CardId != cashCard.Id)//for another from another card { int rrc; Customer[] customer2 = Customer.GetCustomers(new CustomerParameters { CardId = cashCard.Id }, out rrc); SMS sms = new SMS(); sms.To_number = customer2[0].Telephone; sms.Msg = $"يحاول {customer1.Name} شحن عداده بقيمة {amount} باستخدام بطاقتك"; string status = sms.Send(); sms.SaveData(); SMS sms1 = new SMS(); sms1.To_number = customer1.Telephone; sms1.Msg = $"يحاول {customer.Name} شحن عدادك بقيمة {amount} باستخدام بطاقة {customer2[0].Name}"; string status1 = sms1.Send(); sms1.SaveData(); if (status == "OK" && status1 == "OK") { Topup topup = new Topup(id, meterId, amount, SerialNUM); int result; result = topup.SaveData(); ViewBag.result = result; } else { return(RedirectToAction("Save", "Topups")); } } else if (customer.Id != meter[0].UserId && customer.CardId != cashCard.Id && customer1.CardId == cashCard.Id)//for another from the another card { SMS sms = new SMS(); sms.To_number = customer1.Telephone; sms.Msg = $"يحاول {customer.Name} شحن عدادك باستخدام بطاقتك"; string status = sms.Send(); sms.SaveData(); SMS sms1 = new SMS(); sms1.To_number = customer.Telephone; sms1.Msg = $"أهلا وسهلا بك أنت تحاول الان شحن عداد {customer1.Name} باستخدام بطاقته {customer1.CardId}"; string status1 = sms1.Send(); sms1.SaveData(); if (status == "OK" && status1 == "OK") { Topup topup = new Topup(id, meterId, amount, SerialNUM); int result; result = topup.SaveData(); ViewBag.result = result; } else { return(RedirectToAction("Save", "Topups")); } } return(View()); } else { return(RedirectToAction("Save", "Topups")); } }
public void ShouldCreateBlankMeter() { var meter = new Meter("thing", TimeUnit.Seconds); Assert.That(meter.Count, Is.EqualTo(0)); }
public void ViewToSelectTagKeys() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List <Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { "name" }, Name = "NameOnly" }) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { "size" }, Name = "SizeOnly" }) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { }, Name = "NoTags" }) .AddInMemoryExporter(exportedItems) .Build(); var counter = meter.CreateCounter <long>("FruitCounter"); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large")); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(3, exportedItems.Count); var metric = exportedItems[0]; Assert.Equal("NameOnly", metric.Name); List <MetricPoint> metricPoints = new List <MetricPoint>(); foreach (ref var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // Only one point expected "apple" Assert.Single(metricPoints); metric = exportedItems[1]; Assert.Equal("SizeOnly", metric.Name); metricPoints.Clear(); foreach (ref var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // 3 points small,medium,large expected Assert.Equal(3, metricPoints.Count); metric = exportedItems[2]; Assert.Equal("NoTags", metric.Name); metricPoints.Clear(); foreach (ref var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // Single point expected. Assert.Single(metricPoints); }
private Channel ParseChannel(Meter meter, GSF.PQDIF.Logical.ChannelDefinition channeldef, AdoDataConnection connection) { Channel channel = new Channel(); channel.MeterID = meter.ID; channel.Name = channeldef.ChannelName; GSF.PQDIF.Logical.QuantityMeasured quantity = channeldef.QuantityMeasured; Guid quantityType = channeldef.QuantityTypeID; GSF.PQDIF.Logical.Phase phase = channeldef.Phase; if (isRMS(quantityType)) { channel.SignalType = SignalType.RMS; } else if (isPOW(quantityType)) { channel.SignalType = SignalType.PointOnWave; } else { channel.SignalType = SignalType.other; } Boolean isV = quantity == QuantityMeasured.Voltage; Boolean isI = quantity == QuantityMeasured.Current; Boolean isA = (phase == Phase.AN) || (phase == Phase.AB); Boolean isB = (phase == Phase.BN) || (phase == Phase.BC); Boolean isC = (phase == Phase.CN) || (phase == Phase.CA); Boolean isN = phase == Phase.Residual; string measurementname = MeasurementType.other; if (isV && isA) { measurementname = MeasurementType.VoltageA; } else if (isV && isB) { measurementname = MeasurementType.VoltageB; } else if (isV && isC) { measurementname = MeasurementType.VoltageC; } else if (isI && isA) { measurementname = MeasurementType.CurrentA; } else if (isI && isB) { measurementname = MeasurementType.CurrentB; } else if (isI && isC) { measurementname = MeasurementType.CurrentC; } else if (isV && isN) { measurementname = MeasurementType.other; } else if (isI && isN) { measurementname = MeasurementType.other; } GSF.Data.Model.TableOperations <Channel> channelTable = new GSF.Data.Model.TableOperations <Channel>(connection); channel.MeasurementType = measurementname; channelTable.AddNewRecord(channel); channel.ID = ModelID.GetID <Channel>(connection); return(channel); }
public ThreadPoolEventsListener(IStats stats, ILogger <EventSourceListener> logger = null) : base(stats) { _logger = logger; availableThreads = Meter.CreateInt64Measure($"clr.threadpool.available"); }
/// <summary> /// Calculates the closest point on the route relative to the given coordinate. /// </summary> /// <returns></returns> public bool ProjectOn(GeoCoordinate coordinates, out GeoCoordinate projectedCoordinates, out int entryIndex, out Meter distanceFromStart, out Second timeFromStart) { double distance = double.MaxValue; distanceFromStart = 0; timeFromStart = 0; double currentDistanceFromStart = 0; projectedCoordinates = null; entryIndex = -1; // loop over all points and try to project onto the line segments. GeoCoordinate projected; double currentDistance; var points = this.GetPoints(); for (int idx = 0; idx < points.Count - 1; idx++) { var line = new GeoCoordinateLine(points[idx], points[idx + 1], true, true); var projectedPoint = line.ProjectOn(coordinates); if (projectedPoint != null) { // there was a projected point. projected = new GeoCoordinate(projectedPoint[1], projectedPoint[0]); currentDistance = coordinates.Distance(projected); if (currentDistance < distance) { // this point is closer. projectedCoordinates = projected; entryIndex = idx; distance = currentDistance; // calculate distance/time. double localDistance = projected.DistanceReal(points[idx]).Value; distanceFromStart = currentDistanceFromStart + localDistance; if (this.HasTimes && idx > 0) { // there should be proper timing information. double timeToSegment = this.Segments[idx].Time; double timeToNextSegment = this.Segments[idx + 1].Time; timeFromStart = timeToSegment + ((timeToNextSegment - timeToSegment) * (localDistance / line.LengthReal.Value)); } } } // check first point. projected = points[idx]; currentDistance = coordinates.Distance(projected); if (currentDistance < distance) { // this point is closer. projectedCoordinates = projected; entryIndex = idx; distance = currentDistance; distanceFromStart = currentDistanceFromStart; if (this.HasTimes) { // there should be proper timing information. timeFromStart = this.Segments[idx].Time; } } // update distance from start. currentDistanceFromStart = currentDistanceFromStart + points[idx].DistanceReal(points[idx + 1]).Value; } // check last point. projected = points[points.Count - 1]; currentDistance = coordinates.Distance(projected); if (currentDistance < distance) { // this point is closer. projectedCoordinates = projected; entryIndex = points.Count - 1; distance = currentDistance; distanceFromStart = currentDistanceFromStart; if (this.HasTimes) { // there should be proper timing information. timeFromStart = this.Segments[points.Count - 1].Time; } } return(true); }
private void AddUndefinedChannels(MeterDataSet meterDataSet) { List <DataSeries> undefinedDataSeries = meterDataSet.DataSeries .Concat(meterDataSet.Digitals) .Where(dataSeries => (object)dataSeries.SeriesInfo.Channel.Line == null) .ToList(); if (undefinedDataSeries.Count <= 0) { return; } Meter meter = meterDataSet.Meter; if (meter.MeterLines.Count == 0) { Log.Warn($"Unable to automatically add channels to meter {meterDataSet.Meter.Name} because there are no lines associated with that meter."); return; } if (meter.MeterLines.Count > 1) { Log.Warn($"Unable to automatically add channels to meter {meterDataSet.Meter.Name} because there are too many lines associated with that meter."); return; } Line line = meter.MeterLines .Select(meterLine => meterLine.Line) .Single(); foreach (DataSeries series in undefinedDataSeries) { series.SeriesInfo.Channel.LineID = line.ID; } using (AdoDataConnection connection = meterDataSet.CreateDbConnection()) { TableOperations <MeasurementType> measurementTypeTable = new TableOperations <MeasurementType>(connection); TableOperations <MeasurementCharacteristic> measurementCharacteristicTable = new TableOperations <MeasurementCharacteristic>(connection); TableOperations <Phase> phaseTable = new TableOperations <Phase>(connection); TableOperations <SeriesType> seriesTypeTable = new TableOperations <SeriesType>(connection); Dictionary <string, MeasurementType> measurementTypeLookup = undefinedDataSeries .Select(dataSeries => dataSeries.SeriesInfo.Channel.MeasurementType) .DistinctBy(measurementType => measurementType.Name) .Select(measurementType => measurementTypeTable.GetOrAdd(measurementType.Name, measurementType.Description)) .ToDictionary(measurementType => measurementType.Name); Dictionary <string, MeasurementCharacteristic> measurementCharacteristicLookup = undefinedDataSeries .Select(dataSeries => dataSeries.SeriesInfo.Channel.MeasurementCharacteristic) .DistinctBy(measurementCharacteristic => measurementCharacteristic.Name) .Select(measurementCharacteristic => measurementCharacteristicTable.GetOrAdd(measurementCharacteristic.Name, measurementCharacteristic.Description)) .ToDictionary(measurementCharacteristic => measurementCharacteristic.Name); Dictionary <string, Phase> phaseLookup = undefinedDataSeries .Select(dataSeries => dataSeries.SeriesInfo.Channel.Phase) .DistinctBy(phase => phase.Name) .Select(phase => phaseTable.GetOrAdd(phase.Name, phase.Description)) .ToDictionary(phase => phase.Name); Dictionary <string, SeriesType> seriesTypeLookup = undefinedDataSeries .Select(dataSeries => dataSeries.SeriesInfo.SeriesType) .DistinctBy(seriesType => seriesType.Name) .Select(seriesType => seriesTypeTable.GetOrAdd(seriesType.Name, seriesType.Description)) .ToDictionary(seriesType => seriesType.Name); Dictionary <ChannelKey, Channel> channelLookup = meter.Channels .GroupBy(channel => new ChannelKey(channel)) .ToDictionary(grouping => { if (grouping.Count() > 1) { Log.Warn($"Detected duplicate channel key: {grouping.First().ID}"); } return(grouping.Key); }, grouping => grouping.First()); List <Channel> undefinedChannels = undefinedDataSeries .Select(dataSeries => dataSeries.SeriesInfo.Channel) .GroupBy(channel => new ChannelKey(channel)) .Where(grouping => !channelLookup.ContainsKey(grouping.Key)) .Select(grouping => grouping.First()) .ToList(); TableOperations <Channel> channelTable = new TableOperations <Channel>(connection); // Add all undefined channels to the database foreach (Channel channel in undefinedChannels) { string measurementTypeName = channel.MeasurementType.Name; string measurementCharacteristicName = channel.MeasurementCharacteristic.Name; string phaseName = channel.Phase.Name; channel.MeterID = meter.ID; channel.LineID = line.ID; channel.MeasurementTypeID = measurementTypeLookup[measurementTypeName].ID; channel.MeasurementCharacteristicID = measurementCharacteristicLookup[measurementCharacteristicName].ID; channel.PhaseID = phaseLookup[phaseName].ID; channel.Enabled = true; // If the per-unit value was not specified in the input file, // we can obtain the per-unit value from the line configuration // if the channel happens to be an instantaneous or RMS voltage if (!channel.PerUnitValue.HasValue) { if (IsVoltage(channel)) { if (IsLineToNeutral(channel)) { channel.PerUnitValue = (line.VoltageKV * 1000.0D) / Sqrt3; } else if (IsLineToLine(channel)) { channel.PerUnitValue = line.VoltageKV * 1000.0D; } } } channelTable.AddNewRecord(channel); } if (undefinedChannels.Count > 0) { // Refresh the channel lookup to // include all the new channels meter.Channels = null; channelLookup = meter.Channels .GroupBy(channel => new ChannelKey(channel)) .ToDictionary(grouping => grouping.Key, grouping => grouping.First()); } Dictionary <SeriesKey, Series> seriesLookup = meter.Channels .SelectMany(channel => channel.Series) .Where(series => series.SourceIndexes == "") .GroupBy(series => new SeriesKey(series)) .ToDictionary(grouping => { if (grouping.Count() > 1) { Log.Warn($"Detected duplicate series key: {grouping.First().ID}"); } return(grouping.Key); }, grouping => grouping.First()); List <Series> undefinedSeries = undefinedDataSeries .SelectMany(dataSeries => dataSeries.SeriesInfo.Channel.Series) .GroupBy(series => new SeriesKey(series)) .Where(grouping => !seriesLookup.ContainsKey(grouping.Key)) .Select(grouping => grouping.First()) .ToList(); TableOperations <Series> seriesTable = new TableOperations <Series>(connection); // Add all undefined series objects to the database foreach (Series series in undefinedSeries) { ChannelKey channelKey = new ChannelKey(series.Channel); string seriesTypeName = series.SeriesType.Name; series.ChannelID = channelLookup[channelKey].ID; series.SeriesTypeID = seriesTypeLookup[seriesTypeName].ID; series.SourceIndexes = ""; seriesTable.AddNewRecord(series); } if (undefinedSeries.Count > 0) { // Refresh the series lookup to // include all the new series foreach (Channel channel in meter.Channels) { channel.Series = null; } seriesLookup = meter.Channels .SelectMany(channel => channel.Series) .GroupBy(series => new SeriesKey(series)) .ToDictionary(grouping => grouping.Key, grouping => grouping.First()); } // Update all undefined data series to reference the new database objects foreach (DataSeries dataSeries in undefinedDataSeries) { SeriesKey seriesKey = new SeriesKey(dataSeries.SeriesInfo); Series series = seriesLookup[seriesKey]; dataSeries.SeriesInfo = series; } } }
private int Clone(int customerId, Int64 assetId) { // Get original datakey and its associated Meter and MeterMap // Since this exists, these entities should exist also. DataKey dataKey = PemsEntities.DataKeys.FirstOrDefault(m => m.DataKeyId == assetId); if (dataKey != null) { MeterMap meterMap = dataKey.MeterMaps.FirstOrDefault(m => m.DataKeyId == dataKey.DataKeyId); if (meterMap != null) { Meter meter = meterMap.Meter; // Create the new meter that is associated with the datakey type of asset. This is not a meter // but rather a an asset in the meter table that represents a datakey. Meter newMeter = CreateBaseAsset(meter.CustomerID, MeterGroups.Datakey, meter.AreaID); // Create a datakey var clonedItem = new DataKey() { //todo - GTC: DataKeys add datakeyname here when db field is added DataKeyDesc = dataKey.DataKeyDesc, DataKeyId = newMeter.MeterId, //this is auto increment, so it wont save the value, its why we have the datakeyidnumber column. DataKeyIdNumber = newMeter.MeterId, DataKeyType = dataKey.DataKeyType, CustomerID = customerId }; PemsEntities.DataKeys.Add(clonedItem); PemsEntities.SaveChanges(); // Add AssetPending record (new PendingFactory(ConnectionStringName, Now)).SetImportPending( AssetTypeModel.AssetType.DataKey, SetToMidnight(Now), AssetStateType.Current, customerId, clonedItem.DataKeyIdNumber.GetValueOrDefault(), (int)AssetStateType.Pending, (int)OperationalStatusType.Inactive, (int)AssetAreaId.DataKey); // Align clonable meter fields. newMeter.Location = meter.Location; newMeter.DemandZone = meter.DemandZone; newMeter.FreeParkingMinute = meter.FreeParkingMinute; newMeter.MeterGroup = meter.MeterGroup; newMeter.MeterName = meter.MeterName; newMeter.MeterType = meter.MeterType; newMeter.TimeZoneID = meter.TimeZoneID; newMeter.TypeCode = meter.TypeCode; newMeter.WarrantyExpiration = meter.WarrantyExpiration; newMeter.NextPreventativeMaintenance = meter.NextPreventativeMaintenance; // Create meter map for cloned item. // Need a [HousingMaster] HousingMaster housingMaster = PemsEntities.HousingMasters.FirstOrDefault(m => m.HousingName.Equals("Default")); // Create a [MeterMap] entry MeterMap newMeterMap = new MeterMap() { Customerid = newMeter.CustomerID, Areaid = newMeter.AreaID, MeterId = newMeter.MeterId, DataKeyId = clonedItem.DataKeyId, HousingId = housingMaster.HousingId }; PemsEntities.MeterMaps.Add(newMeterMap); PemsEntities.SaveChanges(); newMeterMap.AreaId2 = meterMap.AreaId2; newMeterMap.ZoneId = meterMap.ZoneId; newMeterMap.SubAreaID = meterMap.SubAreaID; newMeterMap.CustomGroup1 = meterMap.CustomGroup1; newMeterMap.CustomGroup2 = meterMap.CustomGroup2; newMeterMap.CustomGroup3 = meterMap.CustomGroup3; newMeterMap.MaintRouteId = meterMap.MaintRouteId; PemsEntities.SaveChanges(); // Set audit records. Audit(newMeter); Audit(newMeterMap); Audit(clonedItem); return(clonedItem.DataKeyIdNumber.GetValueOrDefault()); } } return(0); }
/// <summary> /// Calculates the closest point on the route relative to the given coordinate. /// </summary> /// <param name="coordinates"></param> /// <param name="projectedCoordinates"></param> /// <param name="distanceToProjected"></param> /// <param name="timeFromStart"></param> /// <returns></returns> public bool ProjectOn(GeoCoordinate coordinates, out GeoCoordinate projectedCoordinates, out Meter distanceToProjected, out Second timeFromStart) { int entryIdx; return(this.ProjectOn(coordinates, out projectedCoordinates, out entryIdx, out distanceToProjected, out timeFromStart)); }
/// <inheritdoc/> public override void BindTo(Meter meter) { pressedDown = false; base.BindTo(meter); }
/// <summary> /// Luo uuden liukusäätimen. /// Sitoo liukusäätimen arvon mittarin arvoon. /// </summary> /// <param name="width">Säätimen leveys.</param> /// <param name="height">Säätimen korkeus.</param> /// <param name="meter">Mittari</param> public Slider(double width, double height, Meter meter) : this(width, height) { BindTo(meter); }
//Insert meter function created by mateus castanho private static void InsertMeter() { //iniciates boolen var bool insertLoop = true; //iniciates new loop while (insertLoop) { //inform user that his is insert new meter Console.Clear(); Console.WriteLine("--------------Inserting New Meter------------\n"); //iniciantes var serial number var serialNumber = ""; //iniciates integer variable model id int modelId = 0; //iniciates integer variable number int number = 0; //iniciates string variable firmware version string firmwareVersion = ""; //iniciates integer variable switch State int switchState = 0; //iniciates new loop boolean variable bool loop = true; //iniciates input variable var input = ""; //iniciates new loop when user input is valid loop stop while (loop) { //ask user to inform the serial number Console.Write("Inform Serial Number: "); //put user input into serial number variable serialNumber = Console.ReadLine().Trim(); //verify if user input was null or empty if (string.IsNullOrEmpty(serialNumber)) { //inform user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write at least 1 character"); Console.ForegroundColor = ConsoleColor.White; //return to loop star } else { //calls controller function VerifyIfExistBySerialNumber pass serial number var as parameter //puts return into boolean var bool serialExist = Controller.VerifyIfExistBySerialNumber(serialNumber); //verify is exist a meter registred with serial number if (serialExist == true) { //iform user that serial number is already registered Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Fail this serial number already registered"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } else { //stop the loop loop = false; } } } //reset loop var loop = true; //iniciates new loop when user input is valid loop stop while (loop) { //ask user to input model id Console.Write("Model Id: "); //put user input into input varible input = Console.ReadLine(); //verify if user input was a integer //if is interger put input value into model id var if (int.TryParse(input, out modelId)) { //verify is model id var is between 16 and 19 if (modelId < 16 || modelId > 19) { //infor user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write an interger between 16 and 19"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } else { //ends the loop loop = false; } } else { //infor user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write an interger between 16 and 19"); Console.ForegroundColor = ConsoleColor.White; } } //reset loop variable loop = true; //iniciates new loop when user input is valid loop stop while (loop) { //ask user to input number Console.Write("Number: "); input = Console.ReadLine(); //verify if user input was a integer //if is interger put input value into number var if (!int.TryParse(input, out number)) { //inform user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write an interger"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } else { //ends loop loop = false; } } //reset loop var loop = true; //iniciates new loop when user input is valid loop stop while (loop) { //ask user to input firmware vertion Console.Write("Firmware Version: "); //put user input into firmware version variable firmwareVersion = Console.ReadLine().Trim(); //verify if user input is null or invalid if (string.IsNullOrEmpty(firmwareVersion)) { //inform user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write at least 1 character"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } else { //ends loop loop = false; } } //reset loop variable loop = true; //iniciates new loop when user input is valid loop stop while (loop) { //ask user switch state Console.Write("Switch State: "); //verify if user input was a integer //if is interger put input value into switch state var input = Console.ReadLine(); if (int.TryParse(input, out switchState)) { //verify is user input is between 0 and 2 if (switchState < 0 || switchState > 2) { //inform user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write an interger between 0 and 2"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } else { //ends loop loop = false; } } else { //inform user that his input was invalid Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Invalid input, please write an interger between 0 and 2"); Console.ForegroundColor = ConsoleColor.White; //return to loop start } } //creates new object meter and pass to controler the input variable as parameter Meter Novo = new Meter(serialNumber, modelId, number, firmwareVersion, switchState); //calls controller InsertMeter function and pass object novo as parameter //functions trys insert new meter bool inserido = Controller.InsertMeter(Novo); //verify is return was true if (inserido == true) { //inform user succed in insert new meter Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Succeed in insert a new Meter "); Console.ForegroundColor = ConsoleColor.White; } else { //inform user succed in insert new meter Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Failed in insert a new Meter "); Console.ForegroundColor = ConsoleColor.White; } //ends loop insertLoop = false; } //wait user press any key and return to menu; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\n Press any key to continue..."); Console.ReadKey(); }
void slc_MeterAdded(Slice slc, Meter m) { if (m.Name == "SNR") AddSNRMeter(slc, m); }
/// <summary> /// Returns an enumerable of route positions with the given interval between them. /// </summary> /// <param name="interval"></param> /// <returns></returns> public IEnumerable <GeoCoordinate> GetRouteEnumerable(Meter interval) { return(new RouteEnumerable(this, interval)); }
private XDocument ToSheet(Meter meter) { XDocument sheet = new XDocument(); XElement rootElement = new XElement("meterSettingsSheet"); sheet.Add(rootElement); XElement meterElement = new XElement("meter"); meterElement.Add(new XElement(nameof(meter.ID), meter.ID)); meterElement.Add(new XElement(nameof(meter.AssetKey), meter.AssetKey)); meterElement.Add(new XElement(nameof(meter.LocationID), meter.LocationID)); meterElement.Add(new XElement(nameof(meter.Name), meter.Name)); meterElement.Add(new XElement(nameof(meter.Alias), meter.Alias)); meterElement.Add(new XElement(nameof(meter.ShortName), meter.ShortName)); meterElement.Add(new XElement(nameof(meter.Make), meter.Make)); meterElement.Add(new XElement(nameof(meter.Model), meter.Model)); meterElement.Add(new XElement(nameof(meter.TimeZone), meter.TimeZone)); meterElement.Add(new XElement(nameof(meter.Description), meter.Description)); rootElement.Add(meterElement); XElement locationElement = new XElement("location"); locationElement.Add(new XElement(nameof(meter.Location.ID), meter.Location.ID)); locationElement.Add(new XElement(nameof(meter.Location.LocationKey), meter.Location.LocationKey)); locationElement.Add(new XElement(nameof(meter.Location.Name), meter.Location.Name)); locationElement.Add(new XElement(nameof(meter.Location.Alias), meter.Location.Alias)); locationElement.Add(new XElement(nameof(meter.Location.ShortName), meter.Location.ShortName)); locationElement.Add(new XElement(nameof(meter.Location.Latitude), meter.Location.Latitude)); locationElement.Add(new XElement(nameof(meter.Location.Longitude), meter.Location.Longitude)); locationElement.Add(new XElement(nameof(meter.Location.Description), meter.Location.Description)); rootElement.Add(locationElement); // Start With Assets IEnumerable <Asset> assets = meter.MeterAssets .Select(meterLine => meterLine.Asset) .OrderBy(asset => asset.ID); //Save individual Assets (Except LineSegments) List <LineSegment> lineSegments = new List <LineSegment>(); List <AssetConnection> assetConnections = new List <AssetConnection>(); foreach (Asset asset in assets) { XElement assetElement = new XElement("asset");; switch (asset.AssetTypeID) { case ((int)AssetType.Breaker): assetElement = new XElement("breaker"); Breaker breaker = Breaker.DetailedBreaker(asset, asset.ConnectionFactory?.Invoke()); assetElement.Add(new XElement(nameof(breaker.VoltageKV), breaker.VoltageKV)); assetElement.Add(new XElement(nameof(breaker.ThermalRating), breaker.ThermalRating)); assetElement.Add(new XElement(nameof(breaker.Speed), breaker.Speed)); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); break; case ((int)AssetType.Bus): assetElement = new XElement("bus"); Bus bus = Bus.DetailedBus(asset, asset.ConnectionFactory?.Invoke()); assetElement.Add(new XElement(nameof(bus.VoltageKV), bus.VoltageKV)); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); break; case ((int)AssetType.CapacitorBank): assetElement = new XElement("capacitorBank"); CapBank capBank = CapBank.DetailedCapBank(asset, asset.ConnectionFactory?.Invoke()); assetElement.Add(new XElement(nameof(capBank.VoltageKV), capBank.VoltageKV)); assetElement.Add(new XElement(nameof(capBank.NumberOfBanks), capBank.NumberOfBanks)); assetElement.Add(new XElement(nameof(capBank.CansPerBank), capBank.CansPerBank)); assetElement.Add(new XElement(nameof(capBank.CapacitancePerBank), capBank.CapacitancePerBank)); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); break; case ((int)AssetType.Transformer): assetElement = new XElement("transformer"); Transformer xfr = Transformer.DetailedTransformer(asset, asset.ConnectionFactory?.Invoke()); assetElement.Add(new XElement(nameof(xfr.ThermalRating), xfr.ThermalRating)); assetElement.Add(new XElement(nameof(xfr.SecondaryVoltageKV), xfr.SecondaryVoltageKV)); assetElement.Add(new XElement(nameof(xfr.PrimaryVoltageKV), xfr.PrimaryVoltageKV)); assetElement.Add(new XElement(nameof(xfr.Tap), xfr.Tap)); assetElement.Add(new XElement(nameof(xfr.X0), xfr.X0)); assetElement.Add(new XElement(nameof(xfr.R0), xfr.R0)); assetElement.Add(new XElement(nameof(xfr.X1), xfr.X1)); assetElement.Add(new XElement(nameof(xfr.R1), xfr.R1)); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); break; case ((int)AssetType.Line): assetElement = new XElement("line"); Line line = Line.DetailedLine(asset); assetElement.Add(new XElement(nameof(line.VoltageKV), line.VoltageKV)); assetElement.Add(new XElement(nameof(line.MaxFaultDistance), line.MaxFaultDistance)); assetElement.Add(new XElement(nameof(line.MinFaultDistance), line.MinFaultDistance)); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); lineSegments.AddRange(line.Segments); break; case ((int)AssetType.LineSegement): lineSegments.Add(LineSegment.DetailedLineSegment(asset, asset.ConnectionFactory?.Invoke())); break; default: assetElement = new XElement("asset"); assetElement.Add(new XElement(nameof(asset.ID), asset.ID)); assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey)); assetElement.Add(new XElement(nameof(asset.Description), asset.Description)); assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName)); break; } assetConnections.AddRange(asset.Connections.Where(item => item.ParentID == asset.ID)); rootElement.Add(assetElement); } //Deal with special Cases... If it is a line we need to keep the Line Segments... foreach (LineSegment lineSegment in lineSegments) { XElement lineSegmentElement = new XElement("lineSegment"); lineSegmentElement.Add(new XElement(nameof(lineSegment.ThermalRating), lineSegment.ThermalRating)); lineSegmentElement.Add(new XElement(nameof(lineSegment.X0), lineSegment.X0)); lineSegmentElement.Add(new XElement(nameof(lineSegment.R0), lineSegment.R0)); lineSegmentElement.Add(new XElement(nameof(lineSegment.X1), lineSegment.X1)); lineSegmentElement.Add(new XElement(nameof(lineSegment.R1), lineSegment.R1)); lineSegmentElement.Add(new XElement(nameof(lineSegment.ID), lineSegment.ID)); lineSegmentElement.Add(new XElement(nameof(lineSegment.Length), lineSegment.Length)); lineSegmentElement.Add(new XElement(nameof(lineSegment.AssetKey), lineSegment.AssetKey)); lineSegmentElement.Add(new XElement(nameof(lineSegment.Description), lineSegment.Description)); lineSegmentElement.Add(new XElement(nameof(lineSegment.AssetName), lineSegment.AssetName)); assetConnections.AddRange(lineSegment.Connections.Where(item => item.ParentID == lineSegment.ID)); rootElement.Add(lineSegmentElement); } //Deal with Asset -> Asset Connections..... foreach (AssetConnection assetConnection in assetConnections) { if (assets.Select(item => item.ID).Contains(assetConnection.ChildID) || lineSegments.Select(item => item.ID).Contains(assetConnection.ChildID)) { XElement assetConnectionElement = new XElement("assetConnection"); assetConnectionElement.Add(new XElement(nameof(assetConnection.ID), assetConnection.ID)); assetConnectionElement.Add(new XElement(nameof(assetConnection.ChildID), assetConnection.ChildID)); assetConnectionElement.Add(new XElement(nameof(assetConnection.ParentID), assetConnection.ParentID)); assetConnectionElement.Add(new XElement(nameof(assetConnection.AssetRelationshipTypeID), assetConnection.AssetRelationshipTypeID)); rootElement.Add(assetConnectionElement); } } // That is it for Assets IEnumerable <Channel> channels = meter.Channels .OrderBy(channel => channel.ID); foreach (Channel channel in channels) { if (channel.ID == 0) { continue; } XElement channelElement = new XElement("channel"); channelElement.Add(new XElement(nameof(channel.ID), channel.ID)); channelElement.Add(new XElement(nameof(channel.MeterID), channel.MeterID)); channelElement.Add(new XElement(nameof(channel.AssetID), channel.AssetID)); channelElement.Add(new XElement(nameof(channel.MeasurementTypeID), channel.MeasurementTypeID)); channelElement.Add(new XElement(nameof(channel.MeasurementType), channel.MeasurementType.Name)); channelElement.Add(new XElement(nameof(channel.MeasurementCharacteristicID), channel.MeasurementCharacteristicID)); channelElement.Add(new XElement(nameof(channel.MeasurementCharacteristic), channel.MeasurementCharacteristic.Name)); channelElement.Add(new XElement(nameof(channel.PhaseID), channel.PhaseID)); channelElement.Add(new XElement(nameof(channel.Phase), channel.Phase.Name)); channelElement.Add(new XElement(nameof(channel.Name), channel.Name)); channelElement.Add(new XElement(nameof(channel.SamplesPerHour), channel.SamplesPerHour)); channelElement.Add(new XElement(nameof(channel.PerUnitValue), channel.PerUnitValue)); channelElement.Add(new XElement(nameof(channel.HarmonicGroup), channel.HarmonicGroup)); channelElement.Add(new XElement(nameof(channel.Description), channel.Description)); channelElement.Add(new XElement(nameof(channel.Enabled), channel.Enabled)); rootElement.Add(channelElement); } IEnumerable <Series> seriesList = meter.Channels .SelectMany(channel => channel.Series) .OrderBy(series => series.ID); foreach (Series series in seriesList) { if (series.ID == 0) { continue; } XElement seriesElement = new XElement("series"); seriesElement.Add(new XElement(nameof(series.ID), series.ID)); seriesElement.Add(new XElement(nameof(series.ChannelID), series.ChannelID)); seriesElement.Add(new XElement(nameof(series.SeriesTypeID), series.SeriesTypeID)); seriesElement.Add(new XElement(nameof(series.SeriesType), series.SeriesType.Name)); seriesElement.Add(new XElement(nameof(series.SourceIndexes), series.SourceIndexes)); rootElement.Add(seriesElement); } IEnumerable <AssetLocation> assetLocations = meter.Location.AssetLocations .OrderBy(assetLocation => assetLocation.ID); foreach (AssetLocation assetLocation in assetLocations) { XElement meterLocationLineElement = new XElement("assetLocation"); meterLocationLineElement.Add(new XElement(nameof(assetLocation.ID), assetLocation.ID)); meterLocationLineElement.Add(new XElement(nameof(assetLocation.LocationID), assetLocation.LocationID)); meterLocationLineElement.Add(new XElement(nameof(assetLocation.AssetID), assetLocation.AssetID)); rootElement.Add(meterLocationLineElement); } IEnumerable <MeterAsset> meterAssets = meter.MeterAssets .OrderBy(meterAsset => meterAsset.ID); foreach (MeterAsset meterAsset in meterAssets) { XElement meterLineElement = new XElement("meterAsset"); meterLineElement.Add(new XElement(nameof(meterAsset.ID), meterAsset.ID)); meterLineElement.Add(new XElement(nameof(meterAsset.MeterID), meterAsset.MeterID)); meterLineElement.Add(new XElement(nameof(meterAsset.AssetID), meterAsset.AssetID)); rootElement.Add(meterLineElement); } return(sheet); }
private void dbUpdateWorker_DoWork(object sender, DoWorkEventArgs e) { DbRecordChangesTask dbChangesTask = e.Argument as DbRecordChangesTask; try { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { if (tableItem is Meter) { Meter record = dbChangesTask.DbRecord as Meter; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нової одиниці виміру..."); record.Name = record.Name.Trim(); mc.Meters.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення одиниці виміру..."); record.Name = record.Name.Trim(); mc.Meters.Attach(record); mc.Entry <Meter>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення одиниці виміру..."); mc.Meters.Attach(record); mc.Meters.Remove(record); break; } } else if (tableItem is HospitalDepartment) { HospitalDepartment record = dbChangesTask.DbRecord as HospitalDepartment; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нового відділення..."); record.Name = record.Name.Trim(); mc.HospitalDepartments.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення даних про відділення..."); record.Name = record.Name.Trim(); mc.HospitalDepartments.Attach(record); mc.Entry <HospitalDepartment>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення даних про відділення..."); mc.HospitalDepartments.Attach(record); mc.HospitalDepartments.Remove(record); break; } } else if (tableItem is MedicamentGroup) { MedicamentGroup record = dbChangesTask.DbRecord as MedicamentGroup; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нової группи медикаментів..."); record.Name = record.Name.Trim(); mc.MedicamentsGroups.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення группи медикаментів..."); record.Name = record.Name.Trim(); mc.MedicamentsGroups.Attach(record); mc.Entry <MedicamentGroup>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення группи медикаментів..."); mc.MedicamentsGroups.Attach(record); mc.MedicamentsGroups.Remove(record); break; } } mc.SaveChanges(); if (tableItem is HospitalDepartment) { isDepartmentListUpdated = true; } dbUpdateWorker.ReportProgress(0, "Дані успішно збережені!"); } } catch (Exception ex) { dbUpdateWorker.ReportProgress(0, "Помилка: " + ex.Message); } Thread.Sleep(3000); }
private void Parse(string filename) { List <ObservationRecord> observationRecords; List <DataSourceRecord> dataSourceRecords; using (LogicalParser logicalParser = new LogicalParser(filename)) { observationRecords = new List <ObservationRecord>(); logicalParser.Open(); while (logicalParser.HasNextObservationRecord()) { observationRecords.Add(logicalParser.NextObservationRecord()); } dataSourceRecords = logicalParser.DataSourceRecords; } this.m_previousProgress = this.m_previousProgress + 50; this.mProgress.Report(this.m_previousProgress); if (observationRecords.Count == 0) { return; } if (dataSourceRecords.Count != 1) { return; } //create Meter Definition //For now assume a single meter Meter meter = new Meter(); meter.DeviceName = dataSourceRecords[0].DataSourceName; meter.Owner = dataSourceRecords[0].DataSourceOwner; meter.DeviceAlias = GSF.PQDIF.Logical.Equipment.ToString(dataSourceRecords[0].EquipmentID); meter.DeviceLocation = dataSourceRecords[0].DataSourceLocation; if (dataSourceRecords[0].Latitude < uint.MaxValue) { meter.Latitude = dataSourceRecords[0].Latitude; } if (dataSourceRecords[0].Longitude < uint.MaxValue) { meter.Longitude = dataSourceRecords[0].Longitude; } meter.AccountName = GSF.PQDIF.Logical.Vendor.ToString(dataSourceRecords[0].VendorID); using (TransactionScope scope = new TransactionScope()) { AdoDataConnection connection = new AdoDataConnection(connectionstring, dataprovider); GSF.Data.Model.TableOperations <Meter> meterTable = new GSF.Data.Model.TableOperations <Meter>(connection); meterTable.AddNewRecord(meter); meter.ID = ModelID.GetID <Meter>(connection); //create Channel Definitions List <PQio.Model.Channel> channels = dataSourceRecords[0].ChannelDefinitions.Select(channel => ParseChannel(meter, channel, connection)).ToList(); List <PQio.Model.Event> events = new List <Event>(); //create Event Definitions foreach (ObservationRecord record in observationRecords) { //Create Event Event evt = ParseObservationRecord(record, connection); //create DataSeries objects foreach (ChannelInstance channelInstance in record.ChannelInstances) { ParseSeries(channelInstance, channels[(int)channelInstance.ChannelDefinitionIndex], evt, connection); } events.Add(evt); } // Remove Channels whithout data channels = channels.FindAll(item => RemoveEmptyChannel(item, connection)).ToList(); events = events.FindAll(item => RemoveEmptyEvents(item, connection)).ToList(); // Remove Channels whithout data channels = channels.FindAll(item => RemoveEmptyChannel(item, connection)).ToList(); // If only one set of data it's easy to keep only single line int nVa = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.VoltageA); int nVb = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.VoltageB); int nVc = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.VoltageC); int nIa = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.CurrentA); int nIb = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.CurrentB); int nIc = channels.Count(channel => channel.MeasurementType.ToLower() == MeasurementType.CurrentC); if (nVa == 1 && nVb == 1 && nVc == 1) { //Create new asset Asset asset = new Asset() { AssetKey = String.Format("Asset 1 ({0})", meter.AccountName) }; GSF.Data.Model.TableOperations <Asset> assetTable = new GSF.Data.Model.TableOperations <Asset>(connection); assetTable.AddNewRecord(asset); asset.ID = ModelID.GetID <Asset>(connection); GSF.Data.Model.TableOperations <Channel> channelTable = new GSF.Data.Model.TableOperations <Channel>(connection); Channel Va = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.VoltageA); Channel Vb = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.VoltageB); Channel Vc = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.VoltageC); Va.AssetID = asset.ID; Vb.AssetID = asset.ID; Vc.AssetID = asset.ID; channelTable.UpdateRecord(Va); channelTable.UpdateRecord(Vb); channelTable.UpdateRecord(Vc); if (nIa == 1 && nIb == 1 && nIc == 1) { Channel Ia = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.CurrentA); Channel Ib = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.CurrentB); Channel Ic = channels.Find(item => item.MeasurementType.ToLower() == MeasurementType.CurrentC); Ia.AssetID = asset.ID; Ib.AssetID = asset.ID; Ic.AssetID = asset.ID; channelTable.UpdateRecord(Ia); channelTable.UpdateRecord(Ib); channelTable.UpdateRecord(Ic); } } scope.Complete(); } this.m_previousProgress = this.m_previousProgress + 50; this.mProgress.Report(this.m_previousProgress); }
public async Task EnterExitCollectTest() { using var meter = new Meter(Utils.GetCurrentMethodName()); using (var provider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddPrometheusExporter() .Build()) { if (!provider.TryFindExporter(out PrometheusExporter exporter)) { throw new InvalidOperationException("PrometheusExporter could not be found on MeterProvider."); } int runningCollectCount = 0; var collectFunc = exporter.Collect; exporter.Collect = (timeout) => { bool result = collectFunc(timeout); runningCollectCount++; Thread.Sleep(5000); return(result); }; var counter = meter.CreateCounter <int>("counter_int", description: "Prometheus help text goes here \n escaping."); counter.Add(100); Task <Response>[] collectTasks = new Task <Response> [10]; for (int i = 0; i < collectTasks.Length; i++) { collectTasks[i] = Task.Run(async() => { var response = await exporter.CollectionManager.EnterCollect().ConfigureAwait(false); try { return(new Response { CollectionResponse = response, ViewPayload = response.View.ToArray(), }); } finally { exporter.CollectionManager.ExitCollect(); } }); } await Task.WhenAll(collectTasks).ConfigureAwait(false); Assert.Equal(1, runningCollectCount); var firstResponse = collectTasks[0].Result; Assert.False(firstResponse.CollectionResponse.FromCache); for (int i = 1; i < collectTasks.Length; i++) { Assert.Equal(firstResponse.ViewPayload, collectTasks[i].Result.ViewPayload); Assert.Equal(firstResponse.CollectionResponse.GeneratedAtUtc, collectTasks[i].Result.CollectionResponse.GeneratedAtUtc); } counter.Add(100); // This should use the cache and ignore the second counter update. var task = exporter.CollectionManager.EnterCollect(); Assert.True(task.IsCompleted); var response = await task.ConfigureAwait(false); try { Assert.Equal(1, runningCollectCount); Assert.True(response.FromCache); Assert.Equal(firstResponse.CollectionResponse.GeneratedAtUtc, response.GeneratedAtUtc); } finally { exporter.CollectionManager.ExitCollect(); } Thread.Sleep(exporter.Options.ScrapeResponseCacheDurationMilliseconds); counter.Add(100); for (int i = 0; i < collectTasks.Length; i++) { collectTasks[i] = Task.Run(async() => { var response = await exporter.CollectionManager.EnterCollect().ConfigureAwait(false); try { return(new Response { CollectionResponse = response, ViewPayload = response.View.ToArray(), }); } finally { exporter.CollectionManager.ExitCollect(); } }); } await Task.WhenAll(collectTasks).ConfigureAwait(false); Assert.Equal(2, runningCollectCount); Assert.NotEqual(firstResponse.ViewPayload, collectTasks[0].Result.ViewPayload); Assert.NotEqual(firstResponse.CollectionResponse.GeneratedAtUtc, collectTasks[0].Result.CollectionResponse.GeneratedAtUtc); firstResponse = collectTasks[0].Result; Assert.False(firstResponse.CollectionResponse.FromCache); for (int i = 1; i < collectTasks.Length; i++) { Assert.Equal(firstResponse.ViewPayload, collectTasks[i].Result.ViewPayload); Assert.Equal(firstResponse.CollectionResponse.GeneratedAtUtc, collectTasks[i].Result.CollectionResponse.GeneratedAtUtc); } } }
public static bool CompareTwoLengths(Meter firstLength, Meter secondLength) { return firstLength == secondLength; }
internal ObservableCounter(Meter meter, string name, string?unit, string?description) : base(meter, name, unit, description) { throw null; }
private int SyncMeterLocations(string address, MetersToDataPush meterToDataPush, Meter localMeterRecord) { List <MeterLocation> remoteMeterLocations = WebAPIHub.GetRecords(address, "MeterLocation", "all").Select(x => (MeterLocation)x).ToList(); if (meterToDataPush.Obsfucate) { // if the company meter location does not exist, create it if (!remoteMeterLocations.Where(x => x.AssetKey == WebAPIHub.CompanyName).Any()) { MeterLocation record = new MeterLocation() { AssetKey = WebAPIHub.CompanyName, Name = WebAPIHub.CompanyName, Alias = WebAPIHub.CompanyName, ShortName = "", Description = "", Latitude = 0.0F, Longitude = 0.0F }; return(WebAPIHub.CreateRecord(address, "MeterLocation", JObject.FromObject(record))); } else { return(remoteMeterLocations.Where(x => x.AssetKey == WebAPIHub.CompanyName).First().ID); } } else { MeterLocation meterLocation = DataContext.Table <MeterLocation>().QueryRecordWhere("ID = {0}", localMeterRecord.MeterLocationID); if (!remoteMeterLocations.Where(x => x.AssetKey == meterLocation.AssetKey).Any()) { return(WebAPIHub.CreateRecord(address, "MeterLocation", JObject.FromObject(meterLocation))); } else { return(remoteMeterLocations.Where(x => x.AssetKey == meterLocation.AssetKey).First().ID); } } }
void SNR_DataReady(Meter meter, float data) { if (!_SNRTable.ContainsKey(meter)) return; Slice slc = _SNRTable[meter]; UpdateSNR(slc, data); }
public void ViewToProduceCustomHistogramBound() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List <Metric>(); var boundaries = new double[] { 10, 20 }; using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Name = "MyHistogramDefaultBound" }) .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Boundaries = boundaries }) .AddInMemoryExporter(exportedItems) .Build(); var histogram = meter.CreateHistogram <long>("MyHistogram"); histogram.Record(-10); histogram.Record(0); histogram.Record(1); histogram.Record(9); histogram.Record(10); histogram.Record(11); histogram.Record(19); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); var metricDefault = exportedItems[0]; var metricCustom = exportedItems[1]; Assert.Equal("MyHistogramDefaultBound", metricDefault.Name); Assert.Equal("MyHistogram", metricCustom.Name); List <MetricPoint> metricPointsDefault = new List <MetricPoint>(); foreach (ref var mp in metricDefault.GetMetricPoints()) { metricPointsDefault.Add(mp); } Assert.Single(metricPointsDefault); var histogramPoint = metricPointsDefault[0]; var count = histogramPoint.GetHistogramCount(); var sum = histogramPoint.GetHistogramSum(); Assert.Equal(40, sum); Assert.Equal(7, count); int index = 0; int actualCount = 0; var expectedBucketCounts = new long[] { 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0 }; foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets()) { Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount); index++; actualCount++; } Assert.Equal(Metric.DefaultHistogramBounds.Length + 1, actualCount); List <MetricPoint> metricPointsCustom = new List <MetricPoint>(); foreach (ref var mp in metricCustom.GetMetricPoints()) { metricPointsCustom.Add(mp); } Assert.Single(metricPointsCustom); histogramPoint = metricPointsCustom[0]; count = histogramPoint.GetHistogramCount(); sum = histogramPoint.GetHistogramSum(); Assert.Equal(40, sum); Assert.Equal(7, count); index = 0; actualCount = 0; expectedBucketCounts = new long[] { 5, 2, 0 }; foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets()) { Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount); index++; actualCount++; } Assert.Equal(boundaries.Length + 1, actualCount); }
public string InsertMeter(Meter meter) { return(MeterDA.InsertMeter(meter)); }
private List <PQDS.MetaDataTag> PQDSMetaData(Event evt, Meter meter) { List <PQDS.MetaDataTag> result = new List <PQDS.MetaDataTag>(); result.Add(new PQDS.MetaDataTag <string>("DeviceName", meter.Name)); result.Add(new PQDS.MetaDataTag <string>("DeviceAlias", meter.ShortName)); result.Add(new PQDS.MetaDataTag <string>("DeviceLocation", meter.Location.Name)); result.Add(new PQDS.MetaDataTag <string>("DeviceLocationAlias", meter.Location.ShortName)); result.Add(new PQDS.MetaDataTag <string>("Latitude", Convert.ToString(meter.Location.Latitude))); result.Add(new PQDS.MetaDataTag <string>("Longitude", Convert.ToString(meter.Location.Longitude))); Asset asset; double systemFrequency; using (AdoDataConnection connection = new AdoDataConnection("dbOpenXDA")) { asset = (new TableOperations <Asset>(connection)).QueryRecordWhere("ID = {0}", evt.AssetID); systemFrequency = connection.ExecuteScalar <double?>("SELECT Value FROM Setting WHERE Name = 'SystemFrequency'") ?? 60.0; if (asset != null) { result.Add(new PQDS.MetaDataTag <double>("NominalVoltage-LG", asset.VoltageKV)); result.Add(new PQDS.MetaDataTag <double>("NominalFrequency", systemFrequency)); result.Add(new PQDS.MetaDataTag <string>("AssetName", asset.AssetKey)); if (asset.AssetTypeID == connection.ExecuteScalar <int>("SELECT ID FROM AssetType WHERE Name = 'Line'")) { result.Add(new PQDS.MetaDataTag <double>("LineLength", connection.ExecuteScalar <double>("SELECT Length FROM LineView WHERE ID = {0}", asset.ID))); } } result.Add(new PQDS.MetaDataTag <string>("EventID", evt.Name)); result.Add(new PQDS.MetaDataTag <string>("EventGUID", Guid.NewGuid().ToString())); result.Add(new PQDS.MetaDataTag <double>("EventDuration", (evt.EndTime - evt.StartTime).TotalMilliseconds)); result.Add(new PQDS.MetaDataTag <int>("EventTypeCode", PQDSEventTypeCode(evt.EventTypeID))); EventStat stat = (new TableOperations <EventStat>(connection)).QueryRecordWhere("EventID = {0}", evt.ID); if (stat != null) { if (stat.VAMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxVA", (double)stat.VAMax)); } if (stat.VBMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxVB", (double)stat.VBMax)); } if (stat.VCMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxVC", (double)stat.VCMax)); } if (stat.VAMin != null) { result.Add(new PQDS.MetaDataTag <double>("EventMinVA", (double)stat.VAMin)); } if (stat.VBMin != null) { result.Add(new PQDS.MetaDataTag <double>("EventMinVB", (double)stat.VBMin)); } if (stat.VCMin != null) { result.Add(new PQDS.MetaDataTag <double>("EventMinVC", (double)stat.VCMin)); } if (stat.IAMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxIA", (double)stat.IAMax)); } if (stat.IBMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxIB", (double)stat.IBMax)); } if (stat.ICMax != null) { result.Add(new PQDS.MetaDataTag <double>("EventMaxIC", (double)stat.ICMax)); } } result.Add(new PQDS.MetaDataTag <int>("EventYear", ((DateTime)evt.StartTime).Year)); result.Add(new PQDS.MetaDataTag <int>("EventMonth", (evt.StartTime).Month)); result.Add(new PQDS.MetaDataTag <int>("EventDay", (evt.StartTime).Day)); result.Add(new PQDS.MetaDataTag <int>("EventHour", (evt.StartTime).Hour)); result.Add(new PQDS.MetaDataTag <int>("EventMinute", (evt.StartTime).Minute)); result.Add(new PQDS.MetaDataTag <int>("EventSecond", (evt.StartTime).Second)); result.Add(new PQDS.MetaDataTag <int>("EventNanoSecond", Get_nanoseconds(evt.StartTime))); String date = String.Format("{0:D2}/{1:D2}/{2:D4}", (evt.StartTime).Month, (evt.StartTime).Day, (evt.StartTime).Year); String time = String.Format("{0:D2}:{1:D2}:{2:D2}", (evt.StartTime).Hour, (evt.StartTime).Minute, (evt.StartTime).Second); result.Add(new PQDS.MetaDataTag <string>("EventDate", date)); result.Add(new PQDS.MetaDataTag <string>("EventTime", time)); } return(result); }
public ErrorMeterMiddleware(MetricsContext context, string metricName, Regex[] ignorePatterns) : base(ignorePatterns) { this.errorMeter = context.Meter(metricName, Unit.Errors); }
private List <D3Series> QueryVoltageData(Meter meter, Event evt) { bool useLL; using (AdoDataConnection connection = new AdoDataConnection("systemSettings")) { useLL = connection.ExecuteScalar <bool?>("SELECT Value FROM Settings WHERE Name = 'useLLVoltage'") ?? false; } DataGroup dataGroup = OpenSEEController.QueryDataGroup(evt.ID, meter); List <D3Series> WaveForm = dataGroup.DataSeries.Where(ds => ds.SeriesInfo.Channel.MeasurementType.Name == "Voltage" && ( (useLL && !(ds.SeriesInfo.Channel.Phase.Name == "AB" || ds.SeriesInfo.Channel.Phase.Name == "BC" || ds.SeriesInfo.Channel.Phase.Name == "CA")) || (!useLL && (ds.SeriesInfo.Channel.Phase.Name == "AB" || ds.SeriesInfo.Channel.Phase.Name == "BC" || ds.SeriesInfo.Channel.Phase.Name == "CA"))) ).Select( ds => new D3Series() { ChannelID = ds.SeriesInfo.Channel.ID, ChartLabel = OpenSEEController.GetChartLabel(ds.SeriesInfo.Channel), LegendGroup = ds.SeriesInfo.Channel.Asset.AssetName, DataPoints = ds.DataPoints.Select(dataPoint => new double[] { dataPoint.Time.Subtract(m_epoch).TotalMilliseconds, dataPoint.Value }).ToList(), }).ToList(); WaveForm.Sort((a, b) => { if (a.LegendGroup == b.LegendGroup) { return(a.ChartLabel.CompareTo(b.ChartLabel)); } return(a.LegendGroup.CompareTo(b.LegendGroup)); }); VICycleDataGroup viCycleDataGroup = OpenSEEController.QueryVICycleDataGroup(evt.ID, meter); List <D3Series> result = new List <D3Series>(); foreach (D3Series w in WaveForm) { result.Add(w); int index = viCycleDataGroup.CycleDataGroups.FindIndex(item => item.RMS.SeriesInfo.ChannelID == w.ChannelID); if (index > -1) { result.Add(new D3Series { ChannelID = w.ChannelID, DataPoints = viCycleDataGroup.CycleDataGroups[index].RMS.DataPoints.Select(dataPoint => new double[] { dataPoint.Time.Subtract(m_epoch).TotalMilliseconds, dataPoint.Value }).ToList(), ChartLabel = w.ChartLabel + " RMS", LegendGroup = w.LegendGroup, }); result.Add(new D3Series { ChannelID = w.ChannelID, DataPoints = viCycleDataGroup.CycleDataGroups[index].Phase.Multiply(180.0D / Math.PI).DataPoints.Select(dataPoint => new double[] { dataPoint.Time.Subtract(m_epoch).TotalMilliseconds, dataPoint.Value }).ToList(), ChartLabel = w.ChartLabel + " Phase", LegendGroup = w.LegendGroup, }); } } return(result); }
/// <summary> /// 添加表对象到mongodb库中(用于新表安装) /// </summary> /// <param name="info"></param> /// <returns></returns> public string InsertMeter(IoT_Meter info) { Meter _meter = QueryMeter(info.MeterNo.Trim()); if (_meter != null) { MongoDBHelper <Meter> mongo = new MongoDBHelper <Meter>(); var iDelete = new QueryDocument(); iDelete.Add("Mac", info.MeterNo.Trim()); mongo.Delete(CollectionNameDefine.MeterCollectionName, iDelete); } Meter meter = new Meter(); meter.MeterID = info.ID; meter.UserID = info.CompanyID.Trim() + info.UserID.Trim(); meter.Key = info.MKey; meter.Mac = info.MeterNo.Trim(); meter.MeterState = info.MeterState.ToString(); meter.MeterType = info.MeterType; meter.MKeyVer = (byte)(info.MKeyVer & 0xff); meter.PriceCheck = info.PriceCheck.ToString(); meter.SettlementDay = (int)info.SettlementDay; meter.SettlementType = info.SettlementType; meter.TotalAmount = (decimal)info.TotalAmount; meter.TotalTopUp = (decimal)info.TotalTopUp; meter.ValveState = info.ValveState.ToString(); meter.LastTopUpSer = 0; meter.IsUsedLadder = (bool)info.IsUsed; meter.Ladder = (int)info.Ladder; meter.MeterType = info.MeterType; meter.Price1 = (decimal)info.Price1; meter.Price2 = (decimal)info.Price2; meter.Price3 = (decimal)info.Price3; meter.Price4 = (decimal)info.Price4; meter.Price5 = (decimal)info.Price5; meter.Gas1 = (decimal)info.Gas1; meter.Gas2 = (decimal)info.Gas2; meter.Gas3 = (decimal)info.Gas3; meter.Gas4 = (decimal)info.Gas4; meter.SettlementMonth = (int)info.SettlementMonth; meter.SettlementDay = (int)info.SettlementDay; meter.SettlementType = info.SettlementType; meter.CurrentLadder = 1; meter.CurrentPrice = meter.Price1; if (meter.IsUsedLadder && meter.CurrentLadder < meter.Ladder) { meter.NextSettlementPointGas = meter.TotalAmount + meter.Gas1; meter.SetNextSettlementDateTime(); } meter.LastTotal = meter.TotalAmount; meter.LastSettlementAmount = (decimal)info.TotalTopUp; meter.LastGasPoint = meter.TotalAmount; meter.CurrentBalance = (decimal)info.TotalTopUp; meter.LJMoney = 0; meter.IsDianHuo = false;//点火标记 false 未点火 meter.IsPricing = false; meter.CreateBillID(); return(this.InsertMeter(meter));//同时插入数据到mongoDB中 }
/// <summary> /// Creates a new OsmSharpRoute enumerable. /// </summary> /// <param name="route"></param> /// <param name="interval"></param> internal RouteEnumerable(Route route, Meter interval) { _route = route; _intervalMeter = interval.Value; }
void slc_MeterRemoved(Slice slc, Meter m) { if(m.Name != "SNR") return; if (_SNRTable.ContainsKey(m)) _SNRTable.Remove(m); m.DataReady -= SNR_DataReady; }
public DataGroup ToDataGroup(Meter meter, byte[] data) { DataGroup dataGroup = new DataGroup(); dataGroup.FromData(meter, data); return dataGroup; }
public static void Stress(int concurrency = 0, int prometheusPort = 0) { #if DEBUG Console.WriteLine("***WARNING*** The current build is DEBUG which may affect timing!"); Console.WriteLine(); #endif if (concurrency < 0) { throw new ArgumentOutOfRangeException(nameof(concurrency), "concurrency level should be a non-negative number."); } if (concurrency == 0) { concurrency = Environment.ProcessorCount; } using var meter = new Meter("OpenTelemetry.Tests.Stress." + Guid.NewGuid().ToString("D")); var cntLoopsTotal = 0UL; meter.CreateObservableCounter( "OpenTelemetry.Tests.Stress.Loops", () => unchecked ((long)cntLoopsTotal), description: "The total number of `Run()` invocations that are completed."); var dLoopsPerSecond = 0D; meter.CreateObservableGauge( "OpenTelemetry.Tests.Stress.LoopsPerSecond", () => dLoopsPerSecond, description: "The rate of `Run()` invocations based on a small sliding window of few hundreds of milliseconds."); var dCpuCyclesPerLoop = 0D; #if NET462 if (Environment.OSVersion.Platform == PlatformID.Win32NT) #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) #endif { meter.CreateObservableGauge( "OpenTelemetry.Tests.Stress.CpuCyclesPerLoop", () => dCpuCyclesPerLoop, description: "The average CPU cycles for each `Run()` invocation, based on a small sliding window of few hundreds of milliseconds."); } using var meterProvider = prometheusPort != 0 ? Sdk.CreateMeterProviderBuilder() .AddMeter(StressMeter.Name) .AddMeter(meter.Name) .AddPrometheusExporter(options => { options.StartHttpListener = true; options.HttpListenerPrefixes = new string[] { $"http://localhost:{prometheusPort}/" }; options.ScrapeResponseCacheDurationMilliseconds = 0; }) .Build() : null; var statistics = new long[concurrency]; var watchForTotal = Stopwatch.StartNew(); Parallel.Invoke( () => { Console.Write($"Running (concurrency = {concurrency}"); if (prometheusPort != 0) { Console.Write($", prometheusEndpoint = http://localhost:{prometheusPort}/metrics/"); } Console.WriteLine("), press <Esc> to stop..."); var bOutput = false; var watch = new Stopwatch(); while (true) { if (Console.KeyAvailable) { var key = Console.ReadKey(true).Key; switch (key) { case ConsoleKey.Enter: Console.WriteLine(string.Format("{0} {1}", DateTime.UtcNow.ToString("O"), output)); break; case ConsoleKey.Escape: bContinue = false; return; case ConsoleKey.Spacebar: bOutput = !bOutput; break; } continue; } if (bOutput) { Console.WriteLine(string.Format("{0} {1}", DateTime.UtcNow.ToString("O"), output)); } var cntLoopsOld = (ulong)statistics.Sum(); var cntCpuCyclesOld = GetCpuCycles(); watch.Restart(); Thread.Sleep(200); watch.Stop(); cntLoopsTotal = (ulong)statistics.Sum(); var cntCpuCyclesNew = GetCpuCycles(); var nLoops = cntLoopsTotal - cntLoopsOld; var nCpuCycles = cntCpuCyclesNew - cntCpuCyclesOld; dLoopsPerSecond = (double)nLoops / ((double)watch.ElapsedMilliseconds / 1000.0); dCpuCyclesPerLoop = nLoops == 0 ? 0 : nCpuCycles / nLoops; output = $"Loops: {cntLoopsTotal:n0}, Loops/Second: {dLoopsPerSecond:n0}, CPU Cycles/Loop: {dCpuCyclesPerLoop:n0}"; Console.Title = output; } }, () => { Parallel.For(0, concurrency, (i) => { statistics[i] = 0; while (bContinue) { Run(); statistics[i]++; } }); }); watchForTotal.Stop(); cntLoopsTotal = (ulong)statistics.Sum(); var totalLoopsPerSecond = (double)cntLoopsTotal / ((double)watchForTotal.ElapsedMilliseconds / 1000.0); var cntCpuCyclesTotal = GetCpuCycles(); var cpuCyclesPerLoopTotal = cntLoopsTotal == 0 ? 0 : cntCpuCyclesTotal / cntLoopsTotal; Console.WriteLine("Stopping the stress test..."); Console.WriteLine($"* Total Loops: {cntLoopsTotal:n0}"); Console.WriteLine($"* Average Loops/Second: {totalLoopsPerSecond:n0}"); Console.WriteLine($"* Average CPU Cycles/Loop: {cpuCyclesPerLoopTotal:n0}"); }
protected virtual void InitializePump() { bytesReadMeter = new BytesReadMeter(this); bytesWrittenMeter = new BytesReadMeter(this); sourceLength = streamProvider.GetSourceLength(); }
// Start is called before the first frame update void Start() { meter = transform.GetComponentInParent <Meter>(); activated = false; }
private Meter ToMeter(XDocument sheet) { double?ToNullableDouble(string str) { if (string.IsNullOrEmpty(str)) { return(null); } return(Convert.ToDouble(str)); } XElement rootElement = sheet.Root; Meter meter = new Meter() { MeterAssets = new List <MeterAsset>(), Channels = new List <Channel>() }; XElement meterElement = rootElement.Element("meter"); meter.ID = Convert.ToInt32((string)meterElement.Element(nameof(meter.ID))); meter.AssetKey = (string)meterElement.Element(nameof(meter.AssetKey)); meter.LocationID = Convert.ToInt32((string)meterElement.Element(nameof(meter.LocationID))); meter.Name = (string)meterElement.Element(nameof(meter.Name)); meter.Alias = (string)meterElement.Element(nameof(meter.Alias)); meter.ShortName = (string)meterElement.Element(nameof(meter.ShortName)); meter.Make = (string)meterElement.Element(nameof(meter.Make)); meter.Model = (string)meterElement.Element(nameof(meter.Model)); meter.TimeZone = (string)meterElement.Element(nameof(meter.TimeZone)); meter.Description = (string)meterElement.Element(nameof(meter.Description)); Location location = new Location() { Meters = new List <Meter>(), AssetLocations = new List <AssetLocation>() }; XElement meterLocationElement = rootElement.Element("location"); location.ID = Convert.ToInt32((string)meterLocationElement.Element(nameof(location.ID))); location.LocationKey = (string)meterLocationElement.Element(nameof(location.LocationKey)); location.Name = (string)meterLocationElement.Element(nameof(location.Name)); location.Alias = (string)meterLocationElement.Element(nameof(location.Alias)); location.ShortName = (string)meterLocationElement.Element(nameof(location.ShortName)); location.Latitude = Convert.ToDouble((string)meterLocationElement.Element(nameof(location.Latitude))); location.Longitude = Convert.ToDouble((string)meterLocationElement.Element(nameof(location.Longitude))); location.Description = (string)meterLocationElement.Element(nameof(location.Description)); location.Meters.Add(meter); meter.Location = location; // This needs to be adjusted to work for Assets of all Types Dictionary <int, Asset> assets = new Dictionary <int, Asset>(); foreach (XElement breakerElement in rootElement.Elements("breaker")) { Breaker breaker = new Breaker() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.Breaker }; breaker.VoltageKV = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.VoltageKV))); breaker.ThermalRating = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.ThermalRating))); breaker.Speed = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.Speed))); breaker.ID = Convert.ToInt32((string)breakerElement.Element(nameof(breaker.ID))); breaker.AssetKey = (string)breakerElement.Element(nameof(breaker.AssetKey)); breaker.Description = (string)breakerElement.Element(nameof(breaker.Description)); breaker.AssetName = (string)breakerElement.Element(nameof(breaker.AssetName)); assets.Add(breaker.ID, breaker); } foreach (XElement busElement in rootElement.Elements("bus")) { Bus bus = new Bus() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.Bus }; bus.VoltageKV = Convert.ToDouble((string)busElement.Element(nameof(bus.VoltageKV))); bus.ID = Convert.ToInt32((string)busElement.Element(nameof(bus.ID))); bus.AssetKey = (string)busElement.Element(nameof(bus.AssetKey)); bus.Description = (string)busElement.Element(nameof(bus.Description)); bus.AssetName = (string)busElement.Element(nameof(bus.AssetName)); assets.Add(bus.ID, bus); } foreach (XElement capacitorBankElement in rootElement.Elements("capacitorBank")) { CapBank capBank = new CapBank() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.CapacitorBank }; capBank.VoltageKV = Convert.ToDouble((string)capacitorBankElement.Element(nameof(capBank.VoltageKV))); capBank.NumberOfBanks = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.NumberOfBanks))); capBank.CansPerBank = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.CansPerBank))); capBank.CapacitancePerBank = Convert.ToDouble((string)capacitorBankElement.Element(nameof(capBank.CapacitancePerBank))); capBank.ID = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.ID))); capBank.AssetKey = (string)capacitorBankElement.Element(nameof(capBank.AssetKey)); capBank.Description = (string)capacitorBankElement.Element(nameof(capBank.Description)); capBank.AssetName = (string)capacitorBankElement.Element(nameof(capBank.AssetName)); assets.Add(capBank.ID, capBank); } foreach (XElement xfrElement in rootElement.Elements("transformer")) { Transformer xfr = new Transformer() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.Transformer }; xfr.ThermalRating = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.ThermalRating))); xfr.SecondaryVoltageKV = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.SecondaryVoltageKV))); xfr.PrimaryVoltageKV = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.PrimaryVoltageKV))); xfr.Tap = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.Tap))); xfr.R0 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.R0))); xfr.X0 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.X0))); xfr.R1 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.R1))); xfr.X1 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.X1))); xfr.ID = Convert.ToInt32((string)xfrElement.Element(nameof(xfr.ID))); xfr.AssetKey = (string)xfrElement.Element(nameof(xfr.AssetKey)); xfr.Description = (string)xfrElement.Element(nameof(xfr.Description)); xfr.AssetName = (string)xfrElement.Element(nameof(xfr.AssetName)); assets.Add(xfr.ID, xfr); } foreach (XElement lineElement in rootElement.Elements("line")) { Line line = new Line() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.Line, Segments = new List <LineSegment>() }; line.VoltageKV = Convert.ToDouble((string)lineElement.Element(nameof(line.VoltageKV))); line.MaxFaultDistance = Convert.ToInt32((string)lineElement.Element(nameof(line.MaxFaultDistance))); line.MinFaultDistance = Convert.ToInt32((string)lineElement.Element(nameof(line.MinFaultDistance))); line.ID = Convert.ToInt32((string)lineElement.Element(nameof(line.ID))); line.AssetKey = (string)lineElement.Element(nameof(line.AssetKey)); line.Description = (string)lineElement.Element(nameof(line.Description)); line.AssetName = (string)lineElement.Element(nameof(line.AssetName)); assets.Add(line.ID, line); } foreach (XElement lineSegmentElement in rootElement.Elements("lineSegment")) { LineSegment lineSegment = new LineSegment() { AssetLocations = new List <AssetLocation>(), MeterAssets = new List <MeterAsset>(), DirectChannels = new List <Channel>(), Connections = new List <AssetConnection>(), AssetTypeID = (int)AssetType.LineSegement }; lineSegment.ThermalRating = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.ThermalRating))); lineSegment.R0 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.R0))); lineSegment.X0 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.X0))); lineSegment.R1 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.R1))); lineSegment.X1 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.X1))); lineSegment.Length = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.Length))); lineSegment.ID = Convert.ToInt32((string)lineSegmentElement.Element(nameof(lineSegment.ID))); lineSegment.AssetKey = (string)lineSegmentElement.Element(nameof(lineSegment.AssetKey)); lineSegment.Description = (string)lineSegmentElement.Element(nameof(lineSegment.Description)); lineSegment.AssetName = (string)lineSegmentElement.Element(nameof(lineSegment.AssetName)); assets.Add(lineSegment.ID, lineSegment); } foreach (XElement assetConnectionElement in rootElement.Elements("assetConnection")) { AssetConnection assetConnection = new AssetConnection(); assetConnection.ID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ID))); assetConnection.ChildID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ChildID))); assetConnection.ParentID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ParentID))); assetConnection.AssetRelationshipTypeID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.AssetRelationshipTypeID))); assets[assetConnection.ChildID].Connections.Add(assetConnection); assets[assetConnection.ParentID].Connections.Add(assetConnection); if (assets[assetConnection.ChildID].AssetTypeID == (int)AssetType.Line && assets[assetConnection.ParentID].AssetTypeID == (int)AssetType.LineSegement) { Line line = (Line)assets[assetConnection.ChildID]; LineSegment lineSegment = (LineSegment)assets[assetConnection.ParentID]; line.Segments.Add(lineSegment); lineSegment.Line = line; assets[assetConnection.ChildID] = line; assets[assetConnection.ParentID] = lineSegment; } else if (assets[assetConnection.ParentID].AssetTypeID == (int)AssetType.Line && assets[assetConnection.ChildID].AssetTypeID == (int)AssetType.LineSegement) { Line line = (Line)assets[assetConnection.ParentID]; LineSegment lineSegment = (LineSegment)assets[assetConnection.ChildID]; line.Segments.Add(lineSegment); lineSegment.Line = line; assets[assetConnection.ParentID] = line; assets[assetConnection.ChildID] = lineSegment; } assetConnection.Child = assets[assetConnection.ChildID]; assetConnection.Parent = assets[assetConnection.ParentID]; } Dictionary <int, Channel> channels = new Dictionary <int, Channel>(); Dictionary <int, MeasurementType> measurementTypes = new Dictionary <int, MeasurementType>(); Dictionary <int, MeasurementCharacteristic> measurementCharacteristics = new Dictionary <int, MeasurementCharacteristic>(); Dictionary <int, Phase> phases = new Dictionary <int, Phase>(); foreach (XElement channelElement in rootElement.Elements("channel")) { Channel channel = new Channel() { Series = new List <Series>() }; channel.ID = Convert.ToInt32((string)channelElement.Element(nameof(channel.ID))); channel.MeterID = Convert.ToInt32((string)channelElement.Element(nameof(channel.MeterID))); channel.AssetID = Convert.ToInt32((string)channelElement.Element(nameof(channel.AssetID))); channel.MeasurementTypeID = Convert.ToInt32((string)channelElement.Element(nameof(channel.MeasurementTypeID))); channel.MeasurementCharacteristicID = Convert.ToInt32((string)channelElement.Element(nameof(channel.ID))); channel.PhaseID = Convert.ToInt32((string)channelElement.Element(nameof(channel.PhaseID))); channel.Name = (string)channelElement.Element(nameof(channel.Name)); channel.SamplesPerHour = Convert.ToDouble((string)channelElement.Element(nameof(channel.SamplesPerHour))); channel.PerUnitValue = ToNullableDouble((string)channelElement.Element(nameof(channel.PerUnitValue))); channel.HarmonicGroup = Convert.ToInt32((string)channelElement.Element(nameof(channel.HarmonicGroup))); channel.Description = (string)channelElement.Element(nameof(channel.Description)); channel.Enabled = Convert.ToBoolean((string)channelElement.Element(nameof(channel.Enabled))); channels.Add(channel.ID, channel); channel.MeasurementType = measurementTypes.GetOrAdd(channel.MeasurementTypeID, id => new MeasurementType() { ID = id, Name = (string)channelElement.Element(nameof(channel.MeasurementType)) }); channel.MeasurementCharacteristic = measurementCharacteristics.GetOrAdd(channel.MeasurementCharacteristicID, id => new MeasurementCharacteristic() { ID = id, Name = (string)channelElement.Element(nameof(channel.MeasurementCharacteristic)) }); channel.Phase = phases.GetOrAdd(channel.PhaseID, id => new Phase() { ID = id, Name = (string)channelElement.Element(nameof(channel.Phase)) }); channel.Meter = meter; meter.Channels.Add(channel); channel.Asset = assets[channel.AssetID]; channel.Asset.DirectChannels.Add(channel); } Dictionary <int, SeriesType> seriesTypes = new Dictionary <int, SeriesType>(); foreach (XElement seriesElement in rootElement.Elements("series")) { Series series = new Series(); series.ID = Convert.ToInt32((string)seriesElement.Element(nameof(series.ID))); series.ChannelID = Convert.ToInt32((string)seriesElement.Element(nameof(series.ChannelID))); series.SeriesTypeID = Convert.ToInt32((string)seriesElement.Element(nameof(series.SeriesTypeID))); series.SourceIndexes = (string)seriesElement.Element(nameof(series.SourceIndexes)); series.SeriesType = seriesTypes.GetOrAdd(series.SeriesTypeID, id => new SeriesType() { ID = id, Name = (string)seriesElement.Element(nameof(series.SeriesType)) }); series.Channel = channels[series.ChannelID]; series.Channel.Series.Add(series); } foreach (XElement assetLocationElement in rootElement.Elements("assetLocation")) { AssetLocation assetLocation = new AssetLocation(); assetLocation.ID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.ID))); assetLocation.LocationID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.LocationID))); assetLocation.AssetID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.AssetID))); assetLocation.Location = location; location.AssetLocations.Add(assetLocation); assetLocation.Asset = assets[assetLocation.AssetID]; assetLocation.Asset.AssetLocations.Add(assetLocation); } foreach (XElement meterAssetElement in rootElement.Elements("meterAsset")) { MeterAsset meterAsset = new MeterAsset(); meterAsset.ID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.ID))); meterAsset.MeterID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.MeterID))); meterAsset.AssetID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.AssetID))); meterAsset.Meter = meter; meter.MeterAssets.Add(meterAsset); meterAsset.Asset = assets[meterAsset.AssetID]; meterAsset.Asset.MeterAssets.Add(meterAsset); } return(meter); }
public MeterSettingsSheet(Meter meter) { Meter = meter; Sheet = ToSheet(meter); }
public TimedQueueCache(QueueId queueId, TimeSpan cacheTimespan, int cacheSize, int numOfBuckets, Logger logger) { _counterMessagesInCache = Metric.Context("KafkaStreamProvider").Counter($"Messages In Cache queueId:({queueId.GetNumericId()})", Unit.Items); _meterCacheEvacuationsPerSecond = Metric.Context("KafkaStreamProvider").Meter($"Cache Evacuations Per Second queueId:({queueId.GetNumericId()})", Unit.Items); _counterNumberOfCursorsCausingPressure = Metric.Context("KafkaStreamProvider").Counter($"Cursors causing pressure queueId:({queueId.GetNumericId()})", Unit.Items); Id = queueId; _cachedMessages = new LinkedList<TimedQueueCacheItem>(); _logger = logger; _cacheCursorHistogram = new List<TimedQueueCacheBucket>(); _maxCacheSize = cacheSize; _cacheHistogramMaxBucketSize = Math.Max(_maxCacheSize / numOfBuckets, 1); _maxNumberToAdd = _cacheHistogramMaxBucketSize; _cacheTimeSpan = cacheTimespan; _bucketTimeSpan = TimeSpan.FromMilliseconds(cacheTimespan.TotalMilliseconds / numOfBuckets); }
private void AddSNRMeter(Slice slc, Meter m) { if (_SNRTable.ContainsKey(m)) return; _SNRTable.Add(m, slc); m.DataReady += new Meter.DataReadyEventHandler(SNR_DataReady); }