I'm developing a simple Silverlight app. The application will display the information found in the tags of an OPC server, running in the same machine of the web server.
I implemented a domain service class with a method that let the client ask for the value of a tag. The problem is that every time I call the method from the client side it instantiate a new OPC Client, connect to the server, read the value and then disconnect. This can be a problem with a large number of calls.
How can I use a single OPC Client object on the server side?
Here's the code of the domain service class.
namespace BFLabClientSL.Web.Servizi
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using OpcClientX;
using System.Configuration;
// TODO: creare metodi contenenti la logica dell'applicazione.
[EnableClientAccess()]
public class DSCAccessoDati : DomainService
{
protected OPCItem itemOPC = null;
/// <summary>
/// Permette l'acceso al valore di un dato
/// </summary>
/// <param name="itemCode">Chiave del dato</param>
/// <returns>Valore del dato</returns>
public string GetDato(string itemCode)
{
string result = "";
OPCServer clientOPC = new OPCServer();
clientOPC.Connect(Properties.Settings.Default.OPCServer_ProgID);
OPCGroup gruppoOPC = clientOPC.OPCGroups.Add("Gruppo1");
OPCItem itemOPC = gruppoOPC.OPCItems.AddItem(itemCode, 0);
try
{
object value = null;
object quality = null;
object timestamp = null;
itemOPC.Read(1, out value, out quality, out timestamp);
result = (string)value;
}
catch (Exception e)
{
throw new Exception("Errore durante Caricamento dato da OPCServer", e);
}
finally
{
try
{
clientOPC.Disconnect();
}
catch { }
clientOPC = null;
}
return result;
}
}
}