Programmatically Import - Export AF Database

Blog Post created by jhim on Jun 6, 2019

Performing a backup of the backend PIFD database of an AF Server is critical in case everything gets crazy. Backup is a key factor when it comes to dragging everything back to its original state from a sunken ship - and make the AF Server and the Clients happy again.


Server Client Hand Shake


The problem is, sometimes this option may not be available for some cases and customers are forced to look for an alternative - XML export / import.

Note that XML export is not a substitution of PIFD backup and may result in to loss of some data.


Also, there are some use cases where customers want to import & export XML files programmatically. Although this can be done by running the AFExport.exe / AFImport.exe utility in the AF folder, this post is to introduce how to programmatically embed that functionality within the code. (Example code is written in C#)


  1. Exporting
    Let's first look at the PI System Explorer GUI dialog when Exporting XML files.

    Each of the Export Options are defined in PIExportMode enum (more info) and can be added (piped) in ExportXML method. Here's a quick example :
    public static void ExportXML_ToFile(AFDatabase myDB, string filepath)
    myDB.PISystem.ExportXml(myDB, PIExportMode.AllReferences | PIExportMode.Security,
    filepath, null, null, null);

    The example code above uses the second overloaded method of ExportXML. You can define the Start Time and End Time if you wish to export Event Frames, Transfers and Cases.

  2. Importing

    Similar to Exporting, Import Options also are defined on an Enum - PIImportMode. (more info)
    Importing an XML requires more attention than Exporting, especially if it's on a different AF Server. It is very common to see error messages similar to the following screenshot when importing XML to a brand new database.

    This is where the EventHandler comes in handy. As well as PISystem.ExportXML, PISystem.ImportXML has an option to specify an EventHandler in case this kind of event occurs. In fact, that very "Continue" dialog on the screenshot in PI System Explorer also utilizes the EventHandler (where it halts and waits for user input).

    Here's a very simple example code which includes the EventHandler :
    public static void ImportXML_FromFile(AFDatabase myDB, string filepath)
    using (XmlTextReader myXML = new XmlTextReader(filepath))
    myDB.PISystem.ImportXml(myDB, PIImportMode.AutoCheckIn | PIImportMode.AllowCreate,
    myXML, (o, e) => { Console.WriteLine(e.ToString()); e.Cancel = false; });

    The code above is written to continue the import event though there's an error event occurred.
    It uses the following overload method.


I hope this helps all you folks out there trying to write automatic import / export applications.