Skip to content

Connecting to InterSystems IRIS from C#


A step-by-step guide for C# developers looking to connect to and interact with InterSystems IRIS

Connecting to InterSystems IRIS Hierarchical Model from C# (using ADO.NET)

Below is a step-by-step guide for C# developers looking to connect to and interact with InterSystems IRIS Hierarchical model using the ADO.NET provider.

Step 1. Prerequisites

Before writing any code, ensure that all necessary components are installed.

Component
Status
Check
InterSystems IRIS
Running
Ensure the InterSystems IRIS instance is started and accessible
ADO.NET assembly
Available
You need to have the correct version of the InterSystems IRIS ADO.NET assembly available
C# project
Ready
Your project should be set up in Visual Studio or your preferred IDE

If InterSystems IRIS is installed on the same machine - the file is already present in \dev\dotnet\bin.

If InterSystems IRIS is installed on a remote server - you must download and install the standalone development package for your operating system and bitness (32-bit or 64-bit) from WRC website if you're a client or by installing development components and copying files from \dev\dotnet\bin manually.

setuptypeinstallation.png

Step 2. Forming Connection String

The connection string requires three critical pieces of information: the Server location (Host and Port), the target Namespace, and Credentials (UID and PWD):

// Connection String Breakdown
string connectionString =
    "Host=127.0.0.1;" + // Hostname or IP of the IRIS server
    "Port=1972;" +      // SuperServer TCP Port
    "Namespace=USER;" + // Target IRIS Namespace
    "Password=SYS;" +   // Password (Case-Sensitive, if default)
    "User=_System;";    // Username (Case-Insensitive)

Step 3. Adding Assembly to Your Project

Right-click Dependencies in your project in Solution Explorer → Add Project Reference…

addprojectreference.png

In the Reference Manager window: Click Browse… on the bottom right. Locate InterSystems.Data.IRISClient.dll file. Click Add and OK.

InterSystems.Data.IRISClient.dll.png

Step 4. Writing C# Code to Write a Global to InterSystems IRIS via ADO.NET

In the dedicated class add links to the assemblies:

using InterSystems.Data.IRISClient;
using InterSystems.Data.IRISClient.ADO;

Create and open the connection to the database using the connectionString from Step 2:

// Use the 'using' block to ensure the connection is properly closed, 
// even if errors occur.
using (IRISConnection conn = new IRISConnection(connectionString))
{
    conn.Open();
}

Create an InterSystems IRIS object that will allow to work with globals:

IRIS iris = IRIS.CreateIRIS(conn);

Create a global ^Person with two nodes "Doe,John" and "Smith,Jane" and set their dates of birth as values:

iris.Set(DateTime.Now, "Person", "Doe,John");
iris.Set(DateTime.Now, "Person", "Smith,Jane");

To update a value of any node, use the same method.

Close and release resources:

iris.Close();
conn.Close();

Step 5. Writing C# Code to Read All Nodes of the Global from InterSystems IRIS DB

Create an iterator that will allow to get access to all nodes on the first level of the global ^Person:

IRISIterator iterPeople = iris.GetIRISIterator("Person");

Iterate over the resultset and print subscript and value:

foreach (byte[] age in iterPeople)
{
    Byte[] name = (Byte[])iterPeople.CurrentSubscript;
    Console.WriteLine("\n"+ Encoding.UTF8.GetString(name) + " was born " + Encoding.UTF8.GetString(age));
}

Step 6. Writing C# Code to Read Exact Node from InterSystems IRIS DB

Get the value of the node:

DateTime dob = (DateTime)iris.GetDateTime("Person", "Doe,John");
Console.WriteLine("Person(\"Doe,John\")=" + dob.ToString("yyyy-MM-dd"));

Step 7. Writing C# Code to Delete a Node(s) from the DB

Delete the node:

iris.kill("Person", "Doe,John");
iris.Kill("Person");

Resulting Class

Here's the whole class including exception handling:

using InterSystems.Data.IRISClient;
using InterSystems.Data.IRISClient.ADO;
using System.Text;

namespace NativeSpace
{
    class NativeDemo
    {
        static void Main(string[] args)
        {
            try
            {
                //Open a connection to the server and create an IRIS object
                IRISConnection conn = new IRISConnection();
                conn.ConnectionString = "Host=127.0.0.1;Port=1972;Namespace=USER;" +
                                        "Password=SYS;User=_System;";
                conn.Open();
                IRIS iris = IRIS.CreateIRIS(conn);

                //Create a global array in the USER namespace on the server
                iris.Set(DateTime.Now, "Person", "Doe,John");
                iris.Set(DateTime.Now, "Person", "Smith,Jane");

                
                // Iterate over all nodes on the first level and print subscripts and node values
                Console.WriteLine("\nPeople in the DB: ");
                IRISIterator iterPeople = iris.GetIRISIterator("Person");
                foreach (byte[] age in iterPeople)
                {
                    Byte[] name = (Byte[])iterPeople.CurrentSubscript;
                    Console.WriteLine("\n"+ Encoding.UTF8.GetString(name) + " was born " + Encoding.UTF8.GetString(age));
                }

                // Read the values from the database and print them
                DateTime dob = (DateTime)iris.GetDateTime("Person", "Doe,John");
                Console.WriteLine("Person(\"Doe,John\")=" + dob.ToString("yyyy-MM-dd"));

                //Delete the global array and terminate
                iris.Kill("Person"); // delete global array root
                iris.Close();
                conn.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    } 
}

Connecting to InterSystems IRIS Object Model from C# (using XEP API)

Below is a step-by-step guide for Java developers looking to connect to and interact with Object Model of InterSystems IRIS using the InterSystems XEP API.

Step 1. Prerequisites

XEP is a lightweight .NET API that projects .NET object data as persistent events. A persistent event is an instance of an InterSystems IRIS class (normally a subclass of %Persistent) containing a copy of the data fields in a .NET object. Like any such instance, it can be retrieved by object access, SQL query, or direct global access.

Before writing any code, ensure that all necessary components are installed.

Component
Status
Check
InterSystems IRIS
Running
Ensure the InterSystems IRIS instance is started and accessible
XEP assembly
Available
You need to have the correct version of the InterSystems IRIS XEP assembly (InterSystems.Data.XEP.dll) available
C# project
Ready
Your project should be set up in Visual Studio or your preferred IDE

You can download the XEP assembly from Driver packages page.

If InterSystems IRIS is installed on your local machine or another you have access to, you can find the file in install-dir\dev\dotnet\bin\v4.6.2 or similar, where install-dir is the installation directory for the instance.

Step 2. Creating Proxy Class

To be able to work with persistent events, you need to create a class on the client side to generate objects for storage. To do this, create a new class with the following contents:

using System;

namespace xep.sample
{
    public class Person
    {
        public string name;
        public DateTime DOB;

        public Person() { }

        //constructor for a Person
        internal Person(string str, DateTime date)
        {
            name = str;
            DOB = date;
        }

        //method to generate test data
        public static Person[] generateSampleData(int objectCount)
        {
            Person[] data = new Person[objectCount];
            for (int i = 0; i < objectCount; i++)
            {
                data[i] = new Person("Doe,John", DateTime.Now);
            }
            return data;
        }
    }
}

Step 3. Adding Assemblies to Your Project

Right-click Dependencies in your project in Solution Explorer → Add Project Reference…

setuptypeinstallation.png

In the Reference Manager window: Click Browse… on the bottom right. Locate InterSystems.Data.XEP.dll file. Click Add and OK.

InterSystems.Data.XEP.dll.png

Do the same for InterSystems.Data.IRISClient.dll file.

Step 4. Writing C# Code to Store Data in the Database

In the dedicated class add links to the assemblies:

using InterSystems.XEP;
using xep.sample;

Create objects you wish to store in the database

// Generate 12 SingleStringSample objects for use as test data
Person[] sampleArray = Person.generateSampleData(12);

Create an EventPersister and connect to the database

EventPersister xepPersister = PersisterFactory.CreatePersister();

String host = "127.0.0.1"; // InterSystems IRIS host
int port = 1972; // InterSystems IRIS Superserver port
String irisnamespace = "USER"; // InterSystems IRIS namespace
String username = "_system"; // Credentials for InterSystems IRIS
String password = "SYS"; //Credentials for InterSystems IRIS

xepPersister.Connect(host, port, irisnamespace, username, password);

Import schema

xepPersister.ImportSchema("xep.sample.Person");

Create an event and link it to the class

Event xepEvent = xepPersister.GetEvent("xep.sample.Person");

Save 12 created objects of class xep.sample.Person to the database

xepEvent.Store(sampleArray);

Close and release all resources

xepEvent.Close();
xepPersister.Close();

Step 5. Writing C# Code to Read Objects from the Database Using SQL Query

In the same class write a query statement

String sqlQuery = "SELECT * FROM xep_sample.Person WHERE %ID BETWEEN ? AND ?";

Create an EventQuery and execute it

EventQuery xepQuery = xepEvent.CreateQuery(sqlQuery);
xepQuery.AddParameter(3);    // assign value 3 to first SQL parameter
xepQuery.AddParameter(12);   // assign value 12 to second SQL parameter
xepQuery.Execute();            // get resultset for IDs between 3 and 12

Print the results

Person mySample = xepQuery.GetNext();
while (mySample != null)
{
    Console.WriteLine(mySample.name);
    mySample = xepQuery.GetNext();
}

Close the query

xepQuery.Close();

Step 6. Writing C# Code to Read Object from the Database

In the same class using the same event get an object by its ID

mySample = (Person)xepEvent.GetObject(1);
Console.WriteLine($"Name: {mySample.name}, Date of Birth: {mySample.DOB.ToString("yyyy-MM-dd")}");

Step 7. Writing C# Code to Change Object in the Database

In the same file using the same event either create a new object and substitute the existing object or take the already read object from step 6 and change its properties and then update the object in the database

Person newP = new Person("Smith,Jane", DateTime.Now);
xepEvent.UpdateObject(1, newP);

Step 8. Writing C# Code to Delete an Object from the Database

In the same file using the same event use the known ID of an object to delete it from the database

xepEvent.DeleteObject(1);

Resulting Class

Here's the whole class:

using InterSystems.XEP;
using xep.sample;

namespace XepSimpleNamespace
{
    public class XepSimple
    {
        public static void Main(string[] args)
        {
            // Generate 12 SingleStringSample objects for use as test data
            Person[] sampleArray = Person.generateSampleData(12);

            // EventPersister
            EventPersister xepPersister = PersisterFactory.CreatePersister();

            String host = "127.0.0.1"; // InterSystems IRIS host
            int port = 1972; // InterSystems IRIS Superserver port
            String irisnamespace = "USER"; // InterSystems IRIS namespace
            String username = "_system"; // Credentials for InterSystems IRIS
            String password = "SYS"; //Credentials for InterSystems IRIS

            xepPersister.Connect(host, port, irisnamespace, username, password); // connect to localhost
            xepPersister.DeleteExtent("xep.sample.Person");   // remove old test data
            xepPersister.ImportSchema("xep.sample.Person");   // import flat schema

            // Event
            Event xepEvent = xepPersister.GetEvent("xep.sample.Person");
            xepEvent.Store(sampleArray);

            // EventQuery             
            String sqlQuery = "SELECT * FROM xep_sample.Person WHERE %ID BETWEEN ? AND ?";
            EventQuery<Person> xepQuery = xepEvent.CreateQuery<Person>(sqlQuery);
            xepQuery.AddParameter(3);    // assign value 3 to first SQL parameter
            xepQuery.AddParameter(12);   // assign value 12 to second SQL parameter
            xepQuery.Execute();            // get resultset for IDs between 3 and 12

            // Print each item in the resultset
            Console.WriteLine($"\nPrint query result");
            Person mySample = xepQuery.GetNext();
            while (mySample != null)
            {
                Console.WriteLine(mySample.name);
                mySample = xepQuery.GetNext();
            }

            xepQuery.Close();

            //get object with ID = 1
            Console.WriteLine($"\nPrint object data");
            mySample = (Person)xepEvent.GetObject(1);
            Console.WriteLine($"Name: {mySample.name}, Date of Birth: {mySample.DOB.ToString("yyyy-MM-dd")}");

            //change object with ID = 1
            Person newP = new Person("Smith,Jane", DateTime.Now);
            xepEvent.UpdateObject(1, newP);

            //get object with ID = 1
            Console.WriteLine($"\nPrint updatet object data");
            mySample = (Person)xepEvent.GetObject(1);
            Console.WriteLine($"Name: {mySample.name}, Date of Birth: {mySample.DOB.ToString("yyyy-MM-dd")}");
            //see that the properties have different values

            //delete an object with ID = 2
            xepEvent.DeleteObject(2);

            xepEvent.Close();
            xepPersister.Close();
        } 
    } 
}

Connecting to InterSystems IRIS Relational Model from C# (via ODBC)

Below is a step-by-step guide for C# developers looking to connect to and interact with InterSystems IRIS SQL using the industry-standard ODBC (Open Database Connectivity) bridge.

Step 1. Prerequisites

Before writing any code, ensure that all necessary components are installed.

Component
Status
Check
InterSystems IRIS
Running
Ensure the InterSystems IRIS instance is started and accessible
ODBC Driver
Installed
The InterSystems IRIS ODBC35 driver must be present on the machine running the C# application
C# project
Ready
Your project should be set up in Visual Studio or your preferred IDE

If InterSystems IRIS is installed on the same machine - the driver is already present.

If InterSystems IRIS is installed on a remote server - you must download and install the standalone ODBC client driver package for your client operating system and bitness (32-bit or 64-bit) from WRC website if you're a client or by installing Client components and copying ODBC driver manually. 

setuptypeinstallation.png

To verify the presence of ODBC driver open ODBC Data Source Administrator tool on Windows and look for the InterSystems IRIS ODBC35 driver:

ODBC Data Source Administrator.png

Step 2. Forming Connection String

The preferred way to connect to InterSystems IRIS from C# is to use DSN-less connection string as it keeps all connection details within the application code, simplifying deployment and avoiding dependence on pre-configured system settings on the client machine. The string requires four critical pieces of information: the Driver name, the Server location (Host and Port), the target Namespace, and Credentials (UID and PWD):

// Connection String Breakdown
string connectionString = 
    "DRIVER={InterSystems IRIS ODBC35};" +
    "Server=127.0.0.1;" +          // Hostname or IP of the IRIS server
    "Port=51773;" +                // SuperServer TCP Port
    "Database=USER;" +             // Target IRIS Namespace
    "UID=_System;" +               // Username (Case-Insensitive)
    "PWD=SYS;";                    // Password (Case-Sensitive, if default)

Step 3. Writing C# Code to Get Data from InterSystems IRIS via ODBC

In the dedicated class add links to the assemblies that contain necessary classes to work with ODBC:

using System;
using System.Data;
using System.Data.Odbc;

Create and open the connection to the database using the connectionString from Step 2:

// Use the 'using' block to ensure the connection is properly closed, 
// even if errors occur.
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
    connection.Open();
}

Create and execute a SQL statement using OdbcCommand class:

// Define the SQL Query
string sql = "SELECT ID, Name, DOB FROM Sample.Person WHERE ID < 5";
using (OdbcCommand command = new OdbcCommand(sql, connection))
{
    using (OdbcDataReader reader = command.ExecuteReader())
    { 
        //do something with the results
    }
}

Loop through the result

while (reader.Read())
{
    // Access data by column name or index
    string id = reader["ID"].ToString();
    string name = reader["Name"].ToString();
    string dob = reader["DOB"].ToString();                            
    Console.WriteLine($"ID: {id}, Name: {name}, DOB: {dob}");
}

Resulting Class

Here's the whole class including exception handling:

using System;
using System.Data;
using System.Data.Odbc;

public class IrisOdbcConnector
{
    public static void Main(string[] args)
    {
        // Define the DSN-less connection string
        string connectionString =
            "DRIVER={InterSystems IRIS ODBC35};" +
            "Server=127.0.0.1;Port=51773;Database=USER;" +
            "UID=_System;PWD=SYS;";

        // Define the SQL Query
        string sql = "SELECT ID, Name, DOB FROM Sample.Person WHERE ID < 5";

        // Use the 'using' block to ensure the connection is properly closed, 
        // even if errors occur.
        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            try
            {
                // Open the connection to InterSystems IRIS
                connection.Open();
                Console.WriteLine("Connection to InterSystems IRIS successful!");

                // Create the command and associate it with the connection
                using (OdbcCommand command = new OdbcCommand(sql, connection))
                {
                    // Execute the query and get a data reader
                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        // Loop through each row returned
                        while (reader.Read())
                        {
                            // Access data by column name or index
                            string id = reader["ID"].ToString();
                            string name = reader["Name"].ToString();
                            string dob = reader["DOB"].ToString();
                            
                            Console.WriteLine($"ID: {id}, Name: {name}, DOB: {dob}");
                        }
                    }
                }
            }
            catch (OdbcException ex)
            {
                // Catch specific ODBC errors (e.g., driver not found, network failure)
                Console.WriteLine($"\n--- ODBC Error ---");
                Console.WriteLine($"Failed to connect or execute query: {ex.Message}");
            }
            catch (Exception ex)
            {
                // Catch other general errors
                Console.WriteLine($"\n--- General Error ---");
                Console.WriteLine($"An unexpected error occurred: {ex.Message}");
            }
        }
    }
}

Connecting to InterSystems IRIS Relational Model from C# (using ADO.NET)

Below is a step-by-step guide for C# developers looking to connect to and interact with InterSystems IRIS SQL using the ADO.NET provider.

Step 1. Prerequisites

Before writing any code, ensure that all necessary components are installed.

Component
Status
Check
InterSystems IRIS
Running
Ensure the InterSystems IRIS instance is started and accessible
ADO.NET assembly
Available
You need to have the correct version of the InterSystems IRIS ADO.NET assembly available
C# project
Ready
Your project should be set up in Visual Studio or your preferred IDE

If InterSystems IRIS is installed on the same machine - the file is already present in \dev\dotnet\bin.

If InterSystems IRIS is installed on a remote server - you must download and install the standalone development package for your operating system and bitness (32-bit or 64-bit) from WRC website if you're a client or by installing development components and copying files from \dev\dotnet\bin manually.

setuptypeinstallation.png

Step 2. Forming Connection String

The connection string requires three critical pieces of information: the Server location (Host and Port), the target Namespace, and Credentials (UID and PWD):

// Connection String Breakdown
string connectionString =
    "Host=127.0.0.1;" + // Hostname or IP of the IRIS server
    "Port=1972;" +      // SuperServer TCP Port
    "Namespace=USER;" + // Target IRIS Namespace
    "Password=SYS;" +   // Password (Case-Sensitive, if default)
    "User=_System;";    // Username (Case-Insensitive)

Step 3. Adding Assembly to Your Project

Right-click Dependencies in your project in Solution Explorer → Add Project Reference…

addprojectreference.png

In the Reference Manager window: Click Browse… on the bottom right.

Locate  InterSystems.Data.IRISClient.dll file. Click Add and OK.

InterSystems.Data.IRISClient.dll.png

Step 4. Writing C# Code to Get Data from InterSystems IRIS via ADO.NET

In the dedicated class add links to assemblies:

using InterSystems.Data.IRISClient;
using InterSystems.Data.IRISClient.ADO;

Create and open the connection to the database using the connectionString from Step 2:

// Use the 'using' block to ensure the connection is properly closed, 
// even if errors occur.
using (IRISConnection connection = new IRISConnection(connectionString))
{
    connection.Open();
}

Create and execute a SQL statement using OdbcCommand class:

// Define the SQL Query
string sql = "SELECT ID, Name, DOB FROM Sample.Person WHERE ID < 5";
using (IRISCommand command = new IRISCommand(sql, connection))
{
    using (IRISDataReader reader = command.ExecuteReader())
    { 
        //do something with the results
    }
}

Loop through the result

while (reader.Read())
{
    // Access data by column name or index
    string id = reader["ID"].ToString();
    string name = reader["Name"].ToString();
    string dob = reader["DOB"].ToString();                            
    Console.WriteLine($"ID: {id}, Name: {name}, DOB: {dob}");
}

Resulting Class

Here's the whole class including exception handling:

using InterSystems.Data.IRISClient;
using InterSystems.Data.IRISClient.ADO;

public class IrisConnector
{
    public static void Main(string[] args)
    {
        // Define the DSN-less connection string
        string connectionString =
        "Host=127.0.0.1;Port=1972;Namespace=USER;" +
        "Password=SYS;User=_System;";

        // Define the SQL Query
        string sql = "SELECT ID, Name, DOB FROM Sample.Person WHERE ID < 5";

        // Use the 'using' block to ensure the connection is properly closed, 
        // even if errors occur.
        using (IRISConnection connection = new IRISConnection(connectionString))
        {
            try
            {
                // Open the connection to InterSystems IRIS
                connection.Open();
                Console.WriteLine("Connection to InterSystems IRIS successful!");

                // Create the command and associate it with the connection
                using (IRISCommand command = new IRISCommand(sql, connection))
                {
                    // Execute the query and get a data reader
                    using (IRISDataReader reader = command.ExecuteReader())
                    {
                        // Loop through each row returned
                        while (reader.Read())
                        {
                            // Access data by column name or index
                            string id = reader["ID"].ToString();
                            string name = reader["Name"].ToString();
                            string dob = reader["DOB"].ToString();
                            
                            Console.WriteLine($"ID: {id}, Name: {name}, DOB: {dob}");
                        }
                    }
                }
            }
            catch (IRISException ex)
            {
                // Catch specific IRIS errors (e.g., driver not found, network failure)
                Console.WriteLine($"\n--- IRIS Error ---");
                Console.WriteLine($"Failed to connect or execute query: {ex.Message}");
            }
            catch (Exception ex)
            {
                // Catch other general errors
                Console.WriteLine($"\n--- General Error ---");
                Console.WriteLine($"An unexpected error occurred: {ex.Message}");
            }
        }
    }
}