/// <summary> /// Extension method: /// Casts the <see cref="IWcfLogger"/> object to the type specified by <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to wich the object needs to be casted.</typeparam> /// <param name="obj">The object to cast.</param> /// <returns>The casted object if succeed, null otherwise.</returns> public static T Cast <T>(this IWcfLogger obj) where T : class { return(obj as T); }
/// <summary> /// Process the logged messages sending them to the server. /// </summary> private static void ProcessMessages() { HMACSHA256 hmacCalculator = null; //run indefinetly while (true) { //try to connect IWcfLogger channel = s_Factory.CreateChannel(); TimeSpan timeout = new TimeSpan(0, 1, 0); while (channel.Cast <ICommunicationObject>().State != CommunicationState.Opened) { try { channel.Cast <ICommunicationObject>().Open(timeout); //perform handshake BigInteger mod = IWcfLoggerUtility.GenerateRandomInt(); BigInteger prKey = IWcfLoggerUtility.GenerateRandomInt(); LogInReply reply = channel.LogIn(mod, IWcfLoggerUtility.GetPublicKey(2, mod, prKey), "admin"); if (reply.Status) { BigInteger sharedKey = IWcfLoggerUtility.GetSharedKey(mod, prKey, reply.PublicKey); //check the password SHA256 hasher = SHA256.Create(); byte[] tmp = hasher.ComputeHash(Encoding.UTF8.GetBytes("password").Concat(mod.ToByteArray()).ToArray()); tmp = hasher.ComputeHash(tmp.Concat(sharedKey.ToByteArray()).ToArray()); if (tmp.SequenceEqual(reply.PasswordToken.ToByteArray())) { hmacCalculator = new HMACSHA256(sharedKey.ToByteArray()); //exit the loop break; } } channel.Cast <ICommunicationObject>().Abort(); } catch { //re-create the channel and try again channel.Cast <ICommunicationObject>().Abort(); channel = s_Factory.CreateChannel(); } } //now channel is open, start sending messages while (channel.Cast <ICommunicationObject>().State == CommunicationState.Opened) { List <LogMessage> toSend = new List <LogMessage>(); //check for messages s_MsgAvaialble.WaitOne(); lock (s_Lock) { toSend = s_MsgQueue.ToList(); s_MsgQueue.Clear(); } foreach (LogMessage msg in toSend) { //get byte array associated with the message byte[] data = BitConverter.GetBytes(msg.Id) .Concat(BitConverter.GetBytes(msg.Date.ToBinary())) .Concat(Encoding.UTF8.GetBytes(msg.Caller)) .Concat(Encoding.UTF8.GetBytes(msg.Message)) .ToArray(); //compute HMAC and send message channel.SendMessage(msg, new BigInteger(hmacCalculator.ComputeHash(data))); } } } }