# HG changeset patch # User Ivo Smits # Date 1413029011 -7200 # Node ID 8fe32265680783cd697b62cc642d0a33763fdc6d # Parent 1474f92cf7e7b19d66cbe890afa7e37e84c160a3 Cleanup some old PML code diff -r 1474f92cf7e7 -r 8fe322656807 Pml/Channels/TCPPmlChannel.cs --- a/Pml/Channels/TCPPmlChannel.cs Wed Oct 01 23:16:06 2014 +0200 +++ b/Pml/Channels/TCPPmlChannel.cs Sat Oct 11 14:03:31 2014 +0200 @@ -15,7 +15,6 @@ _socket = socket; _rw = new PmlBinaryRW(_socket); _open = true; - //ThreadPool.RunTask(worker, null); } public override void WriteMessage(PmlElement message) { @@ -33,17 +32,5 @@ public override PmlElement ReadMessage() { return _rw.ReadMessage(); } - - /*private void worker(Object state) { - try { - while (_open) { - base.PushReceivedMessage(_rw.ReadMessage()); - } - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } finally { - Close(); - } - }*/ } } diff -r 1474f92cf7e7 -r 8fe322656807 Pml/Elements/Collection.cs --- a/Pml/Elements/Collection.cs Wed Oct 01 23:16:06 2014 +0200 +++ b/Pml/Elements/Collection.cs Sat Oct 11 14:03:31 2014 +0200 @@ -4,74 +4,74 @@ namespace UCIS.Pml { public class PmlCollection : PmlElement, ICollection { - private List pItems = new List(); + private List pItems = new List(); - public PmlCollection() { } - public PmlCollection(params PmlElement[] Elements) { - pItems.AddRange(Elements); - } - public PmlCollection(IEnumerable Elements) { - pItems.AddRange(Elements); - } - public PmlCollection(params String[] Elements) { - foreach (String s in Elements) pItems.Add(s); - } + public PmlCollection() { } + public PmlCollection(params PmlElement[] Elements) { + pItems.AddRange(Elements); + } + public PmlCollection(IEnumerable Elements) { + pItems.AddRange(Elements); + } + public PmlCollection(params String[] Elements) { + foreach (String s in Elements) pItems.Add(s); + } - public PmlElement Add(PmlElement Element) { - pItems.Add(Element); - return Element; - } - public void Remove(PmlElement Element) { - pItems.Remove(Element); - } - public void RemoveAt(int Index) { - pItems.RemoveAt(Index); - } - public void Clear() { - pItems.Clear(); - } - public bool Contains(PmlElement item) { - return pItems.Contains(item); - } - public void CopyTo(PmlElement[] array, int arrayIndex) { - pItems.CopyTo(array, arrayIndex); - } - public int Count { get { return pItems.Count; } } - public bool IsReadOnly { get { return false; } } - public IEnumerator GetEnumerator() { return pItems.GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() { return pItems.GetEnumerator(); } - bool ICollection.Remove(PmlElement item) { return pItems.Remove(item); } - void ICollection.Add(PmlElement item) { Add(item); } + public PmlElement Add(PmlElement Element) { + pItems.Add(Element); + return Element; + } + public void Remove(PmlElement Element) { + pItems.Remove(Element); + } + public void RemoveAt(int Index) { + pItems.RemoveAt(Index); + } + public void Clear() { + pItems.Clear(); + } + public bool Contains(PmlElement item) { + return pItems.Contains(item); + } + public void CopyTo(PmlElement[] array, int arrayIndex) { + pItems.CopyTo(array, arrayIndex); + } + public int Count { get { return pItems.Count; } } + public bool IsReadOnly { get { return false; } } + public IEnumerator GetEnumerator() { return pItems.GetEnumerator(); } + IEnumerator IEnumerable.GetEnumerator() { return pItems.GetEnumerator(); } + bool ICollection.Remove(PmlElement item) { return pItems.Remove(item); } + void ICollection.Add(PmlElement item) { Add(item); } - public override PmlType Type { get { return PmlType.Collection; } } + public override PmlType Type { get { return PmlType.Collection; } } - public override object ToObject() { return pItems; } - public override string ToString() { return null; } - public override bool ToBoolean() { return pItems.Count > 0; } - public override byte ToByte() { return (Byte)pItems.Count; } - public override decimal ToDecimal() { return pItems.Count; } - public override double ToDouble() { return pItems.Count; } - public override short ToInt16() { return (Int16)pItems.Count; } - public override int ToInt32() { return pItems.Count; } - public override long ToInt64() { return pItems.Count; } - public override sbyte ToSByte() { return (SByte)pItems.Count; } - public override float ToSingle() { return pItems.Count; } - public override ushort ToUInt16() { return (UInt16)pItems.Count; } - public override uint ToUInt32() { return (UInt32)pItems.Count; } - public override ulong ToUInt64() { return (UInt64)pItems.Count; } - public override char ToChar() { return '\0'; } - public override byte[] ToByteArray() { return null; } + public override object ToObject() { return pItems; } + public override string ToString() { return null; } + public override bool ToBoolean() { return pItems.Count > 0; } + public override byte ToByte() { return (Byte)pItems.Count; } + public override decimal ToDecimal() { return pItems.Count; } + public override double ToDouble() { return pItems.Count; } + public override short ToInt16() { return (Int16)pItems.Count; } + public override int ToInt32() { return pItems.Count; } + public override long ToInt64() { return pItems.Count; } + public override sbyte ToSByte() { return (SByte)pItems.Count; } + public override float ToSingle() { return pItems.Count; } + public override ushort ToUInt16() { return (UInt16)pItems.Count; } + public override uint ToUInt32() { return (UInt32)pItems.Count; } + public override ulong ToUInt64() { return (UInt64)pItems.Count; } + public override char ToChar() { return '\0'; } + public override byte[] ToByteArray() { return null; } - //public override PmlElement GetChild(string name) { return GetChild(name); } - public override PmlElement GetChild(int index) { return pItems[index]; } - public override IEnumerable GetChildren() { return pItems; } - public override IEnumerable> GetNamedChildren() { - KeyValuePair[] kvps = new KeyValuePair[pItems.Count]; - for (int i = 0; i < kvps.Length; i++) kvps[i] = new KeyValuePair(null, pItems[i]); - return kvps; - } - public override int GetChildCount() { return pItems.Count; } - public override void AddChild(string name, PmlElement value) { Add(value); } - public override void AddChild(PmlElement value) { Add(value); } + //public override PmlElement GetChild(string name) { return GetChild(name); } + public override PmlElement GetChild(int index) { return pItems[index]; } + public override IEnumerable GetChildren() { return pItems; } + public override IEnumerable> GetNamedChildren() { + KeyValuePair[] kvps = new KeyValuePair[pItems.Count]; + for (int i = 0; i < kvps.Length; i++) kvps[i] = new KeyValuePair(null, pItems[i]); + return kvps; + } + public override int GetChildCount() { return pItems.Count; } + public override void AddChild(string name, PmlElement value) { Add(value); } + public override void AddChild(PmlElement value) { Add(value); } } } diff -r 1474f92cf7e7 -r 8fe322656807 Pml/LegacyPmlCommunicator.cs --- a/Pml/LegacyPmlCommunicator.cs Wed Oct 01 23:16:06 2014 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,403 +0,0 @@ -using System; -using System.Threading; -using System.Collections.Generic; -using UCIS.Pml; - -namespace UCIS.Pml { - public class LegacyPmlCommunicator { - private class CSyncRequest { - internal PmlElement Reply; - internal ManualResetEvent ResetEvent = new ManualResetEvent(false); - } - public abstract class SessionBase { - private bool pActive; - private LegacyPmlCommunicator pConnection; - private UInt32 pSID; - - public uint SID { get { return pSID; } } - public bool Active { get { return pActive; } } - public LegacyPmlCommunicator Communicator { get { return pConnection; } } - - protected SessionBase(LegacyPmlCommunicator Connection) { - pConnection = Connection; - } - - protected void Accept(UInt32 SID) { - if (pActive) throw new InvalidOperationException("Session is active"); - pSID = SID; - lock (pConnection.pSessions) pConnection.pSessions.Add(pSID, this); - pActive = true; - } - protected void Request() { - Request(null); - } - protected void Request(PmlElement Message) { - if (pActive) throw new InvalidOperationException("Session is active"); - pSID = pConnection.GetNextSessionId(true); - lock (pConnection.pSessions) pConnection.pSessions.Add(pSID, this); - pConnection.WriteSessionMessage(pSID, 0, Message); - pActive = true; - } - - protected internal abstract void MessageIn(PmlElement Message); - - protected void SendMessage(PmlElement Message) { - if (!pActive) throw new InvalidOperationException("Session is not active"); - pConnection.WriteSessionMessage(pSID, 1, Message); - } - - public void Close() { - Close(null); - } - public void Close(PmlElement Message) { - if (!pActive) return; // throw new InvalidOperationException("Session is not active"); - pConnection.WriteSessionMessage(pSID, 2, Message); - ClosedA(); - } - - internal void ClosedA() { - pActive = false; - lock (pConnection.pSessions) pConnection.pSessions.Remove(pSID); - } - - internal void ClosedB(PmlElement Message) { - pActive = false; - Closed(Message); - } - - protected virtual void Closed(PmlElement Message) { - } - } - public class Session : SessionBase { - public event MessageReceivedEventHandler MessageReceived; - public delegate void MessageReceivedEventHandler(PmlElement Message); - public event SessionClosedEventHandler SessionClosed; - public delegate void SessionClosedEventHandler(PmlElement Message); - - public Session(LegacyPmlCommunicator Connection) : base(Connection) { } - - public new void Accept(UInt32 SID) { - base.Accept(SID); - } - public new void Request() { - Request(null); - } - public new void Request(PmlElement Message) { - base.Request(Message); - } - - protected internal override void MessageIn(PmlElement Message) { - if (MessageReceived != null) MessageReceived(Message); - } - - public new void SendMessage(PmlElement Message) { - base.SendMessage(Message); - } - - protected override void Closed(PmlElement Message) { - if (SessionClosed != null) SessionClosed(Message); - } - } - - private Dictionary pSessions = new Dictionary(); - private UInt32 pNextSession; - private Dictionary pSyncRequests = new Dictionary(); - private UInt32 pNextSyncRequest; - - private IPmlChannel _channel; - - public event MessageReceivedEventHandler MessageReceived; - public delegate void MessageReceivedEventHandler(PmlElement Message); - public event RequestReceivedEventHandler RequestReceived; - public delegate void RequestReceivedEventHandler(PmlElement Request, ref PmlElement Reply); - public event SessionRequestReceivedEventHandler SessionRequestReceived; - public delegate void SessionRequestReceivedEventHandler(PmlElement Request, uint SID); - public event EventHandler Closed; - - public ICollection Sessions { get { return (ICollection)pSessions.Values; } } - public int SyncRequests { get { return pSyncRequests.Count; } } - - public LegacyPmlCommunicator(IPmlChannel channel, bool autoStart) { - _channel = channel; - if (autoStart) Start(); - //_channel.BeginReadMessage(messageReceived, null); - //_channel.MessageReceived += messageReceived; - //_channel.Closed += closed; - } - public void Start() { - _channel.BeginReadMessage(messageReceived, null); - } - - public IPmlChannel Channel { get { return _channel; } } - - public void Close() { - //_channel.MessageReceived -= messageReceived; - //_channel.Closed -= closed; - _channel.Close(); - } - - private void _WriteMessage(PmlElement Message) { - lock (_channel) { - if (_channel.IsOpen) { - _channel.WriteMessage(Message); - } else { - throw new InvalidOperationException("Could not write message: the channel is not open"); - } - } - } - - private UInt32 GetNextSessionId(bool IsSession) { - if (IsSession) { - lock (pSessions) { - do { - if (pNextSession == UInt32.MaxValue) { - pNextSession = 0; - } else { - pNextSession += (uint)1; - } - } - while (pSessions.ContainsKey(pNextSession)); - return pNextSession; - } - } else { - lock (pSyncRequests) { - do { - if (pNextSyncRequest == UInt32.MaxValue) { - pNextSyncRequest = 0; - } else { - pNextSyncRequest += (uint)1; - } - } - while (pSyncRequests.ContainsKey(pNextSyncRequest)); - return pNextSyncRequest; - } - } - } - - protected void WriteSessionMessage(UInt32 SID, byte CMD, PmlElement MSG) { - PmlDictionary Msg2 = new PmlDictionary(); - Msg2.Add("CMD", new PmlString("SES")); - Msg2.Add("SID", new PmlInteger(SID)); - Msg2.Add("SCMD", new PmlInteger(CMD)); - Msg2.Add("MSG", MSG); - _WriteMessage(Msg2); - } - - protected void WriteSyncMessage(UInt32 SID, bool RPL, PmlElement MSG) { - PmlDictionary Msg2 = new PmlDictionary(); - if (RPL) { - Msg2.Add("CMD", new PmlString("RPL")); - } else { - Msg2.Add("CMD", new PmlString("REQ")); - } - Msg2.Add("SID", new PmlInteger(SID)); - Msg2.Add("MSG", MSG); - _WriteMessage(Msg2); - } - - private void messageReceived(IAsyncResult ar) { - PmlElement Message; - try { - Message = _channel.EndReadMessage(ar); - _channel.BeginReadMessage(messageReceived, null); - } catch (InvalidOperationException ex) { - Console.WriteLine("InvalidOperationException in LegacyPmlCommunicator.messageReceived: " + ex.Message); - closed(); - _channel.Close(); - return; - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - closed(); - _channel.Close(); - return; - } - int Ping = 0; - if (Message == null) { - if (Ping > 2) { - _channel.Close(); - return; - } else { - _WriteMessage(new PmlString("PING")); - } - Ping += 1; - } else if (Message is PmlString) { - string Cmd = Message.ToString(); - if (Cmd.Equals("PING")) { - _WriteMessage(new PmlString("PONG")); - } else if (Cmd.Equals("PONG")) { - Ping = 0; - } - } else if (Message is PmlDictionary) { - string Cmd = null; - Cmd = Message.GetChild("CMD").ToString(); - if (Cmd.Equals("SES")) { - UInt32 SID = default(UInt32); - byte SCMD = 0; - SessionBase Session = default(SessionBase); - PmlElement InnerMsg = default(PmlElement); - SID = Message.GetChild("SID").ToUInt32(); - SCMD = Message.GetChild("SCMD").ToByte(); - InnerMsg = Message.GetChild("MSG"); - lock (pSessions) { - if (pSessions.ContainsKey(SID)) { - Session = pSessions[SID]; - } else { - Session = null; - } - } - if (SCMD == 0) { - if (Session == null) { - if (SessionRequestReceived != null) { - try { - SessionRequestReceived(InnerMsg, SID); - } catch (Exception ex) { - Console.WriteLine("Exception in LegacyPmlCommnuicator.messageReceived->SessionRequestReceived: " + ex.ToString()); - WriteSessionMessage(SID, 2, null); - } - } - } else { - try { - Session.ClosedA(); - Session.ClosedB(null); - } catch (Exception ex) { - Console.WriteLine("Exception in LegacyPmlCommnuicator.messageReceived->Session.ClosedA/B: " + ex.ToString()); - } - WriteSessionMessage(SID, 2, null); - } - } else if (SCMD == 1) { - if (Session == null) { - WriteSessionMessage(SID, 2, null); - } else { - try { - Session.MessageIn(InnerMsg); - } catch (Exception ex) { - Console.WriteLine("Exception in LegacyPmlCommnuicator.messageReceived->Session.MessageIn: " + ex.ToString()); - WriteSessionMessage(SID, 2, null); - } - } - } else if (SCMD == 2) { - if (Session != null) { - try { - Session.ClosedA(); - Session.ClosedB(InnerMsg); - } catch (Exception ex) { - Console.WriteLine("Exception in LegacyPmlCommnuicator.messageReceived->Session.ClosedA/B: " + ex.ToString()); - } - } - } - } else if (Cmd.Equals("RPL")) { - UInt32 SID = default(UInt32); - CSyncRequest SRequest = null; - SID = Message.GetChild("SID").ToUInt32(); - lock (pSyncRequests) { - if (pSyncRequests.TryGetValue(SID, out SRequest)) { - pSyncRequests.Remove(SID); - } else { - Console.WriteLine("UCIS.PML.Connection.Worker Invalid request ID in reply: " + SID.ToString()); - } - } - if (SRequest != null) { - SRequest.Reply = Message.GetChild("MSG"); - SRequest.ResetEvent.Set(); - } - } else if (Cmd.Equals("REQ")) { - UCIS.ThreadPool.RunCall(SyncRequestHandler, Message); - //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SyncRequestHandler), Message); - } else if (Cmd.Equals("MSG")) { - PmlElement InnerMsg = Message.GetChild("MSG"); - if (MessageReceived != null) MessageReceived(InnerMsg); - } else { - throw new InvalidOperationException("Invalid operation"); - } - } - } - private void closed() { - //_channel.MessageReceived -= messageReceived; - //_channel.Closed -= closed; - Console.WriteLine("UCIS.PML.Connection: Connection closed"); - try { - SessionBase[] sessions; - lock (pSessions) { - sessions = new SessionBase[pSessions.Count]; - pSessions.Values.CopyTo(sessions, 0); - } - foreach (SessionBase S in sessions) { - try { - S.ClosedB(null); - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } - } - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } - lock (pSessions) pSessions.Clear(); - try { - CSyncRequest[] reqs; - lock (pSyncRequests) { - reqs = new CSyncRequest[pSyncRequests.Count]; - pSyncRequests.Values.CopyTo(reqs, 0); - } - foreach (CSyncRequest T in reqs) { - T.ResetEvent.Set(); - } - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } - lock (pSyncRequests) pSyncRequests.Clear(); - if (Closed != null) Closed(this, new EventArgs()); - } - - private void SyncRequestHandler(object state) { - PmlDictionary Message = (PmlDictionary)state; - PmlElement Reply = null; - UInt32 SID = 0; - try { - SID = Message.GetChild("SID").ToUInt32(); - PmlElement InnerMsg = Message.GetChild("MSG"); - if (RequestReceived != null) { - RequestReceived(InnerMsg, ref Reply); - } - } catch (Exception ex) { - Reply = new PmlDictionary(); - ((PmlDictionary)Reply).Add("EXCEPTION", new PmlString(ex.ToString())); - Console.WriteLine(ex.ToString()); - } - try { - WriteSyncMessage(SID, true, Reply); - } catch (Exception ex) { - Console.WriteLine("Exception: " + ex.ToString()); - } - } - - public PmlElement SyncRequest(PmlElement Request) { - return SyncRequest(Request, 30000); - } - public PmlElement SyncRequest(PmlElement Request, int Timeout) { - CSyncRequest SyncEvent = new CSyncRequest(); - UInt32 SID = GetNextSessionId(false); - lock (pSyncRequests) pSyncRequests.Add(SID, SyncEvent); - try { - WriteSyncMessage(SID, false, Request); - if (!SyncEvent.ResetEvent.WaitOne(Timeout, false)) { - lock (pSyncRequests) pSyncRequests.Remove(SID); - throw new TimeoutException("The SyncRequest timed out (SID=" + SID.ToString() + ")"); - } - } finally { - lock (pSyncRequests) pSyncRequests.Remove(SID); - } - return SyncEvent.Reply; - } - - public void SendMessage(PmlElement Message) { - PmlDictionary Msg = new PmlDictionary(); - Msg.Add("CMD", new PmlString("MSG")); - Msg.Add("MSG", Message); - _WriteMessage(Msg); - } - - public void SendRawMessage(PmlElement Message) { - _WriteMessage(Message); - } - } -} diff -r 1474f92cf7e7 -r 8fe322656807 Pml/PmlCommunicator.cs --- a/Pml/PmlCommunicator.cs Wed Oct 01 23:16:06 2014 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,342 +0,0 @@ -using System; -using System.Threading; -using System.Collections.Generic; - -namespace UCIS.Pml { -/* class PmlCommunicator : IPmlCommunicator, IDisposable { - private IPmlChannel _channel; - private Dictionary _subchannels = new Dictionary(); - private Random _random = new Random(); - - private enum CommandCode : int { - CallWithoutReply = 0, - CallWithReply = 1, - Message = 2, - ChannelRequest = 3, - ChannelAcknowledge = 4, - ChannelClose = 5, - Error = 6 - } - - private interface IPmlSubChannel { - void CloseIn(); - void ErrorIn(PmlElement message); - void MessageIn(PmlElement message); - } - - private class ChannelRequestWaitHandler : IAsyncResult { - internal AsyncCallback Callback = null; - internal Object CallbackState = null; - internal ManualResetEvent Event = null; - internal PmlSubChannel Channel = null; - internal bool Completed = false; - - internal ChannelRequestWaitHandler(PmlSubChannel channel) { - Channel = channel; - } - - internal void Complete() { - Completed = true; - if (Event != null) Event.Set(); - if (Callback != null) Callback.Invoke(this); - } - - public object AsyncState { get { return CallbackState; } } - public WaitHandle AsyncWaitHandle { get { return null; } } - public bool CompletedSynchronously { get { return false; } } - public bool IsCompleted { get { return Completed; } } - } - private class PmlSubChannel : ActivePmlChannel, IPmlSubChannel { - private enum ChannelState { Requesting, Acknowledged, Closed } - - private PmlCommunicator _communicator; - private UInt32 _id; - private ChannelState _state; - - internal PmlSubChannel(PmlCommunicator communicator, UInt32 sid) { - _communicator = communicator; - _id = sid; - _state = ChannelState.Requesting; - } - - public override bool IsOpen { get { return _state == ChannelState.Acknowledged; } } - - internal void AcknowledgeIn() { - if (_state != 0) throw new InvalidOperationException("The subchannel is not awaiting an acknowledgement"); - _state = ChannelState.Acknowledged; - } - void IPmlSubChannel.CloseIn() { - _state = ChannelState.Closed; - _communicator._subchannels.Remove(_id); - base.Close(); - } - void IPmlSubChannel.ErrorIn(PmlElement message) { - (this as IPmlSubChannel).CloseIn(); - } - void IPmlSubChannel.MessageIn(PmlElement message) { - base.PushReceivedMessage(message); - } - - internal void AcknowledgeOut() { - if (_state != 0) throw new InvalidOperationException("The subchannel is not awaiting an acknowledgement"); - _state = ChannelState.Acknowledged; - _communicator.sendMessage(CommandCode.ChannelAcknowledge, _id, null); - } - internal void RejectOut() { - if (_state != 0) throw new InvalidOperationException("The subchannel is not awaiting an acknowledgement"); - _state = ChannelState.Closed; - _communicator.sendMessage(CommandCode.ChannelClose, _id, null); - } - - public override void SendMessage(PmlElement message) { - if (_state != ChannelState.Acknowledged) throw new InvalidOperationException("The subchannel is not open"); - _communicator.sendMessage(CommandCode.Message, _id, message); - } - public override void Close() { - if (_state != ChannelState.Acknowledged) return; - _state = ChannelState.Closed; - _communicator.sendMessage(CommandCode.ChannelClose, _id, null); - _communicator._subchannels.Remove(_id); - base.Close(); - } - } - private class PmlChannelRequestReceivedEventArgsA : PmlChannelRequestReceivedEventArgs { - private PmlCommunicator _communicator; - private PmlElement _data; - private PmlSubChannel _channel; - private bool _accepted; - private bool _rejected; - internal PmlChannelRequestReceivedEventArgsA(PmlCommunicator communicator, UInt32 sid, PmlElement message) { - _communicator = communicator; - _channel = new PmlSubChannel(communicator, sid); - _data = message; - } - public override IPmlChannel Accept() { - if (_accepted || _rejected) throw new InvalidOperationException("The channel has already been accepted or rejected"); - _accepted = true; - _channel.AcknowledgeOut(); - return _channel; - } - public override void Reject() { - if (_accepted) throw new InvalidOperationException("The channel has already been accepted"); - if (_rejected) return; - _rejected = true; - _channel.RejectOut(); - } - internal void RejectIfNotAccepted() { - if (!_accepted) Reject(); - } - public override PmlElement Data { - get { - return _data; - } - } - } - - private class PmlInvocation : IAsyncResult, IPmlSubChannel { - internal PmlCommunicator Communicator = null; - internal AsyncCallback Callback = null; - internal Object CallbackState = null; - internal bool Error = false; - internal bool Completed = false; - internal PmlElement Message = null; - internal ManualResetEvent Event = null; - internal UInt32 ID; - - internal PmlInvocation(PmlCommunicator communicator, UInt32 id) { - Communicator = communicator; - ID = id; - } - - void IPmlSubChannel.CloseIn() { - (this as IPmlSubChannel).ErrorIn(null); - } - void IPmlSubChannel.ErrorIn(PmlElement message) { - Error = true; - Communicator._subchannels.Remove(ID); - (this as IPmlSubChannel).MessageIn(message); - } - void IPmlSubChannel.MessageIn(PmlElement message) { - Message = message; - Completed = true; - if (Event != null) Event.Set(); - if (Callback != null) Callback.Invoke(this); - } - - public object AsyncState { get { return CallbackState; } } - public WaitHandle AsyncWaitHandle { get { return null; } } - public bool CompletedSynchronously { get { return false; } } - public bool IsCompleted { get { return Completed; } } - } - - public event EventHandler CallReceived; - public event EventHandler ChannelRequestReceived; - - public PmlCommunicator(IPmlChannel channel) { - _channel = channel; - _channel.Closed += channelClosed; - } - - public void Dispose() { - _channel.Close(); - _channel = null; - IPmlSubChannel[] A = new IPmlSubChannel[_subchannels.Count]; - _subchannels.Values.CopyTo(A, 0); - foreach (IPmlSubChannel S in A) S.CloseIn(); - _subchannels.Clear(); - _subchannels = null; - _random = null; - } - - private void channelClosed(Object sender, EventArgs e) { - Dispose(); - } - - public IPmlChannel Channel { get { return _channel; } } - - public void Call(PmlElement message) { - sendMessage(0, 0, message); //Call without reply - } - public PmlElement Invoke(PmlElement message) { - return Invoke(message, 60000); - } - public PmlElement Invoke(PmlElement message, int timeout) { - UInt32 sid = getSessionID(); - PmlInvocation inv = new PmlInvocation(this, sid); - inv.Event = new ManualResetEvent(false); - _subchannels.Add(sid, inv); - sendMessage(CommandCode.CallWithReply, sid, message); - inv.Event.WaitOne(timeout); - if (inv.Error) throw new Exception(message.ToString()); - return inv.Message; - } - - public IAsyncResult BeginInvoke(PmlElement message, AsyncCallback callback, Object state) { - UInt32 sid = getSessionID(); - PmlInvocation inv = new PmlInvocation(this, sid); - inv.Callback = callback; - inv.CallbackState = state; - _subchannels.Add(sid, inv); - sendMessage(CommandCode.CallWithReply, sid, message); - return inv; - } - public PmlElement EndInvoke(IAsyncResult result) { - PmlInvocation ar = (PmlInvocation)result; - if (!ar.Completed) { - (_subchannels as IList).Remove(ar); - throw new InvalidOperationException("The asynchronous operation has not completed"); - } else if (ar.Error) { - throw new Exception(ar.Message.ToString()); - } else { - return ar.Message; - } - } - - public IPmlChannel CreateChannel(PmlElement data) { - UInt32 sid = getSessionID(); - PmlSubChannel ch = new PmlSubChannel(this, sid); - ChannelRequestWaitHandler wh = new ChannelRequestWaitHandler(ch); - wh.Event = new ManualResetEvent(false); - _subchannels.Add(sid, ch); - sendMessage(CommandCode.ChannelRequest, sid, data); - wh.Event.WaitOne(); - if (!ch.IsOpen) return null; - return ch; - } - public IAsyncResult BeginCreateChannel(PmlElement data, AsyncCallback callback, Object state) { - UInt32 sid = getSessionID(); - PmlSubChannel ch = new PmlSubChannel(this, sid); - ChannelRequestWaitHandler wh = new ChannelRequestWaitHandler(ch); - wh.Callback = callback; - wh.CallbackState = state; - _subchannels.Add(sid, ch); - sendMessage(CommandCode.ChannelRequest, sid, data); - if (!ch.IsOpen) return null; - return wh; - } - public IPmlChannel EndCreateChannel(IAsyncResult result) { - ChannelRequestWaitHandler ar = (ChannelRequestWaitHandler)result; - if (!ar.Channel.IsOpen) return null; - return ar.Channel; - } - - private UInt32 getSessionID() { - return (uint)_random.Next(); - } - - private void sendMessage(CommandCode cmd, uint sid, PmlElement message) { - PmlDictionary msg = new PmlDictionary(); - msg.Add("c", (int)cmd); - if (cmd > 0) msg.Add("s", sid); - if (message != null) msg.Add("m", message); - _channel.SendMessage(msg); - } - - private void invokeCallReceived(Object state) { - PmlCallReceivedEventArgs e = (PmlCallReceivedEventArgs)state; - try { - if (CallReceived != null) CallReceived(this, e); - if (e.WantReply) sendMessage(CommandCode.Message, e.SID, e.Reply); - } catch (Exception ex) { - if (e.WantReply) sendMessage(CommandCode.Error, e.SID, new PmlString(ex.ToString())); - } - } - private void invokeChannelRequestReceived(Object state) { - PmlChannelRequestReceivedEventArgsA e = (PmlChannelRequestReceivedEventArgsA)state; - if (ChannelRequestReceived != null) ChannelRequestReceived(this, e); - e.RejectIfNotAccepted(); - } - - private void messageReceived(Object sender, EventArgs e) { - IPmlSubChannel subChannel = null; - UInt32 sid = 0; - bool subChannelExists = false; - if (!(e.Message is PmlDictionary)) return; - PmlDictionary msg = (PmlDictionary)e.Message; - PmlElement cmdElement = msg.GetChild("c"); - PmlElement sidElement = msg.GetChild("i"); - PmlElement msgElement = msg.GetChild("m"); - if (cmdElement == null) return; - if (sidElement != null) sid = sidElement.ToUInt32(); - if (sidElement != null) subChannelExists = _subchannels.TryGetValue(sid, out subChannel); - if (!subChannelExists) subChannel = null; - switch ((CommandCode)cmdElement.ToInt32()) { - case CommandCode.CallWithoutReply: - if (CallReceived != null) ThreadPool.RunCall(invokeCallReceived, new PmlCallReceivedEventArgs(msgElement, false, 0)); - break; - case CommandCode.CallWithReply: - if (CallReceived != null) ThreadPool.RunCall(invokeCallReceived, new PmlCallReceivedEventArgs(msgElement, true, sid)); - else sendMessage(CommandCode.Error, sid, null); - break; - case CommandCode.Message: //Reply to call | subchannel message - if (subChannelExists) subChannel.MessageIn(msgElement); - else sendMessage(CommandCode.Error, sid, null); - break; - case CommandCode.ChannelRequest: - if (subChannelExists) { - sendMessage(CommandCode.Error, sid, null); - subChannel.CloseIn(); - } else { - if (ChannelRequestReceived == null) sendMessage(CommandCode.ChannelClose, sid, null); - else ThreadPool.RunCall(invokeChannelRequestReceived, new PmlChannelRequestReceivedEventArgsA(this, sid, msgElement)); - } - break; - case CommandCode.ChannelAcknowledge: - if (subChannelExists) { - if (subChannel is PmlSubChannel) (subChannel as PmlSubChannel).AcknowledgeIn(); - else { - sendMessage(CommandCode.Error, sid, null); //Error - subChannel.CloseIn(); - } - } else sendMessage(CommandCode.Error, sid, null); //Error - break; - case CommandCode.ChannelClose: - if (subChannelExists) subChannel.CloseIn(); - break; - case CommandCode.Error: - if (subChannelExists) subChannel.ErrorIn(msgElement); - break; - } - } - }*/ -} diff -r 1474f92cf7e7 -r 8fe322656807 Pml/PmlCommunicator2.cs --- a/Pml/PmlCommunicator2.cs Wed Oct 01 23:16:06 2014 +0200 +++ b/Pml/PmlCommunicator2.cs Sat Oct 11 14:03:31 2014 +0200 @@ -14,91 +14,6 @@ void CloseIn(); UInt32 ID { get; } } - /*public abstract class SessionBase : ISession { - private bool pActive; - private PmlCommunicator _communicator; - private UInt32 _id; - - public uint SID { get { return _id; } } - public bool Active { get { return pActive; } } - public PmlCommunicator Communicator { get { return _communicator; } } - - protected SessionBase(PmlCommunicator Connection) { - _communicator = Connection; - } - - protected void Accept(UInt32 sid) { - if (pActive) throw new InvalidOperationException("Session is active"); - _id = sid; - lock (_communicator._sessions) _communicator._sessions.Add(_id, this); - pActive = true; - } - protected void Request() { - Request(null); - } - protected void Request(PmlElement Message) { - if (pActive) throw new InvalidOperationException("Session is active"); - _id = _communicator.GetNextSessionId(true); - lock (_communicator._sessions) _communicator._sessions.Add(_id, this); - _communicator.WriteSessionMessage(_id, 0, Message); - pActive = true; - } - - uint ISession.ID { get { return _id; } } - void ISession.MessageIn(PmlElement message) { this.MessageIn(message); } - void ISession.CloseIn() { - pActive = false; - _communicator.RemoveSession(this); - Closed(null); - } - - protected internal abstract void MessageIn(PmlElement Message); - - protected void SendMessage(PmlElement Message) { - if (!pActive) throw new InvalidOperationException("Session is not active"); - _communicator.WriteSessionMessage(_id, 1, Message); - } - - public void Close() { - if (!pActive) return; - pActive = false; - _communicator.WriteSessionMessage(_id, 2, null); - _communicator.RemoveSession(this); - } - - protected virtual void Closed(PmlElement Message) { } - } - public class Session : SessionBase { - public event MessageReceivedEventHandler MessageReceived; - public delegate void MessageReceivedEventHandler(PmlElement Message); - public event SessionClosedEventHandler SessionClosed; - public delegate void SessionClosedEventHandler(PmlElement Message); - - public Session(PmlCommunicator Connection) : base(Connection) { } - - public new void Accept(UInt32 SID) { - base.Accept(SID); - } - public new void Request() { - Request(null); - } - public new void Request(PmlElement Message) { - base.Request(Message); - } - - protected internal override void MessageIn(PmlElement Message) { - if (MessageReceived != null) MessageReceived(Message); - } - - public new void SendMessage(PmlElement Message) { - base.SendMessage(Message); - } - - protected override void Closed(PmlElement Message) { - if (SessionClosed != null) SessionClosed(Message); - } - }*/ - private class PmlSubChannel : ActivePmlChannel, ISession { private enum ChannelState { Requesting, Acknowledged, Closed } @@ -148,11 +63,6 @@ _sid = sid; _accepted = _rejected = false; } - public UInt32 AcceptSession() { - if (_accepted || _rejected) throw new InvalidOperationException("The channel has already been accepted or rejected"); - _accepted = true; - return _sid; - } public override IPmlChannel Accept() { if (_accepted || _rejected) throw new InvalidOperationException("The channel has already been accepted or rejected"); _accepted = true; @@ -163,16 +73,11 @@ if (_rejected) return; _rejected = true; _communicator.WriteSessionMessage(_sid, 2, null); - //_channel.RejectOut(); } internal void RejectIfNotAccepted() { if (!_accepted) Reject(); } - public override PmlElement Data { - get { - return _data; - } - } + public override PmlElement Data { get { return _data; } } } public event EventHandler CallReceived; @@ -268,9 +173,8 @@ if (Message is PmlString) { string Cmd = Message.ToString(); if (Cmd.Equals("PING")) { - _WriteMessage(new PmlString("PONG")); - /*} else if (Cmd.Equals("PONG")) { - Ping = 0;*/ + _WriteMessage("PONG"); + } else if (Cmd.Equals("PONG")) { } } else if (Message is PmlDictionary) { string Cmd = Message.GetChild("CMD").ToString(); diff -r 1474f92cf7e7 -r 8fe322656807 Pml/PmlConnection.cs --- a/Pml/PmlConnection.cs Wed Oct 01 23:16:06 2014 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,384 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using UCIS.Net; -using System.Net.Sockets; -using System.Threading; -using System.IO; - -namespace UCIS.Pml { - /*public class PmlConnection : LegacyPmlCommunicator { - public PmlConnection(Socket Socket) : this(new TCPPmlChannel(Socket)) { } - public PmlConnection(TCPStream Stream) : this(new TCPPmlChannel(Stream)) { } - public PmlConnection(Stream Stream) : this(new PmlBinaryRW(Stream)) {} - public PmlConnection(IPmlRW RW) : this(new PmlChannel(RW)) { } - public PmlConnection(IPmlChannel CH) : base(CH) { } - }*/ - public class PmlConnection { - private class CSyncRequest { - internal PmlElement Reply; - internal ManualResetEvent ResetEvent = new ManualResetEvent(false); - } - public abstract class SessionBase { - private bool pActive; - private PmlConnection pConnection; - private UInt32 pSID; - - protected SessionBase(PmlConnection Connection) { - pConnection = Connection; - } - - protected void Accept(UInt32 SID) { - if (pActive) throw new InvalidOperationException("Session is active"); - pSID = SID; - lock (pConnection.pSessions) pConnection.pSessions.Add(pSID, this); - pActive = true; - } - protected void Request() { - Request(null); - } - protected void Request(PmlElement Message) { - if (pActive) throw new InvalidOperationException("Session is active"); - pSID = pConnection.GetNextSessionId(true); - lock (pConnection.pSessions) pConnection.pSessions.Add(pSID, this); - pConnection.WriteSessionMessage(pSID, 0, Message); - pActive = true; - } - - protected internal abstract void MessageIn(PmlElement Message); - - protected void SendMessage(PmlElement Message) { - if (!pActive) throw new InvalidOperationException("Session is not active"); - pConnection.WriteSessionMessage(pSID, 1, Message); - } - - public void Close() { - Close(null); - } - public void Close(PmlElement Message) { - if (!pActive) throw new InvalidOperationException("Session is not active"); - pConnection.WriteSessionMessage(pSID, 2, Message); - ClosedA(); - } - - internal void ClosedA() { - pActive = false; - lock (pConnection.pSessions) pConnection.pSessions.Remove(pSID); - } - - internal void ClosedB(PmlElement Message) { - pActive = false; - Closed(Message); - } - - protected virtual void Closed(PmlElement Message) { - } - } - public class Session : SessionBase { - public event MessageReceivedEventHandler MessageReceived; - public delegate void MessageReceivedEventHandler(PmlElement Message); - public event SessionClosedEventHandler SessionClosed; - public delegate void SessionClosedEventHandler(PmlElement Message); - - public Session(PmlConnection Connection) : base(Connection) { } - - public new void Accept(UInt32 SID) { - base.Accept(SID); - } - public new void Request() { - Request(null); - } - public new void Request(PmlElement Message) { - base.Request(Message); - } - - protected internal override void MessageIn(PmlElement Message) { - if (MessageReceived != null) MessageReceived(Message); - } - - public new void SendMessage(PmlElement Message) { - base.SendMessage(Message); - } - - protected override void Closed(PmlElement Message) { - if (SessionClosed != null) SessionClosed(Message); - } - } - - private Dictionary pSessions = new Dictionary(); - private UInt32 pNextSession; - private Dictionary pSyncRequests = new Dictionary(); - private UInt32 pNextSyncRequest; - - private Stream pStream; - - public event MessageReceivedEventHandler MessageReceived; - public delegate void MessageReceivedEventHandler(PmlElement Message); - public event RequestReceivedEventHandler RequestReceived; - public delegate void RequestReceivedEventHandler(PmlElement Request, ref PmlElement Reply); - public event SessionRequestReceivedEventHandler SessionRequestReceived; - public delegate void SessionRequestReceivedEventHandler(PmlElement Request, uint SID); - - private IPmlWriter _writer; - private IPmlReader _reader; - - public PmlConnection(Socket Socket) : this(new TCPStream(Socket)) { } - public PmlConnection(Stream Stream) : this(new PmlBinaryRW(Stream)) { - pStream = Stream; - } - public PmlConnection(IPmlRW RMRW) : this(RMRW, RMRW) { } - public PmlConnection(IPmlReader Reader, IPmlWriter Writer) { - _reader = Reader; - _writer = Writer; - } - - public void Close() { - if (pStream != null) pStream.Close(); - } - - public IPmlReader Reader { - get { return _reader; } - } - public IPmlWriter Writer { - get { return _writer; } - } - private PmlElement _ReadMessage() { - PmlElement Message = _reader.ReadMessage(); - return Message; //Warning: Can't lock reader because it can be the same as the Writer (possible deadlock) - } - private void _WriteMessage(PmlElement Message) { - lock (_writer) _writer.WriteMessage(Message); - } - - private UInt32 GetNextSessionId(bool IsSession) { - if (IsSession) { - lock (pSessions) { - do { - if (pNextSession == UInt32.MaxValue) { - pNextSession = 0; - } else { - pNextSession += (uint)1; - } - } - while (pSessions.ContainsKey(pNextSession)); - return pNextSession; - } - } else { - lock (pSyncRequests) { - do { - if (pNextSyncRequest == UInt32.MaxValue) { - pNextSyncRequest = 0; - } else { - pNextSyncRequest += (uint)1; - } - } - while (pSyncRequests.ContainsKey(pNextSyncRequest)); - return pNextSyncRequest; - } - } - } - - protected void WriteSessionMessage(UInt32 SID, byte CMD, PmlElement MSG) { - PmlDictionary Msg2 = new PmlDictionary(); - Msg2.Add("CMD", new PmlString("SES")); - Msg2.Add("SID", new PmlInteger(SID)); - Msg2.Add("SCMD", new PmlInteger(CMD)); - Msg2.Add("MSG", MSG); - _WriteMessage(Msg2); - } - - protected void WriteSyncMessage(UInt32 SID, bool RPL, PmlElement MSG) { - PmlDictionary Msg2 = new PmlDictionary(); - if (RPL) { - Msg2.Add("CMD", new PmlString("RPL")); - } else { - Msg2.Add("CMD", new PmlString("REQ")); - } - Msg2.Add("SID", new PmlInteger(SID)); - Msg2.Add("MSG", MSG); - _WriteMessage(Msg2); - } - - public void Worker() { - try { - PmlElement Message = null; - int Ping = 0; - while (true) { - try { - Message = _ReadMessage(); - if (Message == null) Console.WriteLine("UCIS.PML.Connection: Message is just null?"); - } catch (EndOfStreamException) { - Console.WriteLine("UCIS.PML.Connection: End of stream"); - return; - } catch (SocketException ex) { - if (ex.ErrorCode == (int)SocketError.TimedOut) { - Console.WriteLine("UCIS.PML.Connection: SocketException/TimedOut"); - Message = null; - } else if (ex.ErrorCode == (int)SocketError.ConnectionReset) { - Console.WriteLine("UCIS.PML.Connection: Connection reset by peer"); - return; - } else { - throw new Exception("Exception while reading message", ex); - } - } catch (IOException ex) { - Console.WriteLine("UCIS.PML.Connection: IOException: " + ex.Message); - Message = null; - } catch (TimeoutException) { - Message = null; - } - if (Message == null) { - if (Ping > 2) { - Console.WriteLine("UCIS.PML.Connection: Connection timed out"); - break; - } else { - _WriteMessage(new PmlString("PING")); - } - Ping += 1; - } else if (Message is PmlString) { - string Cmd = Message.ToString(); - if (Cmd.Equals("PING")) { - _WriteMessage(new PmlString("PONG")); - } else if (Cmd.Equals("PONG")) { - Ping = 0; - } - } else if (Message is PmlDictionary) { - string Cmd = null; - Cmd = Message.GetChild("CMD").ToString(); - if (Cmd.Equals("SES")) { - UInt32 SID = default(UInt32); - byte SCMD = 0; - SessionBase Session = default(SessionBase); - PmlElement InnerMsg = default(PmlElement); - SID = Message.GetChild("SID").ToUInt32(); - SCMD = Message.GetChild("SCMD").ToByte(); - InnerMsg = Message.GetChild("MSG"); - lock (pSessions) { - if (pSessions.ContainsKey(SID)) { - Session = pSessions[SID]; - } else { - Session = null; - } - } - if (SCMD == 0) { - if (Session == null) { - if (SessionRequestReceived != null) { - SessionRequestReceived(InnerMsg, SID); - } - } else { - Session.ClosedA(); - Session.ClosedB(null); - WriteSessionMessage(SID, 2, null); - } - } else if (SCMD == 1) { - if (Session == null) { - WriteSessionMessage(SID, 2, null); - } else { - Session.MessageIn(InnerMsg); - } - } else if (SCMD == 2) { - if (Session != null) { - Session.ClosedA(); - Session.ClosedB(InnerMsg); - } - } - } else if (Cmd.Equals("RPL")) { - UInt32 SID = default(UInt32); - CSyncRequest SRequest = null; - SID = Message.GetChild("SID").ToUInt32(); - lock (pSyncRequests) { - if (pSyncRequests.TryGetValue(SID, out SRequest)) { - pSyncRequests.Remove(SID); - } else { - Console.WriteLine("UCIS.PML.Connection.Worker Invalid request ID in reply: " + SID.ToString()); - } - } - if (SRequest != null) { - SRequest.Reply = Message.GetChild("MSG"); - SRequest.ResetEvent.Set(); - } - } else if (Cmd.Equals("REQ")) { - System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SyncRequestHandler), Message); - } else if (Cmd.Equals("MSG")) { - PmlElement InnerMsg = Message.GetChild("MSG"); - if (MessageReceived != null) MessageReceived(InnerMsg); - } else { - throw new InvalidOperationException("Invalid operation"); - } - } - } - } catch (System.Threading.ThreadAbortException ex) { - throw; - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } finally { - Console.WriteLine("UCIS.PML.Connection: Connection closed"); - try { - foreach (SessionBase S in pSessions.Values) { - try { - S.ClosedB(null); - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } - } - pSessions.Clear(); - foreach (CSyncRequest T in pSyncRequests.Values) { - T.ResetEvent.Set(); - } - } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - } - } - } - - private void SyncRequestHandler(object state) { - PmlDictionary Message = (PmlDictionary)state; - UInt32 SID = default(UInt32); - PmlElement InnerMsg = default(PmlElement); - PmlElement Reply = default(PmlElement); - Reply = null; - SID = Message.GetChild("SID").ToUInt32(); - InnerMsg = Message.GetChild("MSG"); - try { - if (RequestReceived != null) { - RequestReceived(InnerMsg, ref Reply); - } - } catch (Exception ex) { - Reply = new PmlDictionary(); - ((PmlDictionary)Reply).Add("EXCEPTION", new PmlString(ex.ToString())); - Console.WriteLine(ex.ToString()); - } - WriteSyncMessage(SID, true, Reply); - } - - public PmlElement SyncRequest(PmlElement Request) { - return SyncRequest(Request, 30000); - } - public PmlElement SyncRequest(PmlElement Request, int Timeout) { - UInt32 SID = default(UInt32); - CSyncRequest SyncEvent = new CSyncRequest(); - SID = GetNextSessionId(false); - lock (pSyncRequests) pSyncRequests.Add(SID, SyncEvent); - WriteSyncMessage(SID, false, Request); - if (!SyncEvent.ResetEvent.WaitOne(Timeout, false)) { - Console.WriteLine("UCIS.PML.Connection.SyncRequest Timeout: " + SID.ToString()); - lock (pSyncRequests) pSyncRequests.Remove(SID); - throw new TimeoutException(); - } - return SyncEvent.Reply; - } - - public void SendMessage(PmlElement Message) { - PmlDictionary Msg = new PmlDictionary(); - Msg.Add("CMD", new PmlString("MSG")); - Msg.Add("MSG", Message); - _WriteMessage(Msg); - } - - public PmlElement ReadMessage() { - return _ReadMessage(); - } - public void SendRawMessage(PmlElement Message) { - _WriteMessage(Message); - } - } -} diff -r 1474f92cf7e7 -r 8fe322656807 UCIS.Core.csproj --- a/UCIS.Core.csproj Wed Oct 01 23:16:06 2014 +0200 +++ b/UCIS.Core.csproj Sat Oct 11 14:03:31 2014 +0200 @@ -117,15 +117,12 @@ - - -