public static int sleepTimePerAnalysis = 1 * 100; // in milliseconds static void Main(string[] args) { var af = new PISystems().DefaultPISystem; var db = af.Databases.DefaultDatabase; var service = af.AnalysisService; StreamReader file = new StreamReader("c:\\kit\\utilities.txt"); string line; while ((line = file.ReadLine()) != null) { Console.WriteLine(line); var search = new AFAnalysisSearch(db, null, line); IEnumerable <AFAnalysis> analyses = search.FindAnalyses(); Console.WriteLine($"Found: {analyses.Count()} analyses."); // start all found analyses foreach (var analysis in analyses) { analysis.SetStatus(AFStatus.Enabled); } // status does not return information in this version var status = service.QueueCalculation(analyses, timeRange, AFAnalysisService.CalculationMode.DeleteExistingData); Thread.Sleep(sleepTimePerAnalysis * analyses.Count()); } file.Close(); }
static void Main(string[] args) { PISystems myPISystems = new PISystems(); PISystem myPISystem = myPISystems[EventFrameTest.Properties.Settings.Default.AFSystemName]; object sysCookie, dbCookie; AFDatabases myDBs = myPISystem.Databases; AFDatabase myDB = myDBs[EventFrameTest.Properties.Settings.Default.AFDBName]; myPISystem.FindChangedItems(false, int.MaxValue, null, out sysCookie); myDB.FindChangedItems(false, int.MaxValue, null, out dbCookie); // Find changes made while application not running. List <AFChangeInfo> list = new List <AFChangeInfo>(); list.AddRange(myPISystem.FindChangedItems(false, int.MaxValue, sysCookie, out sysCookie)); list.AddRange(myDB.FindChangedItems(false, int.MaxValue, dbCookie, out dbCookie)); // Refresh objects that have been changed. AFChangeInfo.Refresh(myPISystem, list); foreach (AFChangeInfo info in list) { AFChangeInfoAction ac = info.Action; AFObject myObj = info.FindObject(myPISystem, true); AFIdentity myID = myObj.Identity; if (myID == AFIdentity.EventFrame && ac == AFChangeInfoAction.Added) { Console.WriteLine("Found changed object: {0}", myObj); } } Console.ReadLine(); }
static void Main(string[] args) { var system = new PISystems().DefaultPISystem; var db = system.Databases.DefaultDatabase; var dataArchive = new PIServers().DefaultPIServer; StopService("PIAnalysisManager", 10000); var archiveAttr = db.Elements["PI Data Archive"].Attributes["Name"]; if (archiveAttr != null) { archiveAttr.SetValue(new AFValue(dataArchive.Name)); } archiveAttr = db.Elements["PI Data Archive"].Attributes["名"]; if (archiveAttr != null) { archiveAttr.SetValue(new AFValue(dataArchive.Name)); } db.CheckIn(); foreach (var elem in db.Elements) { createConfig(elem); } db.CheckIn(); Thread.Sleep(1000); foreach (var category in new List <string> { "Random Data", "Usage", "Cost", "Downtime" }) { ProgrammaticAnalysisRecalculation(system, db, db.AnalysisCategories[category]); } StartService("PIAnalysisManager", 10000); }
bool attemptLogin(ResolveFieldContext context, string piSystemName) { PISystems piSystems = new PISystems(); if (!piSystems.Contains(piSystemName)) { context.Errors.Add(new ExecutionError($"PISystem {piSystemName} not found.")); return(false); } else { aPiSystem = piSystems[piSystemName]; try { aPiSystem.Connect(getCreds(context)); } catch (Exception e) { context.Errors.Add(new ExecutionError($"Connection to PiSystem {piSystemName} failed - Connect() failed.")); } if (aPiSystem.ConnectionInfo.IsConnected) { return(true); } else { context.Errors.Add(new ExecutionError($"Connection to PiSystem {piSystemName} failed - IsConnected() is false.")); return(false); } } }
static AFDatabase GetDatabase(string server, string database) { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems[server]; AFDatabase afDatabase = piSystem.Databases[database]; return afDatabase; }
static void Main(string[] args) { try { PISystems piSystems = new PISystems(); string AFServer = ConfigurationManager.AppSettings.Get("AFServer"); PISystem assetServer = piSystems[AFServer]; PIServers piServers = new PIServers(); string PIServer = ConfigurationManager.AppSettings.Get("DataArchiveServer"); PIServer piServer = piServers[PIServer]; //AFElement.LoadAttributes() if (assetServer == null) { Console.WriteLine("Cannot Find AF Server: {0}", AFServer); Console.ReadLine(); Environment.Exit(0); } if (piServer == null) { Console.WriteLine("Cannot Find PI Data Server: {0}", PIServer); Console.ReadLine(); Environment.Exit(0); } if (assetServer != null && piServer != null) { //AFDatabase database = assetServer.Databases["Demo UOG Well Drilling & Completion Monitoring"]; //AFDatabase database = assetServer.Databases["AARA OEE Demo"]; // PrintElementTemplates(database); // PrintAttributeTemplates(database, "Batch Context Template"); // PrintEnergyUOMs(assetServer); // PrintEnumerationSets(database); // PrintCategories(database); // FindMetersBYTemplate(database, "Line"); // TimeSpan test = new TimeSpan(0, 1, 0); //Program6.PrintInterpolated(database, "Inlet Pump", "14-Nov-18 16:15:00", "14-Nov-18 17:15:00.000000", test); //Program6.CreateFeedersRootElement(database); // Program6.CreateFeederElements(database); //DataPipeSubscribeExample.Run(piServer); Console.WriteLine("Connected Successfully to PI Server: {0} and AF Server: {1}", PIServer, AFServer); //Subscribe.DataPipeSubscribeExample.Run1(); UseCase_DataPipe.Run(piServer); Console.ReadLine(); } } catch (Exception ex) { Logs Err = new Logs(); Err.MyLogFile(ex); Console.WriteLine("An Error has occured for details please check the Log File: '" + ex.Message + "'"); Console.ReadLine(); } }
static void Main(string[] args) { logger.Info("The application has started."); PISystem pisystem = new PISystems().DefaultPISystem; pisystem.Connect(); logger.Info($"Connecting as: {pisystem.CurrentUserIdentityString}"); AFDatabase configuration = pisystem.Databases["Configuration"]; AFElements preferences = configuration.Elements["LimitCalculator"].Elements; logger.Info($"Will process {preferences.Count} preferences"); List <DatabaseMonitoring> monitoredDB = new List <DatabaseMonitoring> { }; Parallel.ForEach(preferences, (preference) => { string JSON = (string)preference.Attributes["configuration"].GetValue().Value; logger.Info($"Configuration for preference: {JSON}"); LimitCalculation calc = new LimitCalculation(CalculationPreference.CalculationPreferenceFromJSON(JSON), preference.Name); monitoredDB.Add(new DatabaseMonitoring(calc)); }); WaitForQuit(); }
static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { // Command values are available here suffix = options.suffix; var systems = new PISystems(); var system = systems.DefaultPISystem; var olddb = system.Databases.DefaultDatabase; var xml = system.ExportXml(olddb, PIExportMode.AllReferences); AFDatabase newdb; if (options.timesuffix) { newdb = system.Databases.Add(olddb.Name + " " + suffix + " " + DateTime.Now.ToString("mm")); } else { newdb = system.Databases.Add(olddb.Name + " " + suffix); } system.ImportXml(newdb, PIImportMode.PasteOperation, xml); system.Databases.DefaultDatabase = newdb; newdb.CheckIn(); system.CheckIn(); } }
/// <summary> /// Creates an instance of the AFFixture class. /// </summary> public AFFixture() { var systems = new PISystems(); if (systems.Contains(Settings.AFServer)) { PISystem = systems[Settings.AFServer]; PISystem.Connect(); } else { throw new InvalidOperationException( $"The specific AF Server [{Settings.AFServer}] does not exist or is not configured."); } if (PISystem.Databases.Contains(Settings.AFDatabase)) { AFDatabase = PISystem.Databases[Settings.AFDatabase]; } else { throw new InvalidOperationException( $"The specific AF database [{Settings.AFDatabase}] does not exist or is not configured."); } }
static void Main(string[] args) { PISystem local = new PISystems().DefaultPISystem; resetToTemplate(local.Databases.DefaultDatabase); //AFDatabaseEditsCheck.runTests(local, resetToTemplate); }
static void Main(string[] args) { PISystems myPISystems = new PISystems(); PISystem myPISystem = myPISystems.DefaultPISystem; if (myPISystem == null) { throw new InvalidOperationException("Default PISystem was not found."); } AFDatabase myDB = myPISystem.Databases["PE"]; if (myDB == null) { throw new InvalidOperationException("Database was not found."); } AFElement element = myDB.Elements["El"]; int count; using (var search = new AFAnalysisSearch(myDB, "MyAnalysisSearch", string.Format(@"Target:'{0}'", element.GetPath()))) { search.CacheTimeout = TimeSpan.FromMinutes(10); count = search.GetTotalCount(); Console.WriteLine("Found {0} Analyses", count); foreach (var item in search.FindObjects(fullLoad: true)) { Console.Write("Analysis Name = {0},", item.Name); Console.Write("Analysis Description = {0},", item.Description); Console.Write("Analysis Target = {0}", item.Target); Console.WriteLine(); } } }
static void Main(string[] args) { var db = new PISystems().DefaultPISystem.Databases.DefaultDatabase; var analyses = new AFAnalysisSearch(db, null, "*"); foreach (var analysis in analyses.FindAnalyses()) analysis.SetStatus(AFStatus.Disabled); }
public void ObserveGarbageCollectorBehavior() { #region Case One AFGlobalSettings.CacheMaxObjects = 100; PISystems systems = new PISystems(true); AFElement myElement = systems.Find <AFElement>(elementPath); WeakReference <AFElement> myRef = new WeakReference <AFElement>(myElement); myElement = null; GC.Collect(); Assert.True(myRef.TryGetTarget(out myElement)); #endregion #region Case Two AFGlobalSettings.CacheMaxObjects = 0; systems = new PISystems(true); myElement = systems.Find <AFElement>(elementPath); myRef = new WeakReference <AFElement>(myElement); myElement = null; GC.Collect(); Assert.False(myRef.TryGetTarget(out myElement)); #endregion }
public AFDatabase InitializeAf() { //отключил олицетворение клиента, код выполняется от учетки пула using (WindowsIdentity.Impersonate(IntPtr.Zero)) { try { var myPiSystem = new PISystems(true).DefaultPISystem; if (myPiSystem == null) { throw new InvalidOperationException("Default PISystem was not found."); } myPiSystem.Connect(); currentDb = myPiSystem.Databases["Database"]; return(currentDb); } catch (Exception) { return(null); } } // }
public override void Run() { try { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems[Server]; piSystem.Connect(true, null); Logger.InfoFormat("Connected to AF Server {0}", Server); Logger.InfoFormat("Creating the new database {0} ...", Database); if (piSystem.Databases.Contains(Database)) { throw new Exception("The database already exists. Cannot create the new database."); } piSystem.Databases.Add(Database); Logger.InfoFormat("Database creation completed"); } catch (Exception ex) { Logger.Error(ex); } }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; AFElementTemplate boilerTemplate = afDatabase.ElementTemplates["Boiler"]; const int pageSize = 1000; int startIndex = 0; int totalCount; do { // Find a collection of elements instantiated from the Boiler tempplate. // Only the Elements' header information (Name, Description, Template, Type, etc.) // are loaded from the AF Server by this call. AFNamedCollection<AFElement> elements = AFElement.FindElements( database: afDatabase, searchRoot: null, query: "Boiler", field: AFSearchField.Template, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); if (elements == null) break; // Partially load the element by retrieving information only for the Water Flow attribute. AFElement.LoadAttributes(elements, new[] { boilerTemplate.AttributeTemplates["Water Flow"] }); Console.WriteLine("Found {0} Elements.", elements.Count); AFAttributeList attrList = new AFAttributeList(); // Because we are retrieving the Water Flow attribute which was previously loaded, // no additional server calls are made. // If LoadAttributes had not been called previously, then a server call would have been made for each element // in the loop below. foreach (AFElement item in elements) { attrList.Add(item.Attributes["Water Flow"]); } AFValues values = attrList.GetValue(); Console.WriteLine(" Water Flow values"); foreach (AFValue val in values) { Console.WriteLine(" Element: {0}, Timestamp: {1}, Value: {2}", val.Attribute.Element, val.Timestamp, val.Value.ToString()); } startIndex += pageSize; } while (startIndex < totalCount); }
static AFDatabase GetDatabase(string server, string database) { PISystems piSystems = new PISystems(); PISystem assetServer = piSystems[server]; AFDatabase afDatabase = assetServer.Databases[database]; return(afDatabase); }
private static PISystem GetPISystem(PISystems systems = null, string systemname = null) { systems = systems == null ? new PISystems() : systems; if (!string.IsNullOrEmpty(systemname)) return systems[systemname]; else return systems.DefaultPISystem; }
static void Main() { PISystems myPISystems = new PISystems(); PISystem myPISystem = myPISystems.DefaultPISystem; Console.WriteLine("Please Enter the name of the AF Database"); string resp = Console.ReadLine(); AFDatabase myAFDB = myPISystem.Databases[resp]; //Console.WriteLine("Please Enter a search start time"); //string starttime = Console.ReadLine(); //Console.WriteLine("Please Enter a search end time"); //string endtime = Console.ReadLine(); bool MaxedEF; int loopcount = 0; Stopwatch stopWatch = new Stopwatch(); do { ++loopcount; Console.WriteLine("current loops count: {0}. Last iteration in ms: {1}", loopcount, stopWatch.ElapsedMilliseconds); //Console.WriteLine("current loops count: {0}.", loopcount); stopWatch.Reset(); stopWatch.Start(); OSIsoft.AF.AFNamedCollectionList <AFEventFrame> EventFrameList = AFEventFrame.FindEventFrames(myAFDB, null, null, AFSearchField.Description, true, AFSortField.StartTime, AFSortOrder.Ascending, 1000, 1000); if (EventFrameList.Count == 1000) { MaxedEF = true; } else { MaxedEF = false; } Parallel.ForEach(EventFrameList, EventFrame => { // Try Deleting the Event Frame try { EventFrame.Delete(); EventFrame.CheckIn(); Console.WriteLine("Sucessfully Deleted Event Frame: {0}", EventFrame.Name); } catch { Console.WriteLine("Error, unable to Delete Event Frame: {0}", EventFrame.Name); } }); stopWatch.Stop(); }while (MaxedEF == true); Console.WriteLine("Press Enter to Exit"); Console.ReadKey(); }
private void ImplicitConnection() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; // At this point, no connection is made. AFAttribute afAttribute = AFAttribute.FindAttribute(@"NuGreen\NuGreen\Houston|Environment", piSystem); // Now a connection is made by first data access. }
private void AFServer_Loaded(object sender, RoutedEventArgs e) { PISystems ps = new PISystems(); //set the items in the box to display the available servers AFServer.ItemsSource = ps; AFServer.DisplayMemberPath = "Name"; AFServer.SelectedItem = ps.DefaultPISystem; }
private void ImplicitConnection() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; // At this point, no connection is made. AFAttribute afAttribute = AFAttribute.FindAttribute(@"NuGreen\NuGreen\Houston|Environment", piSystem); // Now a connection is made by first data access. }
public static T Find <T>(this PISystems systems, string path) where T : AFObject { if (systems.DefaultPISystem == null) { throw new InvalidOperationException("Default PISystem must be set."); } return(AFObject.FindObject(path, systems.DefaultPISystem) as T); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["Basic-AFSDK-Sample"]; CreateEventFrameTemplate(afDatabase); CreateEventFrames(afDatabase); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["Basic-AFSDK-Sample"]; CreateEventFrameTemplate(afDatabase); CreateEventFrames(afDatabase); }
public void DisableAFCache() { AFGlobalSettings.CacheMaxObjects = 0; AFGlobalSettings.CacheTime = 0; PISystems systems = new PISystems(true); AFElement element1 = systems.Find <AFElement>(elementPath); AFElement element2 = systems.Find <AFElement>(elementPath); Assert.Same(element1, element2); }
private void ExplicitConnection() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; // At this point, no connection is made. piSystem.Connect(); // Now a connection is made by explicit call. AFAttribute afAttribute = AFAttribute.FindAttribute(@"NuGreen\NuGreen\Houston|Environment", piSystem); }
static void Main(string[] args) { PISystems myPISystems = new PISystems(); PISystem myPISystem = myPISystems.DefaultPISystem; if (myPISystem == null) { throw new InvalidOperationException("Default PISystem was not found."); } Console.WriteLine("Version of the PISystems = {0}", myPISystems.Version); }
static void Main(string[] args) { PISystem local = new PISystems().DefaultPISystem; AFDatabase db = local.Databases.DefaultDatabase; AFTable translation = db.Tables["Translations"]; local.ExportXml(translation, PIExportMode.AllReferences, @"..\translation.xml", null, null, null); AFTable uomconversion = db.Tables["UOM Conversion"]; local.ExportXml(uomconversion, PIExportMode.AllReferences, @"..\uomConversion.xml", null, null, null); }
private static (bool, string) SMTPServerIsConfigured() { if (_piSystem == null) { var systems = new PISystems(); if (systems.Contains(Settings.AFServer)) { _piSystem = systems[Settings.AFServer]; _piSystem.Connect(); } else { return(false, $"The AF Server [{Settings.AFServer}] does not exist or is not configured."); } } var configurationDb = _piSystem.Databases.ConfigurationDatabase; if (configurationDb != null) { if (configurationDb.Elements.Contains(OSIsoft)) { var pianoElement = configurationDb.Elements[OSIsoft].Elements[PIANO]; if (pianoElement != null) { var emailPlugInElement = pianoElement.Elements[DeliveryChannel]; if (emailPlugInElement != null) { var subEmailPlugInElement = emailPlugInElement.Elements[PlugInGuid]; if (subEmailPlugInElement != null) { if (ElementHasValidAttribute(subEmailPlugInElement, SMTPServer) && ElementHasValidAttribute(subEmailPlugInElement, SMTPServerPort)) { return(true, null); } return(false, "The email PlugIn doesn't have a valid SMTP server configuration."); } return(false, $"The [{PlugInGuid}] element is not found in the [{DeliveryChannel}] element in the configuration database."); } return(false, $"The [{DeliveryChannel}] element is not found in the [{PIANO}] element in the configuration database."); } return(false, $"The [{PIANO}] element is not found in the [{OSIsoft}] element in the configuration database."); } return(false, $"The [{OSIsoft}] element is not found in the configuration database."); } return(false, "The configuration database is not found."); }
/// <summary> /// This example creates a sample AF database from basic element and attribute templates. /// </summary> /// <prerequisite-examples> /// none /// </prerequisite-examples> public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases.Add("Basic-AFSDK-Sample"); CreateTemplates(afDatabase); CreateEnumerationSet(afDatabase); CreateElements(afDatabase); CreatePIPoints(afDatabase); }
/// <summary> /// This example creates a sample AF database from basic element and attribute templates. /// </summary> /// <prerequisite-examples> /// none /// </prerequisite-examples> public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases.Add("Basic-AFSDK-Sample"); CreateTemplates(afDatabase); CreateEnumerationSet(afDatabase); CreateElements(afDatabase); CreatePIPoints(afDatabase); }
static AFDatabase GetDatabase(string servername, string databasename) { PISystems piafsystems = new PISystems(); PISystem system = piafsystems[servername]; if (system != null && system.Databases.Contains(databasename)) { Console.WriteLine("Found '{0}' with '{1}' databases", system.Name, system.Databases.Count); return system.Databases[databasename]; } else return null; }
public void EFPerform1() { PISystems myPISystems = new PISystems(); PISystem myPISystem = myPISystems.DefaultPISystem; myPISystem.Connect(); Console.WriteLine("SDK: {0}, Server: {1}", myPISystems.Version, myPISystem.ServerVersion); _afDatabase = myPISystem.Databases["DongEnergyWind_performance"];//myPISystem.Databases.DefaultDatabase; Console.WriteLine(_afDatabase.Name); }
private void ExplicitConnection() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; // At this point, no connection is made. piSystem.Connect(); // Now a connection is made by explicit call. AFAttribute afAttribute = AFAttribute.FindAttribute(@"NuGreen\NuGreen\Houston|Environment", piSystem); }
static PISystem GetPISystem(PISystems systems = null, string systemName = null) { systems = systems == null ? new PISystems() : systems; if (!string.IsNullOrEmpty(systemName)) { return(systems[systemName]); } else { return(systems.DefaultPISystem); } }
static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { // Command values are available here language = options.language; } PISystem system = new PISystems().DefaultPISystem; AFDatabase db = system.Databases.DefaultDatabase; convertTagNaming(db); }
public MainWindow() { PISystems piSystems = new PISystems(); aPiSystem = piSystems.DefaultPISystem; InitializeComponent(); Closed += MainWindow_Closed; InitializeComponent(); msalAuthHelper = new MsalAuthHelper(); RefreshSignInStatus(); }
private static AFDatabase CreateDatabase(string servername, string databasename) { AFDatabase database = null; PISystems piafsystems = new PISystems(); PISystem system = piafsystems[servername]; if (system != null) { if (system.Databases.Contains(databasename)) database = system.Databases[databasename]; else database = system.Databases.Add(databasename); } return database; }
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(); } }
static void Main(string[] args) { PISystems piSystems = new PISystems(); foreach (PISystem piSystem in piSystems) { piSystem.Connect(); Console.WriteLine("Nome do AF Server: {0}, TZ: {1}, Version: {2}", piSystem.Name, piSystem.ServerTimeZone, piSystem.ServerVersion); } PISystem defaultPISystem = piSystems.DefaultPISystem; Console.WriteLine("\nAF Databases\n"); foreach (AFDatabase db in defaultPISystem.Databases) { Console.WriteLine("Nome do AFDatabase: {0}", db.Name); } AFDatabase afDb = defaultPISystem.Databases["Magical Power Company"]; Console.WriteLine("\nRoot Elements\n"); foreach (AFElement element in afDb.Elements) { Console.WriteLine("Nome dos elementos raízes: {0}", element.Name); } Console.WriteLine("\nBasic Meter Elements\n"); foreach (AFElement element in afDb.Elements["Meters"].Elements.Where(m => m.Template.Name == "MeterBasic")) { Console.WriteLine("Nome dos elementos secundários: {0}, templates: {1}", element.Name, element.Template.Name); } Console.WriteLine("\nBasic Meter Attributes\n"); foreach (AFAttribute attribute in afDb.Elements["Meters"].Elements[0].Attributes) { Console.WriteLine("Nome dos attributos: {0}, data reference: {1}, configString: {2}", attribute.Name, attribute.DataReferencePlugIn == null ? "No DR!" : attribute.DataReferencePlugIn.Name, attribute.ConfigString); } AFAttribute myAttribute = AFObject.FindObject(@"\\PISRV01\Magical Power Company\Meters\Meter001|Energy Usage") as AFAttribute; AFElementTemplate elementTemplate = myAttribute.Element.Template; AFAttributeTemplate attributeTemplate = myAttribute.Template; bool fullLoad = true; var elements = AFElement.FindElementsByTemplate(afDb, null, elementTemplate, false, AFSortField.ID, AFSortOrder.Ascending, 100); if (fullLoad) AFElement.LoadElements(elements); else AFElement.LoadAttributes(elements, new[] { attributeTemplate }); List<AFAttribute> afAttributesList = elements.Select(m => m.Attributes[attributeTemplate.Name]).ToList(); AFAttributeList attributeList = new AFAttributeList(afAttributesList); var results = attributeList.Data.EndOfStream(); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; const int pageSize = 1000; int startIndex = 0; int totalCount; do { // Find a collection of elements instantiated from the Boiler tempplate. // Only the Elements' header information (Name, Description, Template, Type, etc.) // are loaded from the AF Server by this call. AFNamedCollection<AFElement> elements = AFElement.FindElements( database: afDatabase, searchRoot: null, query: "Boiler", field: AFSearchField.Template, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); if (elements == null) break; // This call goes to the AF Server to fully load the found elements in one call, // so further AF Server calls can be avoided. AFElement.LoadElements(elements); // Now we can use the elements without having to make any additional server calls. // In the example below, accessing the Attributes collection would have // caused an additional call per element if we had not called LoadElements previously. Console.WriteLine("Found {0} Elements.", elements.Count); foreach (AFElement item in elements) { Console.WriteLine(" Element {0} has {1} Attributes", item.Name, item.Attributes.Count); } startIndex += pageSize; } while (startIndex < totalCount); }
/// <summary> /// Example that shows how to connect to PI System /// in your application, you should keep a reference to piSystems so its not garbage collected. /// The class <see cref="AfConnectionHelper"/> illustrates this. (ctrl+click to navigate to the class.) /// </summary> /// <param name="server"></param> /// <returns></returns> public PISystem Connect(string server) { string serverName = server; PISystems piSystems = new PISystems(); // in case you would like to force the auto-creation of the PI System in KST if it does not exist, uncomment the following line // see: https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/T_OSIsoft_AF_PISystems_AFDirectoryOptions.htm // PISystems.DirectoryOptions = PISystems.AFDirectoryOptions.AutoAdd; PISystem piSystem = piSystems[serverName]; // true, null option will force a password dialog to appear. // you should not use this option for a service or an executable that runs outside a windows session. // instead use the empty constructor and make sure that the user that runs the application have an account that allows it to connect. piSystem.Connect(true, null); return piSystem; }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; AFCategory elementCategory = afDatabase.ElementCategories["Equipment Assets"]; AFCategory attributeCategory = afDatabase.AttributeCategories["Real-Time Data"]; AFElementTemplate elementTemplate = afDatabase.ElementTemplates["Boiler"]; const int pageSize = 1000; int startIndex = 0; int totalCount; do { // Find all "Water Flow" attributes in the NuGreen database. AFAttributeList attrList = AFAttribute.FindElementAttributes( database: afDatabase, searchRoot: null, nameFilter: "*", elemCategory: elementCategory, elemTemplate: elementTemplate, elemType: AFElementType.Any, attrNameFilter: "*", attrCategory: attributeCategory, attrType: TypeCode.Double, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); foreach (AFAttribute attr in attrList) { Console.WriteLine("Parent element name: {0}", attr.Element); } startIndex += pageSize; } while (startIndex < totalCount); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; AFElement nuGreen = afDatabase.Elements["NuGreen"]; AFElement houston = nuGreen.Elements["Houston"]; AFElement crackingProcess = houston.Elements["Cracking Process"]; AFElement equipment = crackingProcess.Elements["Equipment"]; AFElement b210 = equipment.Elements["B-210"]; AFAttribute processFeedRate = b210.Attributes["Process Feedrate"]; AFValue val = processFeedRate.GetValue(); Console.WriteLine("Timestamp: {0}, Value: {1}", val.Timestamp, val.Value.ToString()); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; const int pageSize = 1000; int startIndex = 0; int totalCount; do { // Find a collection of elements instantiated from the Boiler tempplate. // Only the Elements' header information (Name, Description, Template, Type, etc.) // are loaded from the AF Server by this call. AFNamedCollection<AFElement> elements = AFElement.FindElements( database: afDatabase, searchRoot: null, query: "Boiler", field: AFSearchField.Template, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); if (elements == null) break; // Because we are just retrieving the element's name, no additional calls // to the AF Server are made. Console.WriteLine("Found {0} Elements.", elements.Count); foreach (AFElement item in elements) { Console.WriteLine(" Element name is {0}.", item.Name); } startIndex += pageSize; } while (startIndex < totalCount); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["Basic-AFSDK-Sample"]; const int pageSize = 1000; int startIndex = 0; int returnLimit = 100000; do { AFElementTemplate efTemplate = afDatabase.ElementTemplates["BasicEventFrameTemplate"]; // Get event frames that started the past two days. AFNamedCollectionList<AFEventFrame> eventFrames = AFEventFrame.FindEventFrames( database: afDatabase, searchRoot: null, startTime: "t-2d", startIndex: startIndex, maxCount: pageSize, searchMode: AFEventFrameSearchMode.ForwardFromStartTime, nameFilter: "*", referencedElementNameFilter: "BoilerA", elemCategory: null, elemTemplate: efTemplate, searchFullHierarchy: true); foreach (AFEventFrame ef in eventFrames) { //Note: We should make a bulk call on the attribute values via AFAttributeList if we had many event frames. Console.WriteLine("Name: {0}, Start: {1}, End: {2}, Max temp: {3}", ef.Name, ef.StartTime, ef.EndTime, ef.Attributes["Maximum temperature"].GetValue()); } startIndex += pageSize; } while (startIndex < returnLimit); }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["Basic-AFSDK-Sample"]; AFElement boilerA = afDatabase.Elements["Region_0"].Elements["BoilerA"]; AFElementTemplate elementTemplate = afDatabase.ElementTemplates["BasicBoilerTemplate"]; AFAttributeTemplate temperatureAttrTemplate = elementTemplate.AttributeTemplates["Temperature"]; AFAttributeTemplate modeAttrTemplate = elementTemplate.AttributeTemplates["Mode"]; AFElement.LoadAttributes(new[] { boilerA }, new[] { temperatureAttrTemplate, modeAttrTemplate }); AFEnumerationSet digSet = afDatabase.EnumerationSets["Modes"]; IList<AFValue> valuesToWrite = new List<AFValue>(); for (int i = 0; i < 10; i++) { AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local)); AFValue afValueFloat = new AFValue(i, time); // Associate the AFValue to an attribute so we know where to write to. afValueFloat.Attribute = boilerA.Attributes["Temperature"]; AFEnumerationValue digSetValue = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"]; AFValue afValueDigital = new AFValue(digSetValue, time); afValueDigital.Attribute = boilerA.Attributes["Mode"]; valuesToWrite.Add(afValueFloat); valuesToWrite.Add(afValueDigital); } // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible. // Otherwise, make a single call to the PI Data Archive. // We use no compression just so we can check all the values are written. // AFListData is the class that provides the bulk write method. AFListData.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible); }
static void Main(string[] args) { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems.DefaultPISystem; AFDatabase database = piSystem.Databases["Samples"]; Console.WriteLine("Show All Elements."); ElementManager elementManager = new ElementManager(database); Console.WriteLine("Root"); elementManager.ShowElements(database.Elements); Console.WriteLine("Show All UOMs."); UOMManager uomManager = new UOMManager(piSystem); uomManager.ShowAll(); Console.WriteLine("Show All Tables."); TableManager tableManager = new TableManager(database); tableManager.ShowAll(); Console.WriteLine("Show All Enumeration Set."); EnumSetManager enumSetManager = new EnumSetManager(database); enumSetManager.ShowAll(); }
public override void Run() { try { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems[Server]; piSystem.Connect(true, null); Logger.InfoFormat("Connected to AF Server {0}", Server); Logger.InfoFormat("Creating the new database {0} ...", Database); if(piSystem.Databases.Contains(Database)) throw new Exception("The database already exists. Cannot create the new database."); piSystem.Databases.Add(Database); Logger.InfoFormat("Database creation completed"); } catch (Exception ex) { Logger.Error(ex); } }
// Define other instance members here public AFAssetSearcher(string server, string database) { PISystem piSystem = new PISystems()[server]; if (piSystem != null) _database = piSystem.Databases[database]; }
public WAFElement() { PISystems syss = new PISystems(); m_piSys = syss.DefaultPISystem; m_afDb = m_piSys.Databases.DefaultDatabase; }
public void RunCalculations(IEnumerable<string> elementNames, DateTime startTime, DateTime endTime, TimeStampsGenerator.TimeStampsInterval interval, string afServerName, string afDatabaseName , int afThreadCount, int analysesThreadCount, int dataWriterDelay, string outputFile, bool enableWrite) { var statistics = new Statistics(); var dateWriter = new DataWriter(); var times = TimeStampsGenerator.Get(interval, startTime, endTime); var aftimes = times.Select(t => new AFTime(t)).ToList(); ConcurrentQueue<List<AFValue>> dataWritingQueue = null; #region AFConnection // connects to the the PI system _logger.InfoFormat("Connecting to AF server:{0} and database: {1}...", afServerName, afDatabaseName); var afServers = new PISystems(); var afServer = afServers[afServerName]; AFDatabase database; if (!afServer.ConnectionInfo.IsConnected) { afServer.Connect(); _logger.Info("AF server connected"); } database = afServer.Databases[afDatabaseName]; #endregion AFConnection statistics.Run(); if (enableWrite) { dateWriter.Run(dataWriterDelay, outputFile); } var elements = new List<AFElement>(); _logger.Info("Loading elements"); foreach (var elementName in elementNames) { var element = database.Elements[elementName]; if (element != null) elements.Add(element); else _logger.WarnFormat("Passed element name \"{0}\" did not return an Element object. AF Database {1}", elementName, database.Name); } AFElement.LoadElements(elements); _logger.InfoFormat("{0} Elements Loaded...", elements.Count); _logger.InfoFormat("Starting calculation from {0} to {1}. Means {2} evaluations per analysis to execute.", startTime, endTime, aftimes.Count); _logger.InfoFormat("Configuration:{0} threads for elements and {1} threads for Analyses", afThreadCount, analysesThreadCount); // for each element we carry out the calculations if (enableWrite) { dataWritingQueue = DataWriter.DataQueue;} Parallel.ForEach(elements, new ParallelOptions() { MaxDegreeOfParallelism = afThreadCount }, (element) => RunAnalysesParallel(element, aftimes, analysesThreadCount, dataWritingQueue)); }
/// <summary> /// Create the AF Database, Element Templates, and Attribute Templates. /// </summary> private void CreateAFTemplates() { // Check if PI System exists. PISystem targetPISystem = new PISystems()[_conf.AFServerName]; if (targetPISystem == null) { Console.WriteLine("AF server does not exist"); Environment.Exit(0); } // Check if AF Database exists. If so, delete it and recreate it to start anew. _afContext = new AFContext(); _afContext.Database = targetPISystem.Databases[_conf.AFDatabaseName]; if (_afContext.Database != null) { Console.Write(string.Format(@"AF Database {0} already exists. " + @"Press Y to remove and recreate the database, " + @"N to quit the program and specify a different database name : ", _conf.AFDatabaseName)); while (true) { ConsoleKeyInfo result = Console.ReadKey(); Console.WriteLine("\n"); if ((result.KeyChar == 'Y') || (result.KeyChar == 'y')) { targetPISystem.Databases.Remove(_afContext.Database); break; } else if ((result.KeyChar == 'N') || (result.KeyChar == 'n')) { Environment.Exit(0); } Console.Write("Invalid input, try again (Y/N) : "); } } _afContext.Database = targetPISystem.Databases.Add(_conf.AFDatabaseName); // Create the Enumeration Set. AFEnumerationSet modes = _afContext.Database.EnumerationSets.Add("Modes"); modes.Add("Manual", 0); modes.Add("Auto", 1); modes.Add("Cascade", 2); modes.Add("Program", 3); modes.Add("Prog-Auto", 4); // Create element templates for SubTree and Branch elements. AFElementTemplate subTree_ElemTmp = _afContext.Database.ElementTemplates.Add(Constants.SUBTREE); AFElementTemplate branch_ElemTmp = _afContext.Database.ElementTemplates.Add(Constants.BRANCH); AFAttributeTemplate subtree_Rollup_AttrTmp = subTree_ElemTmp.AttributeTemplates.Add(Constants.ROLLUP_SUM_ATTRIBUTE); AFAttributeTemplate branch_Rollup_AttrTmp = branch_ElemTmp.AttributeTemplates.Add(Constants.ROLLUP_SUM_ATTRIBUTE); AFAttributeTemplate threshold_AttrTmp = branch_ElemTmp.AttributeTemplates.Add(Constants.THRESHOLD_ATTRIBUTE); subtree_Rollup_AttrTmp.Type = typeof(float); branch_Rollup_AttrTmp.Type = typeof(float); threshold_AttrTmp.Type = typeof(int); AFPlugIn _piPointDR = AFDataReference.GetPIPointDataReference(targetPISystem); subtree_Rollup_AttrTmp.DataReferencePlugIn = _piPointDR; branch_Rollup_AttrTmp.DataReferencePlugIn = _piPointDR; string serverPath = @"\\" + _conf.PIServerName + @"\"; subtree_Rollup_AttrTmp.ConfigString = serverPath + @"HighAsset_%Element%_Total"; branch_Rollup_AttrTmp.ConfigString = serverPath + @"HighAsset_%Element%_Total"; threshold_AttrTmp.SetValue(_conf.ThresholdValue, null); // Create element templates for Leaf elements. _afContext.BaseLeafTemplate = _afContext.Database.ElementTemplates.Add(Constants.LEAF); _afContext.SinusoidLeafTemplate = _afContext.Database.ElementTemplates.Add(Constants.LEAF_SIN); _afContext.RandomLeafTemplate = _afContext.Database.ElementTemplates.Add(Constants.LEAF_RAND); _afContext.SinusoidLeafTemplate.BaseTemplate = _afContext.BaseLeafTemplate; _afContext.RandomLeafTemplate.BaseTemplate = _afContext.BaseLeafTemplate; // Add attribute templates for base leaf Element Templates. AFAttributeTemplate subtree_AttrTmp = _afContext.BaseLeafTemplate.AttributeTemplates.Add(Constants.SUBTREE); AFAttributeTemplate branch_AttrTmp = _afContext.BaseLeafTemplate.AttributeTemplates.Add(Constants.BRANCH); AFAttributeTemplate ID_AttrTmp = _afContext.BaseLeafTemplate.AttributeTemplates.Add(Constants.LEAF_ID); AFAttributeTemplate value_AttrTmp = _afContext.BaseLeafTemplate.AttributeTemplates.Add("Value"); AFAttributeTemplate mode_AttrTmp = _afContext.BaseLeafTemplate.AttributeTemplates.Add("Mode"); subtree_AttrTmp.Type = typeof(string); branch_AttrTmp.Type = typeof(string); ID_AttrTmp.Type = typeof(string); value_AttrTmp.Type = typeof(float); value_AttrTmp.DataReferencePlugIn = _piPointDR; mode_AttrTmp.DataReferencePlugIn = _piPointDR; mode_AttrTmp.TypeQualifier = modes; mode_AttrTmp.SetValue(modes["Manual"], null); mode_AttrTmp.ConfigString = serverPath + @"HighAsset_%Element%_Mode; ptclassname=classic; pointtype=digital; digitalset=modes; pointsource=R; location1=0; location4=3; location5=1"; // Add attribute templates for sinusoid leaf Element Templates. AFAttributeTemplate value_sinusoid_AttrTmp = _afContext.SinusoidLeafTemplate.AttributeTemplates.Add("Value"); value_sinusoid_AttrTmp.Type = typeof(double); value_sinusoid_AttrTmp.DataReferencePlugIn = _piPointDR; value_sinusoid_AttrTmp.ConfigString = serverPath + @"HighAsset_%Element%_Sinusoid; ptclassname=classic; pointtype=float32; pointsource=R; location1=0; location4=3; location5=0"; // Add attribute templates for random leaf Element Templates. AFAttributeTemplate value_random_AttrTmp = _afContext.RandomLeafTemplate.AttributeTemplates.Add("Value"); value_random_AttrTmp.Type = typeof(double); value_random_AttrTmp.DataReferencePlugIn = _piPointDR; value_random_AttrTmp.ConfigString = serverPath + @"HighAsset_%Element%_Random; ptclassname=classic; pointtype=float32; pointsource=R; location1=0; location4=3; location5=1"; // Create container element under which all leaf elements will be stored. _afContext.Database.Elements.Add("LeafElements"); // Do a bulk checkin of all changes made so far. _afContext.Database.CheckIn(AFCheckedOutMode.ObjectsCheckedOutThisThread); }
public static AFDatabase GetDatabase(string server, string database) { PISystem piSystem = new PISystems()[server]; if (piSystem != null) return piSystem.Databases[database]; else return piSystem.Databases.DefaultDatabase; }
public AFEventFrameCreator(string server, string database) { PISystem piSystem = new PISystems()[server]; if (piSystem != null) _database = piSystem.Databases[database]; }