public AlarmData(EventSummary eventInfo)
 {
     this.AlarmId              = eventInfo.EventID;
     this.AlarmName            = eventInfo.EventName;
     this.ResourceId           = eventInfo.EventSource + "_" + eventInfo.EventSubject;
     this.ResourceIdName       = eventInfo.EventSource + "_" + eventInfo.EventSubject;
     this.Moc                  = string.Empty;
     this.Sn                   = eventInfo.SerialNumber;
     this.Category             = GetCategory(eventInfo.Severity);
     this.Severity             = GetSeverity(eventInfo.Severity);
     this.OccurTime            = eventInfo.FirstOccurTime;
     this.ClearTime            = eventInfo.ClearTime;
     this.ClearType            = eventInfo.ClearType;
     this.IsClear              = string.Empty;
     this.Status               = eventInfo.Status;
     this.Additional           = eventInfo.EventDescription;
     this.Cause                = string.Empty;
     this.DeviceId             = eventInfo.DeviceID;
     this.EventCategory        = eventInfo.EventCategory;
     this.EventSubject         = eventInfo.EventSubject;
     this.EventDescriptionArgs = eventInfo.EventDescriptionArgs;
     this.PossibleCause        = string.Empty;
     this.Suggstion            = string.Empty;
     this.Effect               = string.Empty;
 }
        private void UpdateTable()
        {
            m_data = new DataTable();
            m_data.Clear();
            m_data.Columns.Add("PMU");
            m_data.Columns.Add("Event");
            m_data.Columns.Add("Number of Occurrences");
            m_data.Columns.Add("Total Active Time (s)");
            m_data.Columns.Add("Shortest Time (s)");
            m_data.Columns.Add("Longest Time (s)");

            foreach (IReader reader in m_readers)
            {
                EventSummary evtSummary = reader.GetEventSummary(m_start, m_end);

                DataRow r = m_data.NewRow();
                r["Event"] = reader.Signal.Device;
                r["Event"] = reader.Signal.Name;
                r["Number of Occurrences"] = evtSummary.Count;
                r["Total Active Time (s)"] = evtSummary.Sum / Gemstone.Ticks.PerSecond;
                r["Shortest Time (s)"]     = evtSummary.Min / Gemstone.Ticks.PerSecond;
                r["Longest Time (s)"]      = evtSummary.Max / Gemstone.Ticks.PerSecond;

                m_data.Rows.Add(r);
            }

            OnPropertyChanged(nameof(DataTable));
        }
Ejemplo n.º 3
0
        public EventSummary Validating(ushort beforeValue, ushort NewValue)
        {
            EventSummary summary = new EventSummary();

            if (beforeValue == NewValue)
            {
                return(summary);
            }
            foreach (ushort EventCode in _evtMaps.Keys)
            {
                ushort evt_flag   = _evtMaps[EventCode];
                bool   beforeFlag = (beforeValue & evt_flag) == evt_flag;
                bool   newFlag    = (NewValue & evt_flag) == evt_flag;
                if (newFlag)
                {
                    summary.ActiveEvents.Add(EventCode);
                }
                if (beforeFlag == newFlag)
                {
                    continue;
                }
                if (beforeFlag == false && newFlag) // 새로운 이벤트 발생
                {
                    summary.NewEvents.Add(EventCode);
                }
                else if (newFlag == false && beforeFlag) // 복구 이벤트
                {
                    summary.RecoverEvents.Add(EventCode);
                }
            }
            return(summary);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a medication item.
        /// </summary>
        /// <param name="code">Medication code.</param>
        /// <param name="name">Medication name.</param>
        /// <param name="directionsNullFlavour">The Directions Null Flavour</param>
        /// <param name="recomendationOrChangeNullFlavour">The Recommendation Or Change Null Flavour</param>
        /// <param name="changeTypeNullFlavour">The Change Type Null Flavour</param>
        /// <returns></returns>
        private static IMedicationItem CreateMedication(string code, string name, bool showNullflavor)
        {
            IMedicationItem medication = EventSummary.CreateMedication();

            if (showNullflavor)
            {
                medication.Directions   = BaseCDAModel.CreateStructuredText(NullFlavour.Other);
                medication.ChangeStatus = BaseCDAModel.CreateCodableText(NullFlavour.Other, CodingSystem.SNOMED, "Change made"); // Could not find ChangeStatus code for the provided refset
                medication.ChangeType   = BaseCDAModel.CreateCodableText(NullFlavour.Other, CodingSystem.SNOMED, "Changed");     // Could not find ChangeType code for the provided refset
            }
            else
            {
                medication.Directions   = BaseCDAModel.CreateStructuredText("Dose:1, Frequency: 3 times daily");
                medication.ChangeStatus = BaseCDAModel.CreateCodableText(ChangeStatus.ChangeMade);
                medication.ChangeType   = BaseCDAModel.CreateCodableText(ChangeTypeSnomed.Changed);
            }

            medication.ChangeDescription  = "Change Description";
            medication.ChangeReason       = BaseCDAModel.CreateStructuredText("Change Reason");
            medication.ClinicalIndication = "Clinical Indication";
            medication.Comment            = "Comment";

            medication.Medicine = BaseCDAModel.CreateCodableText(code, CodingSystem.AMTV3, name);

            return(medication);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates and Hydrates the Medications section for the Event Summary
        ///
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated List of RequestedService</returns>
        private static List <RequestedService> CreateRequestedService(Boolean mandatorySectionsOnly)
        {
            var requestedServiceList = new List <RequestedService>();

            // Create Service Provider for a Person
            var requestedServicePerson = EventSummary.CreateRequestedService();

            requestedServicePerson.ServiceCommencementWindow = BaseCDAModel.CreateInterval(
                new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day),
                new ISO8601DateTime(DateTime.Now.AddMonths(6), ISO8601DateTime.Precision.Day));
            requestedServicePerson.RequestedServiceDescription         = BaseCDAModel.CreateCodableText("399208008", CodingSystem.SNOMED, "Plain chest X-ray");
            requestedServicePerson.ServiceBookingStatus                = EventTypes.AppointmentRequest;
            requestedServicePerson.SubjectOfCareInstructionDescription = "Subject Of Care Instruction Description";
            requestedServicePerson.RequestedServiceDateTime            = new ISO8601DateTime(DateTime.Now.AddDays(4), ISO8601DateTime.Precision.Day);
            requestedServicePerson.ServiceProvider = CreateServiceProviderPerson(mandatorySectionsOnly);

            // Add to list
            requestedServiceList.Add(requestedServicePerson);

            // Create Service Provider for a Organisation
            var requestedServiceOrganisation = EventSummary.CreateRequestedService();

            requestedServiceOrganisation.ServiceScheduled                    = new ISO8601DateTime(DateTime.Now, ISO8601DateTime.Precision.Day);
            requestedServiceOrganisation.RequestedServiceDescription         = BaseCDAModel.CreateCodableText("399208008", CodingSystem.SNOMED, "Plain chest X-ray");
            requestedServiceOrganisation.ServiceBookingStatus                = EventTypes.Intent;
            requestedServiceOrganisation.SubjectOfCareInstructionDescription = "Subject Of Care Instruction Description";
            requestedServiceOrganisation.RequestedServiceDateTime            = new ISO8601DateTime(DateTime.Now.AddDays(4));
            requestedServiceOrganisation.ServiceProvider = CreateServiceProviderOrganisation(mandatorySectionsOnly);

            // Add to list
            requestedServiceList.Add(requestedServiceOrganisation);

            return(requestedServiceList);
        }
Ejemplo n.º 6
0
        public async Task<EventSummary> AddEventSummaryAsync(EventSummary eventSummary)
        {
            try
            {
                var userContext = await GetUserContext().ConfigureAwait(false);
                var httpRequestMessage = new HttpRequestMessage();
                httpRequestMessage = GetDefaultHeaders(httpRequestMessage);
                httpRequestMessage.Method = HttpMethod.Post;

                httpRequestMessage.Headers.Add("Authorization", "BEARER " + userContext.AccessToken);
                httpRequestMessage.RequestUri = new Uri(EventSummaryApi);

                httpRequestMessage.Content = JsonContent.Create(eventSummary, typeof(EventSummary), null, SerializerOptions);

                HttpClient client = new HttpClient();
                _ = await client.SendAsync(httpRequestMessage);

                return await GetEventSummaryAsync(eventSummary.EventId);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(@"\tERROR {0}", ex.Message);
                throw;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates and Hydrates Event Details
        /// </summary>
        /// <returns>A Hydrated IImagingExaminationResult object</returns>
        private static EventDetails CreateEventDetails()
        {
            var eventDetails = EventSummary.CreateEventDetails();

            eventDetails.ClinicalSynopsisDescription = "laceration";
            return(eventDetails);
        }
Ejemplo n.º 8
0
        private void GenerateIndex(int activeFolderIndex)
        {
            if (activeFolderIndex > 0)
            {
                updateIndexSummary(activeFolderIndex);
            }

            if (activeFolderIndex == NLevels)
            {
                return;
            }

            string path = $"{m_rootFolder}{Path.DirectorySeparatorChar}{string.Join(Path.DirectorySeparatorChar, m_activeFolder.Take(activeFolderIndex + 1))}";


            if (m_activeSummary[activeFolderIndex].Count > 0)
            {
                Directory.CreateDirectory(path);
                //write to file
                using (BinaryWriter writer = new BinaryWriter(File.OpenWrite($"{path}{Path.DirectorySeparatorChar}summary.node")))
                {
                    writer.Write(m_activeSummary[activeFolderIndex].ToByte());
                    writer.Flush();
                    writer.Close();
                }
            }

            // reset lower level
            m_activeSummary[activeFolderIndex] = new EventSummary();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates an immunisation.
        /// </summary>
        /// <param name="date">Date of immunisation.</param>
        /// <param name="code">Code of immunisation.</param>
        /// <param name="codingSystem">Coding system for the code.</param>
        /// <param name="name">Name of immunisation.</param>
        /// <param name="sequenceNumber">The immunisation sequence number </param>
        /// <returns>Created immunisation.</returns>
        private static IImmunisation CreateImmunisation(DateTime date, ICodableText codableText, int?sequenceNumber)
        {
            var immunisation = EventSummary.CreateImmunisation();

            immunisation.DateTime       = new ISO8601DateTime(date, ISO8601DateTime.Precision.Day);
            immunisation.Medicine       = codableText;
            immunisation.SequenceNumber = sequenceNumber;
            return(immunisation);
        }
Ejemplo n.º 10
0
        private static EventSummary LoadEventSummary(HtmlNode root)
        {
            var eventSummary = root.Descendants().Where(w => w.InnerText == "Event Summary").FirstOrDefault().ParentNode.ParentNode.Descendants("tr");

            var i  = 0;
            var sb = new StringBuilder();

            foreach (var r in eventSummary)
            {
                foreach (var x in r.Descendants("td"))
                {
                    if (string.IsNullOrWhiteSpace(x.InnerText))
                    {
                        continue;
                    }

                    var value = x.InnerText.Trim().Replace("&nbsp;", null);

                    if (i % 2 == 0)
                    {
                        //Console.Write($"\"{value}\":");
                        sb.Append($"\"{value.FormatEventInfoFieldTitle()}\":");
                    }
                    else
                    {
                        //Console.Write($"\"{value}\",");
                        sb.Append($"\"{value}\",");
                    }

                    i++;
                }
            }

            var plainTextEventSummary = $"{{ {sb} }}";
            var result = JsonConvert.DeserializeObject <EventSummaryDto>(plainTextEventSummary);

            var model = new EventSummary();

            model.Event                            = result.Event.ToEntity();
            model.Location                         = result.Location.Titleize().FormatStateAbbreviation().Trim();
            model.EventDates                       = result.EventDates.Trim();
            model.SponsoringAffiliates             = result.SponsoringAffiliates.ToEntity();
            model.ChiefTournamentDirector          = result.ChiefTournamentDirector.ToEntity();
            model.ChiefAssistantTournamentDirector = result.ChiefAssistantTournamentDirector.ToEntity();
            model.OtherTournamentDirectors         = result.OtherTournamentDirectors.ToEntity();
            model.Processed                        = result.Processed.Trim();

            var stats = result.Stats.Split('\n')[0].Split(',');

            model.NumberOfSections = int.Parse(stats[0].Replace(" Section(s)", null).Trim());
            model.Players          = int.Parse(stats[1].Replace(" Players", null).Trim());

            //Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
            //Console.WriteLine(JsonConvert.SerializeObject(model, Formatting.Indented));

            return(model);
        }
Ejemplo n.º 11
0
 private IEventSummary GenSampleEvents(int lsevent_id, int series_id)
 {
     EventSummary evtsum = new EventSummary();
     EventSummarySeries series = new EventSummarySeries();
     series.Series = "event";
     series.Add(new EventSummaryItem() { Team = "Test Team", TeamScore = 999, TournamentPoints = 9, Rank = 1, GamesPlayed = 2});
     series.Add(new EventSummaryItem() { Team = "Test Team b", TeamScore = 888, TournamentPoints = 8, Rank = 2, GamesPlayed = 2 });
     evtsum.Add("event", series);
     return evtsum;
 }
        private void TestEventSerialization(Event e, LdValue expectedJsonValue)
        {
            var f            = new EventOutputFormatter(new SimpleConfiguration());
            var emptySummary = new EventSummary();

            var outputEvent = LdValue.Parse(f.SerializeOutputEvents(new Event[] { e }, emptySummary, out var count)).Get(0);

            Assert.Equal(1, count);
            Assert.Equal(expectedJsonValue, outputEvent);
        }
        public void SummaryEventIsSerialized()
        {
            var summary = new EventSummary();

            summary.NoteTimestamp(1001);

            summary.IncrementCounter("first", 1, 11, LdValue.Of("value1a"), LdValue.Of("default1"));

            summary.IncrementCounter("second", 1, 21, LdValue.Of("value2a"), LdValue.Of("default2"));

            summary.IncrementCounter("first", 1, 11, LdValue.Of("value1a"), LdValue.Of("default1"));
            summary.IncrementCounter("first", 1, 12, LdValue.Of("value1a"), LdValue.Of("default1"));

            summary.IncrementCounter("second", 2, 21, LdValue.Of("value2b"), LdValue.Of("default2"));
            summary.IncrementCounter("second", null, 21, LdValue.Of("default2"), LdValue.Of("default2"));  // flag exists (has version), but eval failed (no variation)

            summary.IncrementCounter("third", null, null, LdValue.Of("default3"), LdValue.Of("default3")); // flag doesn't exist (no version)

            summary.NoteTimestamp(1000);
            summary.NoteTimestamp(1002);

            var f           = new EventOutputFormatter(new SimpleConfiguration());
            var outputEvent = LdValue.Parse(f.SerializeOutputEvents(new Event[0], summary, out var count)).Get(0);

            Assert.Equal(1, count);

            Assert.Equal("summary", outputEvent.Get("kind").AsString);
            Assert.Equal(1000, outputEvent.Get("startDate").AsInt);
            Assert.Equal(1002, outputEvent.Get("endDate").AsInt);

            var featuresJson = outputEvent.Get("features");

            Assert.Equal(3, featuresJson.Count);

            var firstJson = featuresJson.Get("first");

            Assert.Equal("default1", firstJson.Get("default").AsString);
            TestUtil.AssertContainsInAnyOrder(firstJson.Get("counters").AsList(LdValue.Convert.Json),
                                              LdValue.Parse(@"{""value"":""value1a"",""variation"":1,""version"":11,""count"":2}"),
                                              LdValue.Parse(@"{""value"":""value1a"",""variation"":1,""version"":12,""count"":1}"));

            var secondJson = featuresJson.Get("second");

            Assert.Equal("default2", secondJson.Get("default").AsString);
            TestUtil.AssertContainsInAnyOrder(secondJson.Get("counters").AsList(LdValue.Convert.Json),
                                              LdValue.Parse(@"{""value"":""value2a"",""variation"":1,""version"":21,""count"":1}"),
                                              LdValue.Parse(@"{""value"":""value2b"",""variation"":2,""version"":21,""count"":1}"),
                                              LdValue.Parse(@"{""value"":""default2"",""version"":21,""count"":1}"));

            var thirdJson = featuresJson.Get("third");

            Assert.Equal("default3", thirdJson.Get("default").AsString);
            TestUtil.AssertContainsInAnyOrder(thirdJson.Get("counters").AsList(LdValue.Convert.Json),
                                              LdValue.Parse(@"{""unknown"":true,""value"":""default3"",""count"":1}"));
        }
Ejemplo n.º 14
0
 public SeatsAtEventDate PurchasedSeats(EventSummary eventSummary)
 {
     using (var connection = new SqlConnection(connectionString))
     {
         string queryStringSeat = "INSERT INTO SeatsAtEventDate  (TicketEventDateID) VALUES(@TicketEventDateID)";
         connection.Open();
         connection.Query(queryStringSeat, new { TicketEventDateID = eventSummary.TicketEventDateID });
         var addedSeatsAtEventDateQuery = connection.Query <int>("SELECT IDENT_CURRENT ('SeatsAtEventDate') AS Current_Identity").First();
         return(connection.Query <SeatsAtEventDate>("SELECT * FROM SeatsAtEventDate WHERE SeatID=@Id", new { Id = addedSeatsAtEventDateQuery }).First());
     }
 }
Ejemplo n.º 15
0
        // Update the records of a particular EventSummary
        public async Task <EventSummary> UpdateEventSummary(EventSummary eventSummary)
        {
            eventSummary.LastUpdatedDate           = DateTimeOffset.UtcNow;
            mobDbContext.Entry(eventSummary).State = EntityState.Modified;
            await mobDbContext.SaveChangesAsync().ConfigureAwait(false);

            var summary = await mobDbContext.EventSummaries.FindAsync(eventSummary.EventId).ConfigureAwait(false);

            mobDbContext.Entry(summary).State = EntityState.Detached;
            return(summary);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Adds a SeatAtEventDate to the database.
        /// </summary>
        /// <param name="eventSummary">TicketEventDateId</param>
        /// <returns>SeatId, TicketEventDateId</returns>

        public SeatsAtEventDate PurchasedSeats(EventSummary eventSummary)
        {
            var json    = JsonConvert.SerializeObject(eventSummary);
            var client  = new RestClient(localhost);
            var request = new RestRequest("TicketTransactions/Seat/", Method.POST);

            request.AddParameter("application/json", json, ParameterType.RequestBody);
            var response = client.Execute <SeatsAtEventDate>(request);

            return(response.Data);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// This example populates only the mandatory Sections / Entries; as a result this sample omits all
        /// of the content within the body of the CDA document; as each of the sections within the body
        /// are optional.
        /// </summary>
        public XmlDocument PopulateEventSummarySample_1A(string fileName)
        {
            XmlDocument xmlDoc;

            var document = PopulatedEventSummary(true);

            // Hide Administrative Observations Section
            document.ShowAdministrativeObservationsSection = false;

            document.SCSContent = EventSummary.CreateSCSContent();

            document.IncludeLogo = false;

            var structuredBodyFileList = new List <ExternalData>();

            var structuredBodyFile = BaseCDAModel.CreateStructuredBodyFile();

            structuredBodyFile.Caption = "Structured Body File";
            structuredBodyFile.ExternalDataMediaType = MediaType.PDF;
            structuredBodyFile.Path = StructuredFileAttachment;
            structuredBodyFileList.Add(structuredBodyFile);

            document.SCSContent.StructuredBodyFiles = structuredBodyFileList;

            try
            {
                CDAGenerator.NarrativeGenerator = new CDANarrativeGenerator();

                //Pass the document model into the Generate method
                xmlDoc = CDAGenerator.GenerateEventSummary(document);

                using (var writer = XmlWriter.Create(OutputFolderPath + @"\" + fileName, new XmlWriterSettings()
                {
                    Indent = true
                }))
                {
                    if (!fileName.IsNullOrEmptyWhitespace())
                    {
                        xmlDoc.Save(writer);
                    }
                }
            }
            catch (ValidationException ex)
            {
                //Catch any validation exceptions
                var validationMessages = ex.GetMessagesString();

                //Handle any validation errors as appropriate.
                throw;
            }

            return(xmlDoc);
        }
Ejemplo n.º 18
0
        public async void EventPushing(EventSummary summary)
        {
            if (summary.HasOccurEvent == false)
            {
                return;
            }
            JObject evtRow = summary.CreateJObject();

            _logger?.LogInformation($"RAISE EVENT {evtRow}");

            await PublishAsync(evtRow.ToString());
        }
        public void Save(EventSummary entity)
        {
            try
            {
                IMongoQuery queryBase = Query.And
                                        (
                    Query <EventSummary> .EQ <DateTime>(mem => mem.Date, entity.Date),
                    Query <EventSummary> .EQ <Guid>(mem => mem.ApplicationId, entity.ApplicationId),
                    Query <EventSummary> .EQ <string>(mem => mem.Version, entity.Version),
                    Query <EventSummary> .EQ <PlatformType>(mem => mem.PlatformId, entity.PlatformId)
                                        );

                IMongoUpdate update = Update <EventSummary>
                                      .SetOnInsert(x => x.Version, entity.Version)
                                      .SetOnInsert(x => x.Date, entity.Date)
                                      .SetOnInsert(x => x.ApplicationId, entity.ApplicationId)
                                      .SetOnInsert(x => x.PlatformId, entity.PlatformId)
                                      .Inc(mem => mem.Count, entity.Count);

                this.GetCollection <EventSummary>().FindAndModify(queryBase, SortBy.Descending("Date"), update, false, true);
                this.GetCollection <EventSummary>().EnsureIndex(IndexKeys.Descending("Date"));

                IMongoQuery queryEventInsert = Query.And
                                               (
                    queryBase,
                    Query.NE("ScreenEvents.ScreenAndEvent",
                             BsonValue.Create(entity.ScreenEvents.First().ScreenAndEvent))
                                               );

                IMongoUpdate insertEvent = Update
                                           .Push("ScreenEvents", BsonValue.Create(entity.ScreenEvents.First()
                                                                                  .CopyOnlyKeys().ToBsonDocument()));

                this.GetCollection <EventSummary>().Update(queryEventInsert, insertEvent);


                IMongoQuery queryGetExistingScreenEvents = Query.And
                                                           (
                    queryBase,
                    Query.EQ("ScreenEvents.ScreenAndEvent",
                             BsonValue.Create(String.Concat(entity.ScreenEvents.First().ScreenAndEvent)))
                                                           );

                IMongoUpdate updateScreenEvents = Update
                                                  .Inc("ScreenEvents.$.Count", 1);

                this.GetCollection <EventSummary>().Update(queryGetExistingScreenEvents, updateScreenEvents);
            }
            catch (Exception ex)
            {
                throw new DataAccessLayerException(ex);
            }
        }
Ejemplo n.º 20
0
        public ActionResult Eventsummary(string wishlist_id)
        {
            EventsBLL    oeventBLL = new EventsBLL();
            EventSummary osummary  = new EventSummary();

            osummary = oeventBLL.GetWishlistDetails(wishlist_id, Convert.ToString(Session["UserId"]));
            foreach (var items in osummary.ItemList)
            {
                osummary.total += Convert.ToInt32(items.Item_Tentative_Cost);
            }
            return(PartialView("_EventDetails", osummary));
        }
Ejemplo n.º 21
0
        public void Save_EventSummary_ValuesIncrement()
        {
            EventMapper eventMapper   = new EventMapper(this.client, this.database);
            Guid        applicationId = Guid.NewGuid();
            Guid        deviceId      = Guid.NewGuid();

            EventSummary expected = new EventSummary()
            {
                ApplicationId = applicationId,
                Count         = 2,
                Date          = date,
                PlatformId    = platform,
                Version       = version,
                ScreenEvents  = new List <EventAggregate>()
                {
                    new EventAggregate("someScreen", "someEvent")
                    {
                        Count = 2
                    }
                }
            };

            Event eventItem = new Event()
            {
                ApplicationId       = applicationId,
                Date                = date,
                Version             = version,
                PlatformId          = platform,
                DateCreatedOnDevice = dateCreatedOnDevice,
                ScreenName          = "someScreen",
                EventName           = "someEvent",
                DeviceId            = deviceId,
                DateCreated         = date
            };

            EventSummary summary = new EventSummary(eventItem);

            eventMapper.Save(summary);
            eventMapper.Save(summary);

            IMongoQuery query = Query.And
                                (
                Query <AppUsageSummary> .EQ <DateTime>(mem => mem.Date, date),
                Query <AppUsageSummary> .EQ <Guid>(mem => mem.ApplicationId, applicationId),
                Query <AppUsageSummary> .EQ <string>(mem => mem.Version, version),
                Query <AppUsageSummary> .EQ <PlatformType>(mem => mem.PlatformId, platform)
                                );

            EventSummary actual = this.GetCollection <EventSummary>().FindOne(query);

            actual.ShouldHave().AllPropertiesBut(x => x.Id)
            .IncludingNestedObjects().EqualTo(expected);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creates and Hydrates the adverse substance reactions section for the Event Summary
        ///
        /// Note: the data used within this method is intended as a guide and should be replaced.
        /// </summary>
        /// <returns>A Hydrated List of IAdverseReactionsEventSummay object</returns>
        private static IAdverseReactionsWithoutExclusions CreateAdverseReactions()
        {
            var reactions = EventSummary.CreateAdverseReactions();

            reactions.AdverseSubstanceReaction = new List <Reaction>
            {
                CreateAdverseReaction(BaseCDAModel.CreateCodableText("86461001", CodingSystem.SNOMED, "Plant diterpene")),
                CreateAdverseReaction(BaseCDAModel.CreateCodableText("117491007", CodingSystem.SNOMED, "trans-Nonachlor"))
            };

            return(reactions);
        }
        public void SummarizeEventDoesNothingForIdentifyEvent()
        {
            EventSummarizer es       = new EventSummarizer();
            EventSummary    snapshot = es.Snapshot();

            es.SummarizeEvent(_eventFactory.NewIdentifyEvent(_user));
            EventSummary snapshot2 = es.Snapshot();

            Assert.Equal(snapshot.StartDate, snapshot2.StartDate);
            Assert.Equal(snapshot.EndDate, snapshot2.EndDate);
            Assert.Equal(snapshot.Counters, snapshot2.Counters);
        }
        public void SummarizeEventDoesNothingForCustomEvent()
        {
            EventSummarizer es       = new EventSummarizer();
            EventSummary    snapshot = es.Snapshot();

            es.SummarizeEvent(_eventFactory.NewCustomEvent("whatever", _user, LdValue.Null, null));
            EventSummary snapshot2 = es.Snapshot();

            Assert.Equal(snapshot.StartDate, snapshot2.StartDate);
            Assert.Equal(snapshot.EndDate, snapshot2.EndDate);
            Assert.Equal(snapshot.Counters, snapshot2.Counters);
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            long     unix = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            DateTime dt   = new DateTime(1970, 1, 1).AddSeconds(unix);

            DateTime newdt = dt.ToLocalTime();

            Console.WriteLine("Hello World!");

            MqttAddress address = new MqttAddress();

            address.BindAddress = "www.peiu.co.kr";
            address.Port        = 2084;
            address.QosLevel    = 2;

            string peiu_event_topic = $"hubbub/{6}/Event";

            address.Topic = peiu_event_topic;
            using (EventPusher pusher = new EventPusher(address, true))
            {
                for (int i = 0; i < 8; i++)
                {
                    double pow = Math.Pow(2, i);
                    pusher.AddEvent("PCS_FAULT1", (ushort)(100 + i), (ushort)pow);
                }



                while (true)
                {
                    Console.Write("Input Value: ");
                    string str = Console.ReadLine();
                    if (str.ToUpper() == "QUIT")
                    {
                        break;
                    }
                    ushort iValue;

                    if (ushort.TryParse(str, out iValue))
                    {
                        pusher.BeginProcessing();
                        EventSummary summary = null;
                        bool         isEvent = pusher.ProcessingEvent(6, "Jeju1", "PCS_FAULT1", iValue, ref summary);
                        if (isEvent)
                        {
                            pusher.EventPushing(summary);
                            Console.WriteLine(summary);
                        }
                        pusher.EndProcessing();
                    }
                }
            }
        }
        public async Task <IActionResult> PutEventSummary(EventSummary eventSummary)
        {
            var user = await userRepository.GetUserByInternalId(eventSummary.CreatedByUserId).ConfigureAwait(false);

            if (user == null || !ValidateUser(user.NameIdentifier))
            {
                return(Forbid());
            }

            var updatedEvent = await eventSummaryRepository.UpdateEventSummary(eventSummary).ConfigureAwait(false);

            return(Ok(updatedEvent));
        }
Ejemplo n.º 27
0
        public async Task RunAsync(CancellationToken token)
        {
            while (token.IsCancellationRequested == false)
            {
                EventSummary summary = await _queue.DequeueAsync(token);

                try
                {
                    using (var session = da.SessionFactory.OpenStatelessSession())
                        using (var txn = session.BeginTransaction())
                        {
                            foreach (ushort Code in summary.RecoverEvents)
                            {
                                await RecoverEventAsync(session, summary, Code, token);
                            }


                            foreach (ushort Code in summary.NewEvents)
                            {
                                EventMap map = await session.GetAsync <EventMap>(Code, token);

                                if (map == null)
                                {
                                    _logger.Warn($"DB상에 존재하지 않는 이벤트 코드입니다. 이벤트 코드:{Code}");
                                    continue;
                                }

                                DeviceEvent ae = new DeviceEvent();

                                byte[] descBuffer = Encoding.UTF8.GetBytes(map.Description);
                                ae.DeviceName     = summary.DeviceName;
                                ae.EventId        = CreateEventId(session, summary, Code);
                                ae.EventCode      = Code;
                                ae.OccurTimestamp = summary.GetTimestamp();
                                ae.siteId         = summary.SiteId;
                                await session.InsertAsync(ae, token);
                            }


                            await txn.CommitAsync(token);
                        }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex);
                }
            }
            _logger.Info("Abort RunAsync");
        }
Ejemplo n.º 28
0
        protected override Task OnApplicationMessageReceived(string ClientId, string Topic, string ContentType, uint QosLevel, byte[] payload)
        {
            try
            {
                string  msg      = Encoding.UTF8.GetString(payload);
                JObject json_obj = JObject.Parse(msg);

                EventSummary summary = JsonConvert.DeserializeObject <EventSummary>(msg);
                _queue.QueueWorkItem(summary);
            }
            finally
            {
            }
            return(Task.CompletedTask);
        }
        private EventSummary Aggregate(IEnumerable <EventSummary> points)
        {
            EventSummary pt = new EventSummary();

            pt.Count = points.Sum(item => item.Count);
            pt.Min   = points.Min(item => item.Min);
            pt.Max   = points.Max(item => item.Max);
            pt.Sum   = points.Sum(item => item.Sum);

            pt.Tmax = points.Max(item => item.Tmax);
            pt.Tmin = points.Min(item => item.Tmin);

            pt.Continuation = points.Where(item => item.Tmin == pt.Tmin).FirstOrDefault()?.Continuation ?? false;

            return(pt);
        }
        private List <AdaptEvent> GetPoints(string root, DateTime start, DateTime end)
        {
            List <AdaptEvent> results = new List <AdaptEvent>();

            byte[]       data = File.ReadAllBytes(root);
            EventSummary pt   = new EventSummary(data);

            if (pt.Tmin > end)
            {
                return(new List <AdaptEvent>());
            }
            if (pt.Tmax < start)
            {
                return(new List <AdaptEvent>());
            }

            int index = EventSummary.NSize;


            while (index < data.Length)
            {
                long     ts         = BitConverter.ToInt64(data, index);
                double   value      = BitConverter.ToDouble(data, index + 8);
                double[] parameters = new double[m_parameters.Count()];

                for (int i = 0; i < parameters.Count(); i++)
                {
                    parameters[i] = BitConverter.ToDouble(data, index + 8 + 8 + i * 8);
                }

                Gemstone.Ticks ticks = new Gemstone.Ticks(ts);

                index = index + 8 + 8 + parameters.Count() * 8;

                if (ticks.Value < start.Ticks || ticks.Value > end.Ticks)
                {
                    continue;
                }

                AdaptEvent point = new AdaptEvent(m_guid, ticks, value, m_parameters.Select((key, i) => new KeyValuePair <string, double>(key, parameters[i])).ToArray());
                point.Parameters = parameters;

                results.Add(point);
            }

            return(results);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Creates an adverse reaction.
        /// </summary>
        /// <param name="code">Code for the adverse reaction.</param>
        /// <param name="name">Name of the adverse reaction.</param>
        /// <returns></returns>
        private static Reaction CreateAdverseReaction(ICodableText substanceOrAgent)
        {
            Reaction reaction = EventSummary.CreateReaction();

            reaction.SubstanceOrAgent = substanceOrAgent;

            reaction.ReactionEvent = BaseCDAModel.CreateReactionEvent();
            reaction.ReactionEvent.Manifestations = new List <ICodableText>
            {
                BaseCDAModel.CreateCodableText("248265004", CodingSystem.SNOMED, "Work stress"),
                BaseCDAModel.CreateCodableText("425392003", CodingSystem.SNOMED, "Active advance directive")
            };

            reaction.ReactionEvent.ReactionType = BaseCDAModel.CreateCodableText("419076005", CodingSystem.SNOMED, "Allergic reaction");

            return(reaction);
        }