Beispiel #1
0
        private int ReviewStatus_AFEventFrameSearch_CalculateCountOnAllTurbines(int reviewStatus, string windFarmName)
        {
            var templateName  = "EFTCMVibrationEvent";
            var attributeName = "ReviewStatus";

            AFStopwatch stopwatch          = new AFStopwatch();
            var         afEventFrameSearch = new AFEventFrameSearch(_afDatabase, "MyQuery", "ElementName:" + windFarmName + " Template:" + templateName + " |" + attributeName + ":=" + reviewStatus + " SortField:ID");

            var countDictionary = new Dictionary <string, int>();

            IEnumerable <AFEventFrame> efs = afEventFrameSearch.FindEventFrames(pageSize: pagesize);

            //Console.WriteLine("Done : " + efs.Count() + ", " + stopwatch.ElapsedMilliseconds + "ms");

            var eventFramesGroupedByPrimaryReferencedElementNames = efs.GroupBy(ef => ef.PrimaryReferencedElement.Name);

            foreach (var eventFrameGroup in eventFramesGroupedByPrimaryReferencedElementNames)
            {
                countDictionary[eventFrameGroup.Key] = eventFrameGroup.Count();
            }

            //Console.WriteLine("Done2 : " + efs.Count() + ", " + stopwatch.ElapsedMilliseconds + "ms");
            return(stopwatch.ElapsedMilliseconds);

            //_log.Info($"Time:{stopwatch.Elapsed.TotalSeconds}, Template:{templateName}, {attributeName}:{reviewStatus}, Element:{windFarmName}, Element Count: {countDictionary.Keys.Count}, EventFrame Count:{countDictionary.Sum(e => e.Value)}");

            //foreach (var counts in countDictionary)
            //{
            //    _log.Info($"{counts.Key}:{counts.Value}");
            //}
        }
Beispiel #2
0
        protected override List <Action> GetActions()
        {
            List <Action> actions = Constants.ClassificationIds.Select(classificationId => (Action)(() =>
            {
                var actionStopwatch = new AFStopwatch();
                actionStopwatch.Start();

                string query = $"Template:EFOutageClassification |Id:={classificationId}  SortField:ID";
                // Sometimes we use AFSearchMode.StartInclusive other times AFSearchMode.Overlapped. StartInclusive we use when a start and end time is provided
                // Is there a performance difference?
                var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "ASearch", query);
                var maxCount = 1000;
                var eventFrames = afEventFrameSearch.FindEventFrames(0, true, maxCount).Take(maxCount).ToList();
                var count = eventFrames.Count;

                TestOutput.AddActionResult(
                    new ActionPerformanceResult
                {
                    ActionMillis = actionStopwatch.ElapsedMilliseconds,
                    ResultCount = count
                });
            })).ToList();

            return(actions);
        }
        public LimitCalculation(CalculationPreference preference)
        {
            this.preference = preference;
            string afattributepath = preference.sensorPath;
            string eventQuery      = preference.eventFrameQuery;

            calculationsToPerform = preference.getTraitDictionary();

            foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform)
            {
                bounds[pair.Key] = new AFValues();
            }
            sensor    = AFAttribute.FindAttribute(afattributepath, null);
            pisystem  = sensor.PISystem;
            afdatabse = sensor.Database;
            foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform)
            {
                boundAttributes[pair.Key] = sensor.GetAttributeByTrait(pair.Key);
            }

            eventFrameQuery = new AFEventFrameSearch(afdatabse, "eventFrameSearch", eventQuery);
            List <AFSearchToken> tokens = eventFrameQuery.Tokens.ToList();

            tokens.RemoveAll(t => t.Filter == AFSearchFilter.InProgress || t.Filter == AFSearchFilter.Start || t.Filter == AFSearchFilter.End);
            timeLessQuery = new AFEventFrameSearch(afdatabse, "AllEventFrames", tokens);
            InitialRun();
        }
        public static void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }
            if (eventFrameTemplate == null)
            {
                throw new ArgumentNullException(nameof(eventFrameTemplate));
            }

            // Formulate search constraints on time and template
            AFTime startTime   = DateTime.Today.AddDays(-7);
            string queryString = $"template:\"{eventFrameTemplate.Name}\"";

            using (AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, queryString))
            {
                eventFrameSearch.CacheTimeout = TimeSpan.FromMinutes(5);
                int count = 0;
                foreach (AFEventFrame item in eventFrameSearch.FindObjects())
                {
                    item.CaptureValues();
                    if ((count++ % 500) == 0)
                    {
                        database.CheckIn();
                    }
                }

                if (database.IsDirty)
                {
                    database.CheckIn();
                }
            }
        }
Beispiel #5
0
        protected override List <Action> GetActions()
        {
            if (ElementNames == null)
            {
                ElementNames = new[] { string.Empty };
            }

            var           templateFilter = string.IsNullOrEmpty(TemplateName) ? string.Empty : $"Template:{TemplateName}";
            List <Action> actions        = ElementNames.Select(elementName => (Action)(() =>
            {
                var actionStopwatch = new AFStopwatch();
                actionStopwatch.Start();

                var elementNameFilter = elementName != String.Empty ? $"ElementName:{elementName}" : String.Empty;
                string query = $"{elementNameFilter} {templateFilter} {ValueQuery}  SortField:ID";
                // Sometimes we use AFSearchMode.StartInclusive other times AFSearchMode.Overlapped. StartInclusive we use when a start and end time is provided
                // Is there a performance difference?
                var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "ASearch", query);
                var maxCount = 1000;
                var eventFrames = afEventFrameSearch.FindEventFrames(0, true, maxCount).Take(maxCount).ToList();
                var count = eventFrames.Count;

                TestOutput.AddActionResult(
                    new ActionPerformanceResult
                {
                    ActionMillis = actionStopwatch.ElapsedMilliseconds,
                    ResultCount = count
                });
            })).ToList();

            return(actions);
        }
        public static void PrintReport(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }
            if (eventFrameTemplate == null)
            {
                throw new ArgumentNullException(nameof(eventFrameTemplate));
            }
            AFTime startTime   = DateTime.Today.AddDays(-7);
            AFTime endTime     = startTime.LocalTime.AddDays(+8); // Or DateTime.Today.AddDays(1);
            string queryString = $"template:'{eventFrameTemplate.Name}' ElementName:Meter003";

            using (AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFSearchMode.StartInclusive, startTime, endTime, queryString))
            {
                eventFrameSearch.CacheTimeout = TimeSpan.FromMinutes(5);
                foreach (AFEventFrame ef in eventFrameSearch.FindObjects())
                {
                    Console.WriteLine("{0}, {1}, {2}",
                                      ef.Name,
                                      ef.PrimaryReferencedElement.Name,
                                      ef.Attributes["Average Energy Usage"].GetValue().Value);
                }
            }
        }
        public void PrintReportEx5()
        {
            using (StringWriter sw = new StringWriter())
            {
                Console.SetOut(sw);
                var eventFrameTemplate = Ex5WorkingWithEventFramesSln.Program5.CreateEventFrameTemplate(Database);
                Assert.NotNull(eventFrameTemplate);
                Ex5WorkingWithEventFramesSln.Program5.CreateEventFrames(Database, eventFrameTemplate);

                AFTime startTime   = DateTime.Today.AddDays(-7);
                string queryString = $"template:\"{eventFrameTemplate.Name}\"";
                using (AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(Database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, queryString))
                {
                    eventFrameSearch.CacheTimeout = TimeSpan.FromMinutes(5);
                    var resp = eventFrameSearch.FindObjects();
                    Assert.True(resp.Any());
                }

                Ex5WorkingWithEventFramesSln.Program5.CaptureValues(Database, eventFrameTemplate);
                Ex5WorkingWithEventFramesSln.Program5.PrintReport(Database, eventFrameTemplate);
                var actual = sw.ToString();
                Assert.Contains("Daily Usage-Meter", actual);
                Assert.Contains(", Meter003,", actual);
            }
        }
Beispiel #8
0
 public LimitCalculation(CalculationPreference preference, string calculationName)
 {
     this.calculationName = calculationName;
     try {
         logger.Info($"Starting calculations for {calculationName}");
         string afattributepath = preference.sensorPath;
         string eventQuery      = preference.eventFrameQuery;
         calculationsToPerform = preference.getTraitDictionary();
         offset          = preference.offset;
         this.preference = preference;
         sensor          = AFAttribute.FindAttribute(afattributepath, null);
         pisystem        = sensor.PISystem;
         afdatabase      = sensor.Database;
         foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform)
         {
             bounds[pair.Key] = new AFValues();
             AFAttribute possibleAttribute = sensor.GetAttributeByTrait(pair.Key);
             boundAttributes[pair.Key] = possibleAttribute;
             logger.Info($"Will perform calculation for limit: {pair.Key}");
             if (possibleAttribute == null)
             {
                 logger.Error($"{calculationName}: The limit {pair.Key} is not defined yet is used.");
             }
         }
         eventFrameQuery = new AFEventFrameSearch(afdatabase, "eventFrameSearch", eventQuery);
     }
     catch (System.Exception e)
     {
         logger.Error($"{calculationName} the following error occured: {e.Message}");
     }
     logger.Info($"{calculationName}: Doing the initial run");
     InitialRun();
 }
Beispiel #9
0
        /// <summary>
        /// Remove the event frame by name if it exists.
        /// </summary>
        /// <param name="name">The name of the event frame to remove.</param>
        /// <param name="output">The output logger used for writing messages.</param>
        public void RemoveEventFrameIfExists(string name, ITestOutputHelper output)
        {
            Contract.Requires(output != null);

            AFEventFrame preCheckEventFrame = null;

            using (var search = new AFEventFrameSearch(AFDatabase, string.Empty, $"Name:'{name}'"))
            {
                var searchResults = new AFNamedCollectionList <AFEventFrame>(search.FindObjects());
                if (searchResults.Count > 0)
                {
                    preCheckEventFrame = searchResults.First();
                }
            }

            if (preCheckEventFrame?.Name.Equals(name, StringComparison.OrdinalIgnoreCase) ?? false)
            {
                output.WriteLine($"Event Frame [{preCheckEventFrame}] exists, delete it.");
                preCheckEventFrame.Delete();
                preCheckEventFrame.CheckIn();
            }
            else
            {
                output.WriteLine($"Event Frame [{name}] does not exist, can not be deleted.");
            }
        }
        /// <summary>
        /// Performs an event frame search based on a query string
        /// </summary>
        /// <param name="query">Valid AF query</param>
        /// <param name="pageSize">Pagesize (Defaults to 1000)</param>
        private void RunEFQuery(string query, int pageSize = 1000)
        {
            AFDatabase db = Fixture.AFDatabase;

            using (var search = new AFEventFrameSearch(
                       database: db,
                       name: "EFQueryTest",
                       query: query))
            {
                int startIndex = 0;

                var coll                = search.FindObjects(startIndex: startIndex, pageSize: pageSize);
                int totalEFExamined     = 0;
                int valuesCapturedCount = 0;
                foreach (AFEventFrame ef in coll)
                {
                    totalEFExamined++;

                    if (ef.AreValuesCaptured)
                    {
                        valuesCapturedCount++;
                    }
                }

                Output.WriteLine($"Found {totalEFExamined} Event Frames in [{db.GetPath()}] for a query of [{query}].");
                Output.WriteLine($"{valuesCapturedCount} Event Frame's AreValuesCaptured are true.");
            }
        }
Beispiel #11
0
        internal static AFEventFrameSearch currentEventFrame(AFEventFrameSearch query)
        {
            List <AFSearchToken> tokens = query.Tokens.ToList();

            tokens.RemoveAll(t => t.Filter == AFSearchFilter.InProgress || t.Filter == AFSearchFilter.AllDescendants || t.Filter == AFSearchFilter.End || t.Filter == AFSearchFilter.Start || t.Filter == AFSearchFilter.Duration);
            AFSearchToken inprogress = new AFSearchToken(AFSearchFilter.InProgress, AFSearchOperator.Equal, "True");

            tokens.Add(inprogress);
            return(new AFEventFrameSearch(query.Database, "CurrentEventFrame", tokens));
        }
        private void Button_Click(object sender, RoutedEventArgs re)
        {
            //parse the start and end times
            AFTime startTime, endTime;

            if (AFTime.TryParse(StartDate.Text, out startTime) && AFTime.TryParse(EndDate.Text, out endTime))
            {
                //find event frames with the event frame template in the time slot
                var search = new AFEventFrameSearch(db, "Find", AFSearchMode.Overlapped, startTime, endTime, $"Template:={eventFrameTemplate.Name}");
                List <AFEventFrame> efs = search.FindEventFrames().OrderBy(ef => ef.Attributes[matchingAttribute].GetValue().ValueAsInt32()).ToList();

                //read in csv file
                List <CSVLine> lines = new List <CSVLine>();
                using (var reader = new StreamReader(CSV.Text))
                {
                    while (!reader.EndOfStream)
                    {
                        var line  = reader.ReadLine();
                        var split = line.Split(',');

                        int id;
                        if (int.TryParse(split[0], out id))
                        {
                            lines.Add(new CSVLine(id, split[1]));
                        }
                    }
                }
                lines = lines.OrderBy(line => line.ID).ToList();

                //iterate through lines of csv
                //match identifier column with "matchingAttribute"
                int e = 0, l = 0;
                while (e < efs.Count && l < lines.Count)
                {
                    int ef_id   = efs[e].Attributes[matchingAttribute].GetValue().ValueAsInt32();
                    int line_id = lines[l].ID;
                    if (ef_id == line_id)
                    {
                        //match -- update
                        efs[e].Attributes["Attribute1"].SetValue(new AFValue(lines[l].Value));
                        l++;
                        e++;
                    }
                    else if (ef_id > line_id)
                    {
                        l++;
                    }
                    else
                    {
                        e++;
                    }
                }
            }
        }
        public static IEnumerable <AFEventFrame> FindDowntimeEvents(AFDatabase afdb, string relayName, bool InProgress)
        {
            var eventSearch = new AFEventFrameSearch(afdb, "Template Search", $"Template:'Downtime' Name:{relayName}* InProgress:{InProgress}");
            var events      = eventSearch.FindEventFrames();

            foreach (var item in events)
            {
                Console.WriteLine($"Event Found {item.Name}, time: {item.StartTime} - {item.EndTime} Duration: {item.Duration}");
            }
            return(events);
        }
        internal void InitialRun()
        {
            ComputeStatistics();
            AFEventFrameSearch currentEventFrameQuery = new AFEventFrameSearch(afdatabse, "currentEvent", eventFrameQuery.Tokens.ToList());

            currentEventFrameQuery.Tokens.Add(new AFSearchToken(AFSearchFilter.InProgress, AFSearchOperator.Equal, "True"));
            IEnumerable <AFEventFrame> currentEventFrames = currentEventFrameQuery.FindEventFrames(0, true, int.MaxValue);

            foreach (AFEventFrame currentEventFrame in currentEventFrames)
            {
                WriteValues(currentEventFrame.StartTime);
            }
        }
Beispiel #15
0
        private int ReviewStatus_AFEventFrameSearch_GetTotalCount(object value, string elementName = null)
        {
            var templateName  = "EFTCMBaseEvent";
            var attributeName = "ReviewStatus";

            AFStopwatch stopwatch = new AFStopwatch();

            string elementNameFilter  = elementName != null ? "ElementName:" + elementName + " " : string.Empty;
            var    afEventFrameSearch = new AFEventFrameSearch(_afDatabase, "MyQuery" + value, elementNameFilter + "Template:" + templateName + " |" + attributeName + ":=" + value /* + " SortField:ID"*/);

            var count = afEventFrameSearch.GetTotalCount();

            //Console.WriteLine("Done : " + count + ", " + stopwatch.ElapsedMilliseconds + "ms");
            return(stopwatch.ElapsedMilliseconds);
            //_log.Info($"time:{stopwatch.Elapsed.TotalSeconds}, Template:{templateName}, {attributeName}: {value}, Element:{elementName}, count:{count}");
        }
        static void PrintReport(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            DateTime           timereference    = DateTime.Now.AddDays(-7);
            AFTime             startTime        = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
            AFTime             endTime          = startTime.LocalTime.AddDays(+8);
            string             query            = string.Format("template:\"{0}\" ElementName:\"{1}\"", eventFrameTemplate.Name, "Meter003");
            AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFSearchMode.StartInclusive, startTime, endTime, query);

            foreach (AFEventFrame ef in eventFrameSearch.FindEventFrames())
            {
                Console.WriteLine("{0}, {1}, {2}",
                                  ef.Name,
                                  ef.PrimaryReferencedElement.Name,
                                  ef.Attributes["Average Energy Usage"].GetValue().Value);
            }
        }
        public void EventFrameSearchTest()
        {
            AFDatabase db = Fixture.AFDatabase;

            string baseEFNameText      = $"OSIsoftTests_AF_EFSrchTst - {DateTime.UtcNow.ToString(AFFixture.DateTimeFormat, CultureInfo.InvariantCulture)}_";
            string ef1Name             = $"{baseEFNameText}EF1";
            string ef2Name             = $"{baseEFNameText}EF2";
            string ef3Name             = $"{baseEFNameText}LastEF";
            string eventFrameSearchTxt = $"'{baseEFNameText}EF*'";

            try
            {
                Output.WriteLine($"Create Event Frames for search.");
                _ = new AFEventFrame(db, ef1Name);
                _ = new AFEventFrame(db, ef2Name);
                _ = new AFEventFrame(db, ef3Name);
                db.CheckIn();

                Output.WriteLine($"Execute search for Event Frames using search string [{eventFrameSearchTxt}].");
                db = Fixture.ReconnectToDB(); // This operation clears AFSDK cache and assures retrieval from AF server
                using (var searchResults = new AFEventFrameSearch(db, string.Empty, eventFrameSearchTxt))
                {
                    int       actualEventsFramesFound = searchResults.GetTotalCount();
                    const int ExpectedEventFrames     = 2;
                    Assert.True(actualEventsFramesFound == ExpectedEventFrames, $"Search string [{eventFrameSearchTxt}] found " +
                                $"{actualEventsFramesFound} Event Frames, expected {ExpectedEventFrames}.");

                    int actualEventFramesFoundWithSearch = 0;
                    foreach (AFEventFrame at in searchResults.FindObjects())
                    {
                        actualEventFramesFoundWithSearch++;
                    }

                    Assert.True(actualEventFramesFoundWithSearch == ExpectedEventFrames,
                                $"Only able to find {actualEventFramesFoundWithSearch} Elements returned using Search string " +
                                $"[{eventFrameSearchTxt}], expected {ExpectedEventFrames}.");
                }
            }
            finally
            {
                Fixture.RemoveEventFrameIfExists(ef1Name, Output);
                Fixture.RemoveEventFrameIfExists(ef2Name, Output);
                Fixture.RemoveEventFrameIfExists(ef3Name, Output);
            }
        }
Beispiel #18
0
        internal void InitialRun()
        {
            currentFrameQuery = currentEventFrame(eventFrameQuery);
            ComputeStatistics();
            //AFEventFrameSearch currentEventFrameQuery = currentEventFrame(eventFrameQuery);

            IEnumerable <AFEventFrame> currentEventFrames = currentFrameQuery.FindEventFrames(0, true, int.MaxValue);

            try {
                foreach (AFEventFrame currentEventFrame in currentEventFrames)
                {
                    WriteValues(currentEventFrame.StartTime);
                }
            }
            catch (System.Exception e)
            {
                logger.Error($"{calculationName} : Was not able to write initial data due {e.Message}");
            }
        }
Beispiel #19
0
        internal bool timelessMatch(AFEventFrameSearch query, AFEventFrame ef)
        {
            List <AFSearchToken> tokens = query.Tokens.ToList();

            tokens.RemoveAll(t => t.Filter == AFSearchFilter.InProgress || t.Filter == AFSearchFilter.Start || t.Filter == AFSearchFilter.End || t.Filter == AFSearchFilter.Duration);

            AFEventFrameSearch timeless = new AFEventFrameSearch(query.Database, "AllEventFrames", tokens);

            logger.Debug($"{calculationName} : Attemps to match {timeless.ToString()} on event {ef.Name}");
            try
            {
                return(timeless.IsMatch(ef));
            }
            catch (System.FormatException e)
            {
                logger.Error($"There was an error with the query: {e.Message}");
                return(false);
            }
        }
Beispiel #20
0
        private int AFEventFrameSearch(string templateName, string elementName = null, string attributeName = null, object value = null)
        {
            AFStopwatch stopwatch = new AFStopwatch();

            string elementNameFilter = elementName != null ? "ElementName:" + elementName + " " : string.Empty;
            string query             = $"Template:{templateName} SortField:ID";

            if (elementName != null)
            {
                query += $" ElementName:{elementName}";
            }

            if (attributeName != null)
            {
                query += $" |{attributeName}:={value}";
            }

            var afEventFrameSearch = new AFEventFrameSearch(_afDatabase, "MyQuery" + value, query);

            if (pageCount != 0)
            {
                afEventFrameSearch.CacheTimeout = TimeSpan.FromSeconds(30);
                for (int page = 0; page < pageCount; page++)
                {
                    var afEventFrames = afEventFrameSearch.FindEventFrames(startIndex: page * pagesize, fullLoad: false, pageSize: pagesize)
                                        .ToList();
                    //var uniqueIds = afEventFrames.Select(ef => ef.Attributes["SourceSystemUniqueId"]);
                    //Console.WriteLine($"Page:{page + 1}, PageSize:{pagesize}, EFCount:{afEventFrames.Count}");
                }
            }
            else
            {
                var afEventFrames = afEventFrameSearch.FindEventFrames(fullLoad: false, pageSize: pagesize).ToList();
                //var uniqueIds = afEventFrames.Select(ef => ef.Attributes["SourceSystemUniqueId"]);
                //Console.WriteLine($"EFCount:{afEventFrames.Count}");
            }

            //Console.WriteLine("Done : " + afEventFrames.Count + ", " + stopwatch.ElapsedMilliseconds + "ms");
            return(stopwatch.ElapsedMilliseconds);

            //_log.Info($"time:{stopwatch.Elapsed.TotalSeconds}, Template:{templateName}, {attributeName}:{value}, Element:{elementName}, count:{afEventFrames.Count}");
        }
Beispiel #21
0
        private List <AFEventFrame> GetEventFramesFromAfEventFrameSearch(string templateName, string elementName,
                                                                         string attributeName,
                                                                         object value)
        {
            string query = $"Template:{templateName} SortField:ID";

            if (elementName != null)
            {
                query += $" ElementName:{elementName}";
            }

            if (attributeName != null)
            {
                query += $" |{attributeName}:={value}";
            }

            var afEventFrameSearch = new AFEventFrameSearch(AfDatabase, "MyQuery" + value, AFSearchMode.StartInclusive, Start, End,
                                                            query);

            return(afEventFrameSearch.FindEventFrames().ToList());
        }
        static public void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            // Formulate search constraints on time and template
            DateTime           timereference    = DateTime.Now.AddDays(-7);
            AFTime             startTime        = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
            string             query            = string.Format("template:\"{0}\"", eventFrameTemplate.Name);
            AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, query);

            int startIndex = 0;

            foreach (AFEventFrame item in eventFrameSearch.FindEventFrames())
            {
                item.CaptureValues();
                if ((startIndex++ % 512) == 0)
                {
                    database.CheckIn();
                }
            }

            database.CheckIn();
        }
Beispiel #23
0
        private void lbNotificationRules_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Selected notification rule
            AFNotificationRule SelectedNotificationRule = lbNotificationRules.SelectedItem as AFNotificationRule;

            // Clear the notificaiton list
            lbNotificationInstances.Items.Clear();

            // Check empty Selected
            if (SelectedNotificationRule == null)
            {
                return;
            }

            // Get information from Notification Rule Selected;
            AFTime     startTime     = new AFTime(tbStart.Text);
            AFTime     endTime       = new AFTime(tbEnd.Text);
            AFElement  targetElement = SelectedNotificationRule.Target;
            AFDatabase database      = SelectedNotificationRule.Database;


            // Consulting the dataBase
            string             query  = string.Format("Element: '{0}' {1}", targetElement.GetPath(database), SelectedNotificationRule.Criteria);
            AFEventFrameSearch search = new AFEventFrameSearch(database, "", AFSearchMode.Overlapped, startTime, endTime, query);

            search.CacheTimeout = TimeSpan.FromMinutes(5);

            IEnumerable <AFEventFrame> instances = search.FindEventFrames(fullLoad: false);

            // Populate the eventframe listbox

            foreach (AFEventFrame instance in instances)
            {
                string s = string.Format("Element: {0}, \t{1}, \t{2}"
                                         , targetElement.Name
                                         , instance.StartTime.LocalTime
                                         , instance.EndTime == AFTime.MaxValue ? "Event is ongoing": instance.EndTime.LocalTime.ToString());
                lbNotificationInstances.Items.Add(s);
            }
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            NetworkCredential credential = new NetworkCredential(connectionInfo.user, connectionInfo.password);
            var piSystem = (new PISystems())[connectionInfo.AFServerName];

            piSystem.Connect(credential);
            var afdb = piSystem.Databases[connectionInfo.AFDatabaseName];


            //using tokens
            List <AFSearchToken> tokenList = new List <AFSearchToken>();

            tokenList.Add(new AFSearchToken(AFSearchFilter.Template, AFSearchOperator.Equal, "Low Contaiment Strength"));
            tokenList.Add(new AFSearchToken(AFSearchFilter.Name, AFSearchOperator.Equal, "T001*"));
            var tokenSearch = new AFEventFrameSearch(afdb, "Template Search", tokenList);


            //using search string
            //var query = "Template:'Low Contaiment Strength' Name:T001*";
            //var stringSearch = new AFEventFrameSearch(afdb, "Template Search", query);


            var results = tokenSearch.FindEventFrames(0, false, 10);
            var counter = 0;

            foreach (var item in results)
            {
                Console.WriteLine($"Event {item.Name}, time: {item.StartTime} - {item.EndTime} Duration: {item.Duration}");
                counter++;
                if (counter > 9)
                {
                    break;
                }
            }


            Console.ReadKey();
        }
Beispiel #25
0
        //Get instances, which are Event Frames beginning with PI Notifications 2016
        private void FindNotificationInstances()
        {
            gridNotificationInstances.Rows.Clear();

            if (!btnView.Enabled)
            {
                return;
            }

            var rule      = lboxNotificationRules.SelectedItem as AFNotificationRule;
            var startTime = tbStartTime.Tag as AFTime?;
            var endTime   = tbEndTime.Tag as AFTime?;

            var database = Element.Database;

            //We echo the current notification rule search criteria, which includes literal "Criteria:"
            //but include the Target element in the filter.
            string             query  = string.Format("Element:'{0}' {1}", Element.GetPath(database), rule.Criteria);
            AFEventFrameSearch search = new AFEventFrameSearch(database, "", AFSearchMode.Overlapped, startTime.Value, endTime.Value, query);

            search.CacheTimeout = TimeSpan.FromMinutes(5);
            IEnumerable <AFEventFrame> instances = search.FindEventFrames(fullLoad: true);

            //Populate listbox with notification instances, which are just event frames in PI Notifications 2016 or later.
            foreach (AFEventFrame instance in instances)
            {
                // For multi-trigger analyses, the "Start Trigger Name" would be null on the parent event frame if there were multiple triggers.
                // We should suppress those.  Note the "Start Trigger Name" is our default attribute.
                object defaultObject = instance.DefaultAttribute?.GetValue() ?? (object)string.Empty;
                if (!string.IsNullOrWhiteSpace(defaultObject.ToString()))
                {
                    object endObject = (instance.EndTime == AFTime.MaxValue) ? (object)"ongoing/active" : instance.EndTime.LocalTime;
                    gridNotificationInstances.Rows.Add(instance.StartTime.LocalTime, endObject, defaultObject);
                }
            }
        }
        static public void CaptureValues(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            // Formulate search constraints on time and template
            DateTime timereference = DateTime.Now.AddDays(-7);
            AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
            string query = string.Format("template:\"{0}\"", eventFrameTemplate.Name);
            AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFEventFrameSearchMode.ForwardFromStartTime, startTime, query);

            int startIndex = 0;
            foreach (AFEventFrame item in eventFrameSearch.FindEventFrames())
            {
                item.CaptureValues();
                if ((startIndex++ % 512) == 0)
                    database.CheckIn();
            }

            database.CheckIn();
        }
        static void PrintReport(AFDatabase database, AFElementTemplate eventFrameTemplate)
        {
            DateTime timereference = DateTime.Now.AddDays(-7);
            AFTime startTime = new AFTime(new DateTime(timereference.Year, timereference.Month, timereference.Day, 0, 0, 0, DateTimeKind.Local));
            AFTime endTime = startTime.LocalTime.AddDays(+8);
            string query = string.Format("template:\"{0}\" ElementName:\"{1}\"", eventFrameTemplate.Name, "Meter003");
            AFEventFrameSearch eventFrameSearch = new AFEventFrameSearch(database, "EventFrame Captures", AFSearchMode.StartInclusive, startTime, endTime, query);

            foreach (AFEventFrame ef in eventFrameSearch.FindEventFrames())
            {
                Console.WriteLine("{0}, {1}, {2}",
                    ef.Name,
                    ef.PrimaryReferencedElement.Name,
                    ef.Attributes["Average Energy Usage"].GetValue().Value);
            }
        }