Maintenant que nous avons définit les différentes opérations possibles pour notre serveur, il nous faut le développer. Nous allons donc écrire le code du service WCF qui sera hébergé par le serveur. Ce service WCF implémente l'interface affichée plus haut, nous devons donc créer une classe qui implémente cette interface :
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
public class ServiceImplementation : IServerContract
{
#region Member Fields
private System.IO.FileSystemWatcher fsw = null;
private OperationContext context = null;
private IClientContract client = null;
#endregion
#region IServerContract Members
/// <summary>
/// Start the FileSystemWatcher on the server.
/// </summary>
/// <param name="path">The path to the directory to watch.</param>
public void StartWatcher(string path)
{
try
{
context = OperationContext.Current;
client = context.GetCallbackChannel<IClientContract>();
fsw = new System.IO.FileSystemWatcher();
fsw.Path = path;
fsw.IncludeSubdirectories = true;
fsw.Filter = "*.*";
fsw.Created += new System.IO.FileSystemEventHandler(GetUpdateFileFromFSW);
fsw.Deleted += new System.IO.FileSystemEventHandler(GetUpdateFileFromFSW);
fsw.EnableRaisingEvents = true;
}
catch (Exception ex)
{
throw new FaultException<ServerException>(new ServerException(
string.Format("An error occured !{0}{1}", Environment.NewLine, ex.Message)));
}
}
/// <summary>
/// Retrieve the images which are in the specified folder during the startup.
/// </summary>
/// <param name="path">The folder to get the images.</param>
public void GetImagesFromPathAtFirstLoad(string path)
{
var imgList = new List<CustomImage>();
CustomImage image = null;
foreach (var file in Directory.GetFiles(path))
{
try
{
if (Path.GetExtension(file).ToLower() == ".png" || Path.GetExtension(file).ToLower() == ".jpg" ||
Path.GetExtension(file).ToLower() == ".jpeg" || Path.GetExtension(file).ToLower() == ".bmp" ||
Path.GetExtension(file).ToLower() == ".gif")
{
using (var stream = File.OpenRead(file))
{
if (stream.Length > 0)
{
image = new CustomImage();
image.Name = Path.GetFileName(file);
image.FullPath = Path.GetFullPath(file);
image.Modification = CustomImage.ChangeType.Add;
}
}
byte[] array = GetByteFromImage(file);
image.Img = array;
imgList.Add(image);
}
}
catch (Exception ex)
{
throw new FaultException<ServerException>(new ServerException(
string.Format("An error occured !{0}{1}", Environment.NewLine, ex.Message)));
}
}
if (client != null)
{
client.GetImagesFromServer(imgList);
}
}
#endregion
/// <summary>
/// Convert a file on a byte array.
/// </summary>
/// <param name="file">The file to convert.</param>
/// <returns>An array of byte corresponding to the file.</returns>
private static byte[] GetByteFromImage(string file)
{
byte[] array;
try
{
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
BinaryReader reader = new BinaryReader(fs);
array = reader.ReadBytes((int)fs.Length);
reader.Close();
}
}
catch (Exception ex)
{
throw new FaultException<ServerException>(new ServerException(
string.Format("An error occured !{0}{1}", Environment.NewLine, ex.Message)));
}
return array;
}
/// <summary>
/// Method called when the FileSystemWatcher detects that a file has been added/deleted.
/// </summary>
private void GetUpdateFileFromFSW(object sender, System.IO.FileSystemEventArgs e)
{
CustomImage image = null;
if (e.ChangeType == System.IO.WatcherChangeTypes.Created)
{
if (File.Exists(e.FullPath) && (Path.GetExtension(e.FullPath).ToLower() == ".png" ||
Path.GetExtension(e.FullPath).ToLower() == ".jpg"
|| Path.GetExtension(e.FullPath).ToLower() == ".jpeg"
|| Path.GetExtension(e.FullPath).ToLower() == ".bmp"
|| Path.GetExtension(e.FullPath).ToLower() == ".gif"))
{
try
{
using (var stream = File.OpenRead(e.FullPath))
{
if (stream.Length > 0)
{
image = new CustomImage();
image.Name = e.Name;
image.FullPath = e.FullPath;
image.Modification = CustomImage.ChangeType.Add;
}
}
byte[] array = GetByteFromImage(e.FullPath);
image.Img = array;
}
catch (Exception ex)
{
throw new FaultException<ServerException>(new ServerException(
string.Format("An error occured !{0}{1}", Environment.NewLine, ex.Message)));
}
}
}
else if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted)
{
image = new CustomImage();
image.Name = e.Name;
image.FullPath = e.FullPath;
image.Modification = CustomImage.ChangeType.Delete;
}
if (image != null)
{
SendUpdateToClient(image);
}
}
/// <summary>
/// Inforl the client that an update is available.
/// </summary>
/// <param name="image">The image that have been added/deleted.</param>
private void SendUpdateToClient(CustomImage image)
{
if (client != null)
{
client.GetUpdateFromFileShare(image);
}
}
}
Il y a plusieurs choses à observer sur cette classe. Tout d'abord, la méthode
qui va scanner le répertoire contenant les images et nous informer des mises à jour disponibles. La méthode
, quand à elle, est utilisée pour récupérer les images lors du premier lancement de l'application cliente. Cette méthode, ainsi que la méthode utilisée par le
, font toutes les deux appels aux méthodes proposées par l'interface « cliente ».
. Cela est obligatoire car l'application cliente, celle qui va consommer le service WCF, est une application WPF (cela aurait été la même chose dans le cas d'une simple application WindowsForms). En ce qui concerne le reste de la classe, vous pouvez constater qu'il est tout ce qu'il y a de plus simple et ne nécessite pas d'être commenté.