Writing an Ice Application with C-Sharp
This page shows how to create an Ice application with C#.
On this page:
Create Projects for your Client and Server Applications
We create two projects, one for the Server application and one for the Client application. These are regular Console projects with very little Ice-specific additions.
Open Visual Studio and create a new Console Application
Create the client project using "File > Add > New Project..."
Add the zeroc.icebuilder.msbuild
and zeroc.ice.net
NuGet package to the projects with the NuGet Package Manager, found in "Tools > NuGet Package Manager > Manage NuGet Packages for Solution...".
Open a new Command Prompt a run the following command to create the server and client projects:
dotnet new console -o Server
This generates a new .NET Core console application project in the Server
directory.
Then add references to the zeroc.icebuilder.msbuild
and zeroc.ice.net
NuGet packages to this project:
dotnet add Server package zeroc.icebuilder.msbuild dotnet add Server package zeroc.ice.net
Finally, repeat these steps for the client project:
dotnet new console -o Client dotnet add Client package zeroc.icebuilder.msbuild dotnet add Client package zeroc.ice.net
Compile your Slice File
The next step is to add the Slice file (Printer.ice
) created earlier to each project, and then compile this Slice file.
Open the "Project > Add Existing Item" dialog and add Printer.ice
to your Project:
If the Ice Builder for Visual Studio is installed, it immediately generates the file generated\Printer.cs
from Printer.ice
unless you disabled automatic building in the Ice Builder.
If you have automatic building disabled, select Build
to build your project. The build generates generated\Printer.cs
from Printer.ice
(using Ice Builder) and then compiles both generated\Printer.cs
and the default no-op Program.cs
.
Ice Builder invokes the Slice to C# compiler (slice2cs
) to compile Slice files into C# files.
Add a Slice item that includes Printer.ice
to your two projects. The code below shows the client project:
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> </PropertyGroup> <ItemGroup> <SliceCompile Include="../Printer.ice" /> <PackageReference Include="zeroc.ice.net" Version="3.7.8" /> <PackageReference Include="zeroc.icebuilder.msbuild" Version="5.0.9" /> </ItemGroup> </Project>
When building the project, the SliceCompile
task (imported automatically from the zeroc.icebuilder.msbuild
NuGet package) compiles Printer.ice
into generated/Printer.cs
using the Slice to C# compiler, slice2cs.
Use the following command to build the projects:
dotnet build Server dotnet build Client
Write and Compile your Server
To implement our Printer
interface, we must create a servant class. By convention, a servant class uses the name of its interface with an I
-suffix, so our servant class is called PrinterI
and we will place it into the default C# source file Program.cs:
using System; namespace Server { public class PrinterI : Demo.PrinterDisp_ { public override void printString(string s, Ice.Current current) { Console.WriteLine(s); } } class Program { static void Main(string[] args) { } } }
The PrinterI
class inherits from a base class called PrinterDisp_
, which is generated by the slice2cs
compiler. The base class is abstract and contains a printString
method that accepts a string for the printer to print and a parameter of type Ice.Current
. (For now we will ignore the Ice.Current
parameter.) Our implementation of the printString
method simply writes its argument to the terminal.
The remainder of the server code follows in Program.cs
and is shown in full here:
using System; namespace Server { public class PrinterI : Demo.PrinterDisp_ { public override void printString(string s, Ice.Current current) { Console.WriteLine(s); } } public class Program { public static int Main(string[] args) { try { using(Ice.Communicator communicator = Ice.Util.initialize(ref args)) { var adapter = communicator.createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -h localhost -p 10000"); adapter.add(new PrinterI(), Ice.Util.stringToIdentity("SimplePrinter")); adapter.activate(); communicator.waitForShutdown(); } } catch(Exception e) { Console.Error.WriteLine(e); return 1; } return 0; } } }
The body of Main
contains a try
block in which we place all the server code, followed by a catch
block. The catch block catches all exceptions that may be thrown by the code; the intent is that, if the code encounters an unexpected run-time exception anywhere, the stack is unwound all the way back to Main
, which prints the exception and then returns failure to the operating system.
The Ice.Communicator
object implements IDisposable
, which allows us to use the using
statement for the initialization of the Ice.Communicator
object. This ensures the communicator destroy
method is called when the using
block goes out of scope. Doing this is essential in order to correctly finalize the Ice run time.
The body of our try
block contains the actual server code.
The code goes through the following steps:
- We initialize the Ice run time by calling
Ice.Util.initialize
. (We passargs
to this call because the server may have command-line arguments that are of interest to the run time; for this example, the server does not require any command-line arguments.) The call toinitialize
returns anIce.Communicator
reference, which is the main object in the Ice run time. - We create an object adapter by calling
createObjectAdapterWithEndpoints
on theCommunicator
instance. The arguments we pass are"SimplePrinterAdapter"
(which is the name of the adapter) and"default -p 10000"
, which instructs the adapter to listen for incoming requests using the default transport protocol (TCP/IP) at port number 10000. - At this point, the server-side run time is initialized and we create a servant for our
Printer
interface by instantiating aPrinterI
object. - We inform the object adapter of the presence of a new servant by calling
add
on the adapter; the arguments toadd
are the servant we have just instantiated, plus an identifier. In this case, the string"SimplePrinter"
is the name of the Ice object. (If we had multiple printers, each would have a different name or, more correctly, a different object identity.) - Next, we activate the adapter by calling its
activate
method. (The adapter is initially created in a holding state; this is useful if we have many servants that share the same adapter and do not want requests to be processed until after all the servants have been instantiated.) - Finally, we call
waitForShutdown
. This call suspends the calling thread until the server implementation terminates, either by making a call to shut down the run time, or in response to a signal. (For now, we will simply interrupt the server on the command line when we no longer need it.)
We can compile the server code as follows:
Build the server project using "Build > Builder Server"
Build the server project using the dotnet build
command:
cd Server dotnet build
Write and Compile your Client
The client code, in Client/Program.cs
, looks very similar to the server.
Here it is in full:
using Demo; using System; namespace Client { public class Program { public static int Main(string[] args) { try { using(Ice.Communicator communicator = Ice.Util.initialize(ref args)) { var obj = communicator.stringToProxy("SimplePrinter:default -h localhost -p 10000"); var printer = PrinterPrxHelper.checkedCast(obj); if(printer == null) { throw new ApplicationException("Invalid proxy"); } printer.printString("Hello World!"); } } catch(Exception e) { Console.Error.WriteLine(e); return 1; } return 0; } } }
Note that the overall code layout is the same as for the server: we use the same try
and catch
blocks to deal with errors. The code in the try
block does the following:
- As for the server, we initialize the Ice run time by calling
Ice.Util.initialize
within theusing
statement - The next step is to obtain a proxy for the remote printer. We create a proxy by calling
stringToProxy
on the communicator, with the string"SimplePrinter:default -p 10000"
. Note that the string contains the object identity and the port number that were used by the server. (Obviously, hard-coding object identities and port numbers into our applications is a bad idea, but it will do for now; we will see more architecturally sound ways of doing this when we discuss IceGrid. - The proxy returned by
stringToProxy
is of typeIce.ObjectPrx
, which is at the root of the inheritance tree for interfaces and classes. But to actually talk to our printer, we need a proxy for aPrinter
interface, not anObject
interface. To do this, we need to do a down-cast by callingPrinterPrxHelper.checkedCast
. A checked cast sends a message to the server, effectively asking "is this a proxy for aPrinter
interface?" If so, the call returns a proxy of typeDemo::Printer
; otherwise, if the proxy denotes an interface of some other type, the call returns null. - We test that the down-cast succeeded and, if not, throw an error message that terminates the client.
- We now have a live proxy in our address space and can call the
printString
method, passing it the time-honored"Hello World!"
string. The server prints that string on its terminal.
The client's project is just like the server's project shown earlier.
Build the client project using "Build > Builder Client"
Build the client project using dotnet build
command:
cd Client dotnet build
Run your Client and Server
To run client and server, we first start the server in a separate window:
server
cd Server dotnet run
At this point, we won't see anything because the server simply waits for a client to connect to it. We run the client in a different window:
client
cd Client dotnet run
The client runs and exits without producing any output; however, in the server window, we see the "Hello World!"
that is produced by the printer. To get rid of the server, we just interrupt it on the command line for now.
If anything goes wrong, the client will print an error message. For example, if we run the client without having first started the server, we get something like the following:
Ice.ConnectionRefusedException error = 0