public void Start()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("AssetRankProvider was disposed.");
            }

            // Gets all attributes from the AttributeTemplate
            AFAttributeList attrList = GetAttributes();

            Console.WriteLine("{0} | Signing up for updates for {1} attributes", DateTime.Now, attrList.Count);
            DataPipe.Subscribe(this);

            // Throw exception on errors
            AFListResults <AFAttribute, AFDataPipeEvent> initEvents = DataPipe.AddSignupsWithInitEvents(attrList);

            if (initEvents.HasErrors)
            {
                throw new Exception("There was an error during signup.", new AggregateException(initEvents.Errors.Values));
            }

            // Initialize the dictionary cache
            foreach (AFDataPipeEvent dpEvent in initEvents)
            {
                OnNext(dpEvent);
            }

            Console.WriteLine("{0} | Signed up for updates for {1} attributes\n", DateTime.Now, attrList.Count);

            _mainTask = Task.Run(() =>
            {
                bool hasMoreEvents = false;

                while (true)
                {
                    if (_ct.IsCancellationRequested)
                    {
                        // The main task in AssetRankProvider is cancelled.
                        _ct.ThrowIfCancellationRequested();
                        // NOTE!!! A "OperationCanceledException was unhandled
                        // by user code" error will be raised here if "Just My Code"
                        // is enabled on your computer. On Express editions JMC is
                        // enabled and cannot be disabled. The exception is benign.
                        // Just press F5 to continue executing your code.
                    }

                    AFErrors <AFAttribute> results = DataPipe.GetObserverEvents(out hasMoreEvents);

                    if (results != null)
                    {
                        Console.WriteLine("Errors in GetObserverEvents: {0}", results.ToString());
                    }

                    if (!hasMoreEvents)
                    {
                        Thread.Sleep(_threadSleepTimeInMilliseconds);
                    }
                }
            }, _ct);
        }
Exemple #2
0
        /// <summary>
        /// Deletes the PI Points matching the name filter.
        /// </summary>
        /// <param name="nameFilter">Name filter to use when deleting PI Points.</param>
        /// <param name="output">The output logger used for writing messages.</param>
        public void DeletePIPoints(string nameFilter, ITestOutputHelper output)
        {
            Contract.Requires(output != null);

            var pointList = new List <PIPoint>();

            pointList.AddRange(PIPoint.FindPIPoints(PIServer, nameFilter));

            if (pointList.Count <= 0)
            {
                output.WriteLine($"Did not find any PI Points to delete with name filter [{nameFilter}].");
            }
            else
            {
                output.WriteLine($"PI Points with name filter [{nameFilter}] found. Removing from [{PIServer.Name}].");
            }

            // Process PI Points in pages
            int i = 0;

            foreach (IList <PIPoint> pointGroup in pointList.GroupBy(name => i++ / PointPageSize).Select(g => g.ToList()))
            {
                AFErrors <string> errors = PIServer.DeletePIPoints(pointGroup.Select(pt => pt.Name));
                if (errors != null)
                {
                    throw errors.Errors.First().Value;
                }
            }
        }
Exemple #3
0
        public AFErrors <AFAttribute> Start()
        {
            // Subscribe this object (Observer) to the AFDataPipe (Observable)
            DataPipe.Subscribe(this);

            // The data pipe will provide updates from attributes inside AttributeList
            AFErrors <AFAttribute> errors = DataPipe.AddSignups(AttributeList);

            if (errors != null)
            {
                return(errors);
            }
            else
            {
                // This task loop calls GetObserverEvents every 5 seconds
                Task mainTask = Task.Run(() =>
                {
                    bool hasMoreEvents = false;
                    while (true)
                    {
                        AFErrors <AFAttribute> results = DataPipe.GetObserverEvents(out hasMoreEvents);
                        if (!hasMoreEvents)
                        {
                            Thread.Sleep(_threadSleepTimeInMilliseconds);
                        }
                    }
                });
                return(null);
            }
        }
        public void UpdateValues(AFValues cityValues)
        {
            AFErrors <AFValue> errors = AFListData.UpdateValues(cityValues, AFUpdateOption.NoReplace);

            if ((errors != null) && (errors.HasErrors))
            {
                log.Error(errors.Errors.First().Value.Message);
            }
        }
        public void Flush()
        {
            var sw = Stopwatch.StartNew();

            int numValuesWritten           = 0;
            AFErrors <AFValue> writeErrors = null;

            try
            {
                // Write results with "Replace" mode. Ideally you would first want to delete existing data and then publish new results, in order to make sure we don't end up with mixed old & new events.
                writeErrors       = AFListData.UpdateValues(_values, AFUpdateOption.Replace);
                numValuesWritten += _values.Count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to publish outputs using bulk call. {0}", ex.Message);
                return;
            }
            finally
            {
                _values.Clear();
            }

            if (!ReferenceEquals(writeErrors, null) && writeErrors.HasErrors)
            {
                foreach (var afError in writeErrors.PISystemErrors)
                {
                    Console.WriteLine("Error while writing outputs to AF Server {0}. {1}", afError.Key, afError.Value.Message);
                }

                foreach (var piError in writeErrors.PIServerErrors)
                {
                    Console.WriteLine("Error while writing outputs to Data archive {0}. {1}", piError.Key, piError.Value.Message);
                }

                if (writeErrors.Errors.Count > 0)
                {
                    numValuesWritten -= writeErrors.Errors.Count;
                    Console.WriteLine("{0} Errors when publishing output results.", writeErrors.Errors.Count);
                    foreach (var error in writeErrors.Errors)
                    {
                        Console.WriteLine("/t{0}: {1}", error.Key.Attribute.Name, error.Value.Message);
                    }
                }
            }

            Console.WriteLine("Published {0} values. ({1} ms)", numValuesWritten, sw.ElapsedMilliseconds);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            // Connect to the AF server and database
            PISystem   myAF = new PISystems()["DNG-AF2014"];
            AFDatabase myDB = myAF.Databases["Dev Support"];

            // Create attribute list for attributes to be signed up for AFDataPipe
            AFElement           myElement    = myDB.Elements["CDR"];
            AFAttribute         myAttribute1 = myElement.Attributes["cdt158"];
            AFAttribute         myAttribute2 = myElement.Attributes["SQLDRTest"];
            AFAttribute         myAttribute3 = myElement.Attributes["SQLDRTest2"];
            IList <AFAttribute> attrList     = new List <AFAttribute>();

            attrList.Add(myAttribute1);
            attrList.Add(myAttribute2);
            attrList.Add(myAttribute3);

            // Get new events continuously until users enter any key in the console window
            using (AFDataPipe myDataPipe = new AFDataPipe())
            {
                myDataPipe.AddSignups(attrList);
                IObserver <AFDataPipeEvent> observer = new DataPipeObserver();
                myDataPipe.Subscribe(observer);
                bool more = false;

                // create a cancellation source to terminate the update thread when the user is done
                CancellationTokenSource cancellationSource = new CancellationTokenSource();
                Task task = Task.Run(() =>
                {
                    // keep polling while the user hasn't requested cancellation
                    while (!cancellationSource.IsCancellationRequested)
                    {
                        // Get updates from pipe and process them
                        AFErrors <AFAttribute> myErrors = myDataPipe.GetObserverEvents(out more);

                        // wait for 1 second using the handle provided by the cancellation source
                        cancellationSource.Token.WaitHandle.WaitOne(1000);
                    }
                }, cancellationSource.Token);

                Console.ReadKey();
                Console.WriteLine("Exiting updates");
                cancellationSource.Cancel();

                // wait for the task to complete before taking down the pipe
                task.Wait();
            }
        }
Exemple #7
0
        /// <summary>
        /// Sends a number of events to each PI Point in a PI Point list.
        /// </summary>
        /// <remarks>
        /// By default the events' timestamp increments by 1 second and the values are calculated from the timestamps.
        /// If the eventsToSend parameter is specified then those events are used explicitly.
        /// </remarks>
        /// <param name="startTime">Start time used for event time stamps.</param>
        /// <param name="eventCount">Number of events to write to PI Data Archive.</param>
        /// <param name="piPoints">List of PI Points to which events will be written.</param>
        /// <param name="eventsToSend">OPTIONAL events to use (instead of being generated by routine).</param>
        public void SendTimeBasedPIEvents(AFTime startTime, int eventCount, List <PIPoint> piPoints, Dictionary <DateTime, double> eventsToSend = null)
        {
            // Build PI events as needed
            if (eventsToSend == null)
            {
                DateTime st = startTime;
                eventsToSend = new Dictionary <DateTime, double>();
                for (int i = 0; i < eventCount; i++)
                {
                    DateTime ts = st.AddSeconds(i);
                    eventsToSend.Add(ts, PIFixture.ConvertTimeStampToFloat(ts));
                }
            }

            object[]        vals       = eventsToSend.Values.Cast <object>().ToArray();
            DateTime[]      timeStamps = eventsToSend.Keys.ToArray();
            AFValueStatus[] statuses   = Enumerable.Range(0, eventCount).Select(_ => AFValueStatus.Good).ToArray();
            UOM             nullUOM    = null;

            var newValues = new List <AFValues>();
            var pointList = new PIPointList(piPoints);

            foreach (PIPoint pt in pointList)
            {
                var newAFValues = new AFValues(vals, timeStamps, statuses, nullUOM)
                {
                    PIPoint = pt,
                };
                newValues.Add(newAFValues);
            }

            if (newValues.Count == 0)
            {
                return;
            }

            // Send PI events
            foreach (AFValues values in newValues)
            {
                AFErrors <AFValue> errors = PIServer.UpdateValues(values.ToList(), AFUpdateOption.NoReplace);
                if (errors != null)
                {
                    throw errors.Errors.First().Value;
                }
            }
        }
Exemple #8
0
		public WAFErrors(AFErrors<AFValue> valErrs)
		{
			if (valErrs == null)
			{
				m_genericErrs = new string[0, 0];
			} 
			else
			{
				m_genericErrs = new string[valErrs.Errors.Count, 1];
				int key = 0;

				foreach (AFValue item in valErrs.Errors.Keys)
				{
					m_genericErrs[key, 0] = item.Timestamp.ToString();
					m_genericErrs[key, 1] = valErrs.Errors[item].Message;
					key++;
				}
			}
		}