diff --git a/ConsoleApplication1/ConsoleApplication1.csproj b/ConsoleApplication1/ConsoleApplication1.csproj index d03d154..a814995 100644 --- a/ConsoleApplication1/ConsoleApplication1.csproj +++ b/ConsoleApplication1/ConsoleApplication1.csproj @@ -56,13 +56,17 @@ - - {5C1838A8-CD45-450F-9065-1ED7CF6557C5} - SocketService.Client.API - - + {93FD4F32-5214-40E3-8E36-5B4E354F10C4} - SocketService.Framework.Client + SocketService.Client.Core + + + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9} + SocketService.Event + + + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1} + SocketService.Shared diff --git a/ConsoleApplication1/Program.cs b/ConsoleApplication1/Program.cs index 99bb6c8..c05b607 100644 --- a/ConsoleApplication1/Program.cs +++ b/ConsoleApplication1/Program.cs @@ -1,50 +1,60 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Net.Sockets; using System.Threading; -using System.Security.Cryptography; -using System.Collections; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; -using System.IO.Compression; -using SocketService.Client.API; -using SocketService.Framework.SharedObjects; -using SocketService.Framework.Request; -using SocketService.Client.API.Event; -using SocketService.Client.API.Data; +using SocketService.Client.Core; +using SocketService.Client.Core.Request; +using SocketService.Event; +using SocketService.Shared.Response; namespace ConsoleApplication1 { class Program { - ClientEngine _engine = new ClientEngine(); - Server _server = new Server(); + readonly ClientEngine _engine = new ClientEngine(); + readonly Server _server = new Server(); - private long _loginState = 0; - private AutoResetEvent _loginReceievedEvent = new AutoResetEvent(false); - private AutoResetEvent _connectedReceivedEvent = new AutoResetEvent(false); + private long _loginState; + private readonly AutoResetEvent _loginReceievedEvent = new AutoResetEvent(false); + private readonly AutoResetEvent _connectedReceivedEvent = new AutoResetEvent(false); - private bool _connectionSuccessful = false; + private bool _connectionSuccessful; private string _userName = string.Empty; static void Main(string[] args) { - Program p = new Program(); + var p = new Program(); p.Run(args); } public void Run(string[] args) { - _engine.ServerMessageRecieved += new EventHandler(engine_ServerMessageRecieved); - _engine.LoginResponseReceived += new EventHandler(engine_LoginResponseReceived); - _engine.GetRoomVariableResponseRecieved += new EventHandler(engine_GetRoomVariableResponseRecieved); - _engine.JoinRoom += new EventHandler(engine_JoinRoom); + _engine.ServerMessageRecieved += + (o, receivedArgs) => { + if (receivedArgs != null) + EngineServerMessageRecieved(receivedArgs); + }; + + _engine.LoginResponseReceived += + (o, eventArgs) => { + if (eventArgs != null) + EngineLoginResponseReceived(eventArgs); + }; + + _engine.GetRoomVariableResponseRecieved += + (o, responseArgs) => { + if (responseArgs != null) + engine_GetRoomVariableResponseRecieved(responseArgs); + }; + + _engine.JoinRoom += (o, eventArgs) => { if (eventArgs != null) EngineJoinRoom(eventArgs); }; + + _server.ConnectionResponse += + (o, eventArgs) => { + if (eventArgs != null) + ServerConnectionResponse(eventArgs); + }; - _server.ConnectionResponse += new EventHandler(server_ConnectionResponse); _engine.AddServer(_server); Console.WriteLine("Connecting to server..."); @@ -54,14 +64,12 @@ public void Run(string[] args) _server.Connect("127.0.0.1", 4000); _connectedReceivedEvent.WaitOne(-1); - if (!_connectionSuccessful) - { - Console.WriteLine("Could not connect to server. Retrying in 5 seconds."); - Thread.Sleep(5000); - } + if (_connectionSuccessful) continue; + Console.WriteLine("Could not connect to server. Retrying in 5 seconds."); + Thread.Sleep(5000); } - bool success = false; + bool success; do { Console.Write("Enter your user name: "); @@ -127,23 +135,28 @@ public void Run(string[] args) _engine.StopEngine(); } - void server_ConnectionResponse(object sender, ConnectionEventArgs e) + void ServerConnectionResponse(ConnectionEventArgs e = null) { + if (e == null) throw new ArgumentNullException("e"); _connectionSuccessful = e.IsSuccessful; _connectedReceivedEvent.Set(); } private void Login(string userName) { - LoginRequest request = new LoginRequest(); - request.LoginName = userName; + var request = new LoginRequest {LoginName = userName}; - _server.SendRequestEncrypted(request); + _server.SendRequest(request); } private void GetRoomVariableRequest(string room, string varname) { + if( string.IsNullOrEmpty(room) || string.IsNullOrEmpty(varname)) + { + + } + //GetRoomVariableRequest grvr = new GetRoomVariableRequest(); //grvr.RoomName = room; //grvr.VariableName = varname; @@ -153,18 +166,19 @@ private void GetRoomVariableRequest(string room, string varname) private void JoinRoom(string roomName) { - CreateRoomRequest crr = new CreateRoomRequest(); + var crr = new CreateRoomRequest {RoomName = roomName}; - crr.RoomName = roomName; - _server.SendRequestEncrypted(crr); + _server.SendRequest(crr); } - void engine_JoinRoom(object sender, JoinRoomEventArgs e) + void EngineJoinRoom(JoinRoomEventArgs e = null) { - Room room = _engine.Managers.RoomManager.FindById(e.Event.RoomId); + if (e == null) throw new ArgumentNullException("e"); + + var room = _engine.Managers.RoomManager.FindById(e.Event.RoomId); Console.WriteLine("You have entered {0}.", room.Name); Console.WriteLine("Users:"); - foreach (User user in room.Users) + foreach (var user in room.Users) { Console.WriteLine("{1}{0}", user.UserName, user.IsMe ? "*" : ""); } @@ -172,49 +186,51 @@ void engine_JoinRoom(object sender, JoinRoomEventArgs e) private void CreateRoomVariable() { - //Console.Write("Room: "); - //string room = Console.ReadLine(); + ////Console.Write("Room: "); + ////string room = Console.ReadLine(); - Console.WriteLine(); - Console.Write("Name: "); - string name = Console.ReadLine(); + //Console.WriteLine(); + //Console.Write("Name: "); + //string name = Console.ReadLine(); - Console.WriteLine(); - Console.Write("Value: "); - string stringValue = Console.ReadLine(); + //Console.WriteLine(); + //Console.Write("Value: "); + //string stringValue = Console.ReadLine(); - SharedObject value = new SharedObject(); - value.SetElementValue("__default__", stringValue, SharedObjectDataType.String); + //var value = new SharedObject(); + //value.SetElementValue("__default__", stringValue, SharedObjectDataType.String); - SharedObject[] valueArray = new SharedObject[1]; - SharedObject arrayObject = new SharedObject(); - arrayObject.SetElementValue("value", 123, SharedObjectDataType.Integer); - valueArray[0] = arrayObject; + //var valueArray = new SharedObject[1]; + //var arrayObject = new SharedObject(); + //arrayObject.SetElementValue("value", 123, SharedObjectDataType.Integer); + //valueArray[0] = arrayObject; - value.SetElementValue("arrayTest", valueArray, SharedObjectDataType.BzObjectArray); + //value.SetElementValue("arrayTest", valueArray, SharedObjectDataType.BzObjectArray); - CreateRoomVariableRequest crvr = new CreateRoomVariableRequest(); + //long roomId = _engine.Managers.UserManager.Me.Room.RoomId; + //var crvr = new CreateRoomVariableRequest {Name = name, Value = value, RoomId = roomId }; //crvr.RoomId = room; get my room id - crvr.Name = name; - crvr.Value = value; - _server.SendRequestEncrypted(crvr); + //_server.SendRequestEncrypted(crvr); } - void engine_GetRoomVariableResponseRecieved(object sender, GetRoomVariableResponseArgs e) + void engine_GetRoomVariableResponseRecieved(GetRoomVariableResponseArgs e) { + if (e == null) throw new ArgumentNullException("e"); } - void engine_LoginResponseReceived(object sender, LoginResponseEventArgs e) + void EngineLoginResponseReceived(LoginResponseEventArgs e = null) { - int state = e.LoginResponse.Success ? 1 : 0; + if (e == null) throw new ArgumentNullException("e"); + var state = e.Response.Success ? 1 : 0; Interlocked.Exchange(ref _loginState, state); _loginReceievedEvent.Set(); } - void engine_ServerMessageRecieved(object sender, ServerMessageReceivedArgs e) + void EngineServerMessageRecieved(ServerMessageReceivedArgs e = null) { + if (e == null) throw new ArgumentNullException("e"); DispatchMessage(e.Message); } diff --git a/ConsoleApplication1/Properties/AssemblyInfo.cs b/ConsoleApplication1/Properties/AssemblyInfo.cs index 4eb2cd3..b4d4f93 100644 --- a/ConsoleApplication1/Properties/AssemblyInfo.cs +++ b/ConsoleApplication1/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following diff --git a/SocketServer.sln b/SocketServer.sln index 2935481..3a9de47 100644 --- a/SocketServer.sln +++ b/SocketServer.sln @@ -15,15 +15,17 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution TraceAndTestImpact.testsettings = TraceAndTestImpact.testsettings EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Framework", "SocketService.Framework\SocketService.Framework.csproj", "{A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1\ConsoleApplication1.csproj", "{0E8F0B30-5C79-47A4-9F35-932CBBEC0139}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Framework.Client", "SocketService.Framework.Client\SocketService.Framework.Client.csproj", "{93FD4F32-5214-40E3-8E36-5B4E354F10C4}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Event", "SocketService.Event\SocketService.Event.csproj", "{656E34AF-78EA-4ED0-B67C-B3EA28E002C9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Crypto", "SocketService.Framework.Crypto\SocketService.Crypto.csproj", "{4138075A-49CD-4A46-92CB-DFF64A0BB0B6}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Core", "SocketService.Core\SocketService.Core.csproj", "{A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1\ConsoleApplication1.csproj", "{0E8F0B30-5C79-47A4-9F35-932CBBEC0139}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Shared", "SocketService.Shared\SocketService.Shared.csproj", "{7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Client.Core", "SocketService.Client.Core\SocketService.Client.Core.csproj", "{93FD4F32-5214-40E3-8E36-5B4E354F10C4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Client.API", "SocketService.Client.API\SocketService.Client.API.csproj", "{5C1838A8-CD45-450F-9065-1ED7CF6557C5}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SocketService.Core.Crypto", "SocketService.Core.Crypto\SocketService.Core.Crypto.csproj", "{4138075A-49CD-4A46-92CB-DFF64A0BB0B6}" EndProject Global GlobalSection(TestCaseManagementSettings) = postSolution @@ -48,6 +50,26 @@ Global {3B89D58C-5E4E-4F7A-B256-2DE189684322}.Release|Mixed Platforms.Build.0 = Release|x86 {3B89D58C-5E4E-4F7A-B256-2DE189684322}.Release|x86.ActiveCfg = Release|x86 {3B89D58C-5E4E-4F7A-B256-2DE189684322}.Release|x86.Build.0 = Release|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Any CPU.ActiveCfg = Debug|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|x86.ActiveCfg = Debug|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|x86.Build.0 = Debug|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Any CPU.ActiveCfg = Release|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Mixed Platforms.Build.0 = Release|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|x86.ActiveCfg = Release|x86 + {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|x86.Build.0 = Release|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Debug|Any CPU.ActiveCfg = Debug|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Debug|x86.ActiveCfg = Debug|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Debug|x86.Build.0 = Debug|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Release|Any CPU.ActiveCfg = Release|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Release|Mixed Platforms.Build.0 = Release|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Release|x86.ActiveCfg = Release|x86 + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9}.Release|x86.Build.0 = Release|x86 {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Debug|Any CPU.Build.0 = Debug|Any CPU {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -58,6 +80,16 @@ Global {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B}.Release|x86.ActiveCfg = Release|Any CPU + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Debug|Any CPU.ActiveCfg = Debug|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Debug|Mixed Platforms.Build.0 = Debug|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Debug|x86.ActiveCfg = Debug|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Debug|x86.Build.0 = Debug|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Release|Any CPU.ActiveCfg = Release|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Release|Mixed Platforms.ActiveCfg = Release|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Release|Mixed Platforms.Build.0 = Release|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Release|x86.ActiveCfg = Release|x86 + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1}.Release|x86.Build.0 = Release|x86 {93FD4F32-5214-40E3-8E36-5B4E354F10C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {93FD4F32-5214-40E3-8E36-5B4E354F10C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {93FD4F32-5214-40E3-8E36-5B4E354F10C4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -78,26 +110,6 @@ Global {4138075A-49CD-4A46-92CB-DFF64A0BB0B6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {4138075A-49CD-4A46-92CB-DFF64A0BB0B6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {4138075A-49CD-4A46-92CB-DFF64A0BB0B6}.Release|x86.ActiveCfg = Release|Any CPU - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Any CPU.ActiveCfg = Debug|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|Mixed Platforms.Build.0 = Debug|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|x86.ActiveCfg = Debug|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Debug|x86.Build.0 = Debug|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Any CPU.ActiveCfg = Release|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Mixed Platforms.ActiveCfg = Release|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|Mixed Platforms.Build.0 = Release|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|x86.ActiveCfg = Release|x86 - {0E8F0B30-5C79-47A4-9F35-932CBBEC0139}.Release|x86.Build.0 = Release|x86 - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Debug|x86.ActiveCfg = Debug|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Release|Any CPU.Build.0 = Release|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {5C1838A8-CD45-450F-9065-1ED7CF6557C5}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/SocketService.Client.API/ClientEngine.cs b/SocketService.Client.API/ClientEngine.cs deleted file mode 100644 index 5214336..0000000 --- a/SocketService.Client.API/ClientEngine.cs +++ /dev/null @@ -1,194 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Crypto; -using SocketService.Framework.Client.Sockets; -using SocketService.Framework.Client.Response; -using System.Net.Sockets; -using System.Threading; -using SocketService.Framework.Client.Serialize; -using System.Collections; -using SocketService.Framework.Request; -using SocketService.Framework.SharedObjects; -using SocketService.Framework.Client.Event; -using SocketService.Client.API.Event; -using SocketService.Client.API.Manager; - -namespace SocketService.Client.API -{ - public class ClientEngine - { - public event EventHandler ServerMessageRecieved; - public event EventHandler LoginResponseReceived; - public event EventHandler GetRoomVariableResponseRecieved; - public event EventHandler JoinRoom; - public event EventHandler RoomUserUpdate; - public event EventHandler LeaveRoom; - public event EventHandler RoomVariableUpdate; - - private readonly List _servers = new List(); - - public ClientEngine() - { - Managers = new ManagerHelper(this); - } - - public ManagerHelper Managers - { - get; - private set; - } - - public void AddServer(Server server) - { - lock (_servers) - { _servers.Add(server); } - - server.ServerEvent += new EventHandler(server_ServerEvent); - server.ServerResponse += new EventHandler(server_ServerResponse); - - } - - public void StopEngine() - { - lock (_servers) - { - foreach (Server server in _servers) - { - server.Disconnect(); - } - } - } - - protected void server_ServerResponse(object sender, ServerResponseEventArgs e) - { - HandleServerResponse(e.Response); - } - - protected void server_ServerEvent(object sender, ServerEventEventArgs e) - { - HandleEvent(e.ServerEvent); - } - - private void HandleServerResponse(IResponse response) - { - if( response is GetRoomVariableResponse) - { - OnGetRoomVariableResponseRecieved( - new GetRoomVariableResponseArgs() - { - Response = response as GetRoomVariableResponse - } - ); - } - else if (response is LoginResponse) - { - OnLoginResponseReceieved( - new LoginResponseEventArgs() - { - LoginResponse = response as LoginResponse - } - ); - } - } - - private void HandleEvent(IEvent evt) - { - if (evt is JoinRoomEvent) - { - OnJoinRoomEvent( - new JoinRoomEventArgs() - { - Event = evt as JoinRoomEvent - } - ); - } - else if (evt is RoomUserUpdateEvent) - { - OnRoomUserUpdate( - new RoomUserUpdateEventArgs() - { - Event = evt as RoomUserUpdateEvent - } - ); - } - else if (evt is RoomVariableUpdateEvent) - { - OnRoomVariableUpdate( - new RoomVariableUpdateArgs() - { - Event = evt as RoomVariableUpdateEvent - } - ); - - } - } - - protected virtual void OnRoomVariableUpdate(RoomVariableUpdateArgs args) - { - var func = RoomVariableUpdate; - if (func != null) - { - func(this, args); - } - } - - protected virtual void OnLeaveRoom(LeaveRoomEventArgs args) - { - var func = LeaveRoom; - if (func != null) - { - func(this, args); - } - } - - - protected virtual void OnRoomUserUpdate(RoomUserUpdateEventArgs args) - { - var func = RoomUserUpdate; - if (func != null) - { - func(this, args); - } - } - - protected virtual void OnGetRoomVariableResponseRecieved(GetRoomVariableResponseArgs args) - { - var func = GetRoomVariableResponseRecieved; - if (func != null) - { - func(this, args); - } - } - - protected virtual void OnServerMessageReceived(ServerMessageReceivedArgs args) - { - var func = ServerMessageRecieved; - if (func != null) - { - func(this, args); - } - } - - protected virtual void OnLoginResponseReceieved(LoginResponseEventArgs args) - { - var func = LoginResponseReceived; - if (func != null) - { - func(this, args); - } - } - - protected virtual void OnJoinRoomEvent(JoinRoomEventArgs args) - { - var func = JoinRoom; - if (func != null) - { - func(this, args); - } - - } - - } -} diff --git a/SocketService.Client.API/Command/CommandQueue.cs b/SocketService.Client.API/Command/CommandQueue.cs deleted file mode 100644 index e3fc7ff..0000000 --- a/SocketService.Client.API/Command/CommandQueue.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; - -namespace SocketService.Client.API.Command -{ - class CommandQueue - { - private long _running; - - private ManualResetEvent _stopEvent = new ManualResetEvent(false); - private object _queueLock = new object(); - private Queue _commandQueue = new Queue(); - - /// - /// Starts this instance. - /// - public void Start() - { - if (Interlocked.Read(ref _running) == 0) - { - _stopEvent.Reset(); - Interlocked.Exchange(ref _running, 1); - - int numProcessors = System.Environment.ProcessorCount; - double numThreadsPerProcessor = 1.5; - int numThreads = (int)((double)numProcessors * numThreadsPerProcessor) + 1; - - for (int i = 0; i < numThreads; i++) - { - Thread serverThread = new Thread(new ThreadStart(CommandThread)); - serverThread.Start(); - } - } - } - - /// - /// Stops this instance. - /// - public void Stop() - { - _stopEvent.Set(); - Interlocked.Exchange(ref _running, 0); - } - - protected virtual void CommandThread() - { - while (_stopEvent.WaitOne(100)) - { - ICommand command = NextCommand(); - if (command != null) - { - // execute the command - command.Execute(); - } - } - } - - private ICommand NextCommand() - { - lock (_queueLock) - { - if (_commandQueue.Count > 0) - { - return _commandQueue.Dequeue(); - } - } - - return null; - } - - } -} diff --git a/SocketService.Client.API/Command/ICommand.cs b/SocketService.Client.API/Command/ICommand.cs deleted file mode 100644 index 3d236a3..0000000 --- a/SocketService.Client.API/Command/ICommand.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Command -{ - interface ICommand - { - void Execute(); - } -} diff --git a/SocketService.Client.API/Command/ProcessInboundMessageCommand.cs b/SocketService.Client.API/Command/ProcessInboundMessageCommand.cs deleted file mode 100644 index 64cc5fd..0000000 --- a/SocketService.Client.API/Command/ProcessInboundMessageCommand.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Command -{ - class ProcessInboundMessageCommand : ICommand - { - private readonly object _message; - public ProcessInboundMessageCommand(object message) - { - _message = message; - } - - public void Execute() - { - } - } -} diff --git a/SocketService.Client.API/Data/Room.cs b/SocketService.Client.API/Data/Room.cs deleted file mode 100644 index 44955dc..0000000 --- a/SocketService.Client.API/Data/Room.cs +++ /dev/null @@ -1,179 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Client.API.Data -{ - public class Room - { - private readonly List _userList = new List(); - private readonly Dictionary _roomVariableList = new Dictionary(); - - private static long _nextId = 0; - - public Room(long id) - { - RoomId = id; - } - - public Room() : this(NextId()) - { - } - - private static long NextId() - { - return _nextId++; - } - - public long RoomId - { - get; - private set; - } - - public string Name - { - get; - set; - } - - public string Description - { - get; - set; - } - - public int Capacity - { - get; - set; - } - - public bool IsProtected - { - get; - set; - } - - public bool IsHidden - { - get; - set; - } - - public void AddUser(User user) - { - //User u = UserByName(user.UserName); - - //if (u == null) - //{ - Monitor.Enter(this); - try - { - _userList.Add(user); - } - finally - { - Monitor.Exit(this); - } - //} - } - - public void RemoveUser(User user) - { - //User user = UserByName(userName); - //if (user != null) - //{ - Monitor.Enter(this); - try - { - _userList.Remove(user); - } - finally - { - Monitor.Exit(this); - } - //} - } - - //public User UserByName(string userName) - //{ - // Monitor.Enter(this); - // try - // { - // var query = from u in _userList - // where u.UserName.Equals(userName) - // select u; - - // return query.FirstOrDefault(); - // } - // finally - // { - // Monitor.Exit(this); - // } - - //} - - public void AddRoomVariable(String Name, SharedObject Value) - { - Monitor.Enter(this); - try - { - _roomVariableList.Add(Name, Value); - } - finally - { - Monitor.Exit(this); - } - } - - public List Users - { - get - { - Monitor.Enter(this); - try - { - return _userList.ToList(); - } - finally - { - Monitor.Exit(this); - } - } - } - - public void RemoveVariable(string Name) - { - Monitor.Enter(this); - try - { - if( _roomVariableList.ContainsKey(Name)) - _roomVariableList.Remove(Name); - } - finally - { - Monitor.Exit(this); - } - } - - public void UpdateVariable(string Name, SharedObject Value) - { - Monitor.Enter(this); - try - { - if (_roomVariableList.ContainsKey(Name)) - _roomVariableList.Remove(Name); - - _roomVariableList.Add(Name, Value); - } - finally - { - Monitor.Exit(this); - } - } - } -} diff --git a/SocketService.Client.API/Data/User.cs b/SocketService.Client.API/Data/User.cs deleted file mode 100644 index 42338d1..0000000 --- a/SocketService.Client.API/Data/User.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Data -{ - public class User - { - public string UserName - { - get; - set; - } - - public bool IsMe - { - get; - set; - } - - - public Room Room { get; set; } - } -} diff --git a/SocketService.Client.API/Event/ConnectionEventArgs.cs b/SocketService.Client.API/Event/ConnectionEventArgs.cs deleted file mode 100644 index 8c8a6e0..0000000 --- a/SocketService.Client.API/Event/ConnectionEventArgs.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Event -{ - public class ConnectionEventArgs : EventArgs - { - public bool IsSuccessful - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/Event/GetRoomVariableResponseArgs.cs b/SocketService.Client.API/Event/GetRoomVariableResponseArgs.cs deleted file mode 100644 index ef2c789..0000000 --- a/SocketService.Client.API/Event/GetRoomVariableResponseArgs.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Response; - -namespace SocketService.Client.API.Event -{ - public class GetRoomVariableResponseArgs : EventArgs - { - public GetRoomVariableResponse Response - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/Event/JoinRoomEventArgs.cs b/SocketService.Client.API/Event/JoinRoomEventArgs.cs deleted file mode 100644 index a96db83..0000000 --- a/SocketService.Client.API/Event/JoinRoomEventArgs.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Event; - -namespace SocketService.Client.API.Event -{ - public class JoinRoomEventArgs : EventArgs - { - public JoinRoomEvent Event - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/Event/LeaveRoomEventArgs.cs b/SocketService.Client.API/Event/LeaveRoomEventArgs.cs deleted file mode 100644 index 29126dc..0000000 --- a/SocketService.Client.API/Event/LeaveRoomEventArgs.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Event -{ - public class LeaveRoomEventArgs : EventArgs - { - public int RoomId - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/Event/LoginResponseEventArgs.cs b/SocketService.Client.API/Event/LoginResponseEventArgs.cs deleted file mode 100644 index e05ae2c..0000000 --- a/SocketService.Client.API/Event/LoginResponseEventArgs.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Response; - -namespace SocketService.Client.API.Event -{ - public class LoginResponseEventArgs : EventArgs - { - public LoginResponse LoginResponse - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/Event/RoomUserUpdateEventArgs.cs b/SocketService.Client.API/Event/RoomUserUpdateEventArgs.cs deleted file mode 100644 index 219b195..0000000 --- a/SocketService.Client.API/Event/RoomUserUpdateEventArgs.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Event; - -namespace SocketService.Client.API.Event -{ - public class RoomUserUpdateEventArgs : EventArgs - { - public RoomUserUpdateEvent Event - { - get; - set; - } - - //public int RoomId - //{ - // get; - // set; - //} - - //public string UserName - //{ - // get; - // set; - //} - - //public RoomUserUpdateAction Action - //{ - // get; - // set; - //} - } -} diff --git a/SocketService.Client.API/Event/ServerEventEventArgs.cs b/SocketService.Client.API/Event/ServerEventEventArgs.cs deleted file mode 100644 index b072fee..0000000 --- a/SocketService.Client.API/Event/ServerEventEventArgs.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Event; - -namespace SocketService.Client.API.Event -{ - public class ServerEventEventArgs : EventArgs - { - public IEvent ServerEvent - { - get; - set; - } - - } -} diff --git a/SocketService.Client.API/Event/ServerMessageReceivedArgs.cs b/SocketService.Client.API/Event/ServerMessageReceivedArgs.cs deleted file mode 100644 index 964d0a9..0000000 --- a/SocketService.Client.API/Event/ServerMessageReceivedArgs.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Client.API.Event -{ - public class ServerMessageReceivedArgs : EventArgs - { - public string Message - { - get; - set; - } - - } -} diff --git a/SocketService.Client.API/Event/ServerResponseEventArgs.cs b/SocketService.Client.API/Event/ServerResponseEventArgs.cs deleted file mode 100644 index 4f98e13..0000000 --- a/SocketService.Client.API/Event/ServerResponseEventArgs.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Response; - -namespace SocketService.Client.API.Event -{ - public class ServerResponseEventArgs : EventArgs - { - public IResponse Response - { - get; - set; - } - } -} diff --git a/SocketService.Client.API/ListUsersInRoomResponseArgs.cs b/SocketService.Client.API/ListUsersInRoomResponseArgs.cs deleted file mode 100644 index 97b0fb2..0000000 --- a/SocketService.Client.API/ListUsersInRoomResponseArgs.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Response; - -namespace SocketService.Client.API -{ - public class ListUsersInRoomResponseArgs : EventArgs - { - public ListUsersInRoomResponse Response - { - get; - set; - } - - } -} diff --git a/SocketService.Client.API/Manager/ManagerHelper.cs b/SocketService.Client.API/Manager/ManagerHelper.cs deleted file mode 100644 index 5cf36c9..0000000 --- a/SocketService.Client.API/Manager/ManagerHelper.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Event; -using SocketService.Framework.SharedObjects; -using SocketService.Framework.Client.Response; -using SocketService.Client.API.Event; -using SocketService.Client.API.Data; - -namespace SocketService.Client.API.Manager -{ - public class ManagerHelper - { - private ClientEngine _engine; - public ManagerHelper(ClientEngine engine) - { - this.RoomManager = new RoomManager(); - this.UserManager = new UserManager(); - - _engine = engine; - - _engine.RoomUserUpdate += new EventHandler(engine_RoomUserUpdate); - _engine.JoinRoom += new EventHandler(engine_JoinRoom); - _engine.LoginResponseReceived += new EventHandler(engine_LoginResponseReceived); - _engine.RoomVariableUpdate += new EventHandler(engine_RoomVariableUpdate); - _engine.LeaveRoom += new EventHandler(engine_LeaveRoom); - } - - void engine_LeaveRoom(object sender, LeaveRoomEventArgs e) - { - this.RoomManager.RemoveRoom(e.RoomId); - } - - void engine_RoomVariableUpdate(object sender, RoomVariableUpdateArgs e) - { - switch (e.Event.Action) - { - case RoomVariableUpdateAction.Add: - RoomManager.AddRoomVariable(e.Event.RoomId, e.Event.Name, e.Event.Value); - break; - - case RoomVariableUpdateAction.Delete: - RoomManager.DeleteRoomVariable(e.Event.RoomId, e.Event.Name); - break; - - case RoomVariableUpdateAction.Update: - RoomManager.UpdateRoomVariable(e.Event.RoomId, e.Event.Name, e.Event.Value); - break; - } - } - - void engine_LoginResponseReceived(object sender, LoginResponseEventArgs e) - { - LoginResponse loginResponse = e.LoginResponse; - if (loginResponse.Success) - { - User user = new User(); - user.IsMe = true; - user.UserName = loginResponse.UserName; - - //foreach (string current in loginResponse.UserVariables.Keys) - //{ - // EsObject value = loginResponse.UserVariables[current] as EsObject; - // user.AddUserVariable(new UserVariable - // { - // Name = current, - // Value = value - // }); - //} - this.UserManager.AddUser(user); - this.UserManager.Me = user; - } - } - - void engine_JoinRoom(object sender, JoinRoomEventArgs e) - { - JoinRoomEvent joinRoomEvent = e.Event; - Room room = this.RoomManager.FindById(joinRoomEvent.RoomId); - if (room == null) - { - room = new Room(joinRoomEvent.RoomId); - room.Name = joinRoomEvent.RoomName; - RoomManager.AddRoom(room); - } - - room.Description = joinRoomEvent.RoomDescription; - room.IsProtected = joinRoomEvent.Protected; - room.Capacity = joinRoomEvent.Capacity; - room.IsHidden = joinRoomEvent.Hidden; - - //foreach (SharedObject roomVariable in joinRoomEvent.RoomVariables) - //{ - // room.AddRoomVariable(roomVariable.Name, roomVariable); - //} - - foreach (UserListEntry userListEntry in joinRoomEvent.Users) - { - User u = this.UserManager.AddUser(this.UserListEntryToUser(userListEntry)); - room.AddUser(u); - } - - this.UserManager.Me.Room = room; - } - - private User UserListEntryToUser(UserListEntry entry) - { - return new User - { - UserName = entry.UserName, - IsMe = false - }; - } - - void engine_RoomUserUpdate(object sender, RoomUserUpdateEventArgs e) - { - RoomUserUpdateEvent roomUserUpdateEvent = e.Event; - - User user = this.UserManager.FindByName(roomUserUpdateEvent.UserName); - Room room = this.RoomManager.FindById(roomUserUpdateEvent.RoomId); - if (user == null) - { - user = new User(); - user.UserName = roomUserUpdateEvent.UserName; - //foreach (UserVariable current in roomUserUpdateEvent.UserVariables) - //{ - // user.AddUserVariable(current); - //} - } - - switch (roomUserUpdateEvent.Action) - { - case RoomUserUpdateAction.AddUser: - user = this.UserManager.AddUser(user); - room.AddUser(user); - break; - case RoomUserUpdateAction.DeleteUser: - this.UserManager.RemoveUser(user.UserName); - room.RemoveUser(user); - break; - } - } - - public RoomManager RoomManager - { - get; - private set; - } - - public UserManager UserManager - { - get; - private set; - } - - } -} diff --git a/SocketService.Client.API/Manager/RoomManager.cs b/SocketService.Client.API/Manager/RoomManager.cs deleted file mode 100644 index 92036ce..0000000 --- a/SocketService.Client.API/Manager/RoomManager.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using SocketService.Client.API.Data; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Client.API.Manager -{ - public class RoomManager - { - private readonly List _roomList = new List(); - public RoomManager() - { - } - - public Room FindById(long roomId) - { - Monitor.Enter(this); - try - { - var query = from r in _roomList - where r.RoomId.Equals(roomId) - select r; - - return query.FirstOrDefault(); - } - finally - { - Monitor.Exit(this); - } - } - - public void AddRoom(Room room) - { - Monitor.Enter(this); - try - { - _roomList.Add(room); - } - finally - { - Monitor.Exit(this); - } - } - - public void AddRoomVariable(long RoomId, string Name, SharedObject Value) - { - Room room = FindById(RoomId); - if (room != null) - { - room.AddRoomVariable(Name, Value); - } - } - - public void DeleteRoomVariable(long RoomId, string Name) - { - Room room = FindById(RoomId); - if ( room != null ) - { - room.RemoveVariable(Name); - } - } - - public void UpdateRoomVariable(long RoomId, string Name, SharedObject Value) - { - Room room = FindById(RoomId); - if (room != null) - { - room.UpdateVariable(Name, Value); - } - } - - public void RemoveRoom(long Id) - { - Room room = FindById(Id); - if (room != null) - { - lock (_roomList) - { - _roomList.Remove(room); - } - } - } - } -} diff --git a/SocketService.Client.API/Manager/UserManager.cs b/SocketService.Client.API/Manager/UserManager.cs deleted file mode 100644 index 73d4939..0000000 --- a/SocketService.Client.API/Manager/UserManager.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using SocketService.Client.API.Data; - -namespace SocketService.Client.API.Manager -{ - public class UserManager - { - private readonly List _userList = new List(); - - public User Me - { - get; - set; - } - - public User AddUser(User user) - { - User u = FindByName(user.UserName); - if (u == null) - { - Monitor.Enter(this); - try - { - _userList.Add(user); - } - finally - { - Monitor.Exit(this); - } - } - else - { - return user = u; - } - - return user; - } - - public User FindByName(string name) - { - Monitor.Enter(this); - try - { - var query = from u in _userList - where u.UserName.Equals(name) - select u; - - return query.FirstOrDefault(); - } - finally - { - Monitor.Exit(this); - } - } - - - - public void RemoveUser(string userName) - { - User user = FindByName(userName); - if (user != null) - { - Monitor.Enter(this); - try - { - _userList.Remove(user); - } - finally - { - Monitor.Exit(this); - } - } - } - } -} diff --git a/SocketService.Client.API/Properties/AssemblyInfo.cs b/SocketService.Client.API/Properties/AssemblyInfo.cs deleted file mode 100644 index 2856dc0..0000000 --- a/SocketService.Client.API/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SocketService.Client.API")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SocketService.Client.API")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("5832abd9-65f1-4234-a108-e27178a9ccee")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketService.Client.API/RoomVariableUpdateArgs.cs b/SocketService.Client.API/RoomVariableUpdateArgs.cs deleted file mode 100644 index ce89859..0000000 --- a/SocketService.Client.API/RoomVariableUpdateArgs.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Event; - -namespace SocketService.Client.API -{ - public class RoomVariableUpdateArgs : EventArgs - { - public RoomVariableUpdateEvent Event { get; set; } - } -} diff --git a/SocketService.Client.API/Server.cs b/SocketService.Client.API/Server.cs deleted file mode 100644 index 828f4f8..0000000 --- a/SocketService.Client.API/Server.cs +++ /dev/null @@ -1,337 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Client.API.Manager; -using System.Net; -using System.Threading; -using System.Collections; -using System.Net.Sockets; -using SocketService.Crypto; -using SocketService.Framework.Client.Sockets; -using SocketService.Framework.Request; -using SocketService.Framework.Client.Serialize; -using SocketService.Framework.Client.Response; -using SocketService.Client.API.Event; -using SocketService.Framework.Client.Event; - -namespace SocketService.Client.API -{ - public class Server - { - private ManualResetEvent _serverDisconnectedEvent = new ManualResetEvent(false); - private DiffieHellmanKey _remotePublicKey; - private DiffieHellmanProvider _provider; - private ZipSocket socket; - private bool _connected = false; - - public event EventHandler ConnectionResponse; - public event EventHandler ServerResponse; - public event EventHandler ServerEvent; - - public Server() - { - } - - public void Disconnect() - { - _serverDisconnectedEvent.Set(); - _connected = false; - } - - public void Connect(string address, int port) - { - if (!_connected) - { - Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - _serverDisconnectedEvent.Reset(); - - bool connected = false; - while (!connected) - { - try - { - rawSocket.Connect(address, port); - connected = true; - } - catch (SocketException ex) - { - OnConnectionResponse(new ConnectionEventArgs() { IsSuccessful = false }); - return; - } - } - - // wrap the socket - socket = new ZipSocket(rawSocket, Guid.NewGuid()); - NegotiateKeys(); - - OnConnectionResponse(new ConnectionEventArgs() { IsSuccessful = true }); - _connected = true; - - Thread serverThread = new Thread(new ThreadStart(PumpMessages)); - serverThread.Start(); - } - - } - - //public void Connect(IPEndPoint endpoint) - //{ - // Connect(endpoint.Address, endpoint.Port); - //} - - //public void Connect(string address, int port) - //{ - // IPHostEntry hostEntry = Dns.GetHostEntry(address); - // if (hostEntry != null && hostEntry.AddressList.Length > 0) - // { - // IPAddress addr = hostEntry.AddressList[0]; - // Connect(addr, port); - // } - //} - - protected virtual void OnConnectionResponse(ConnectionEventArgs args) - { - var func = ConnectionResponse; - if (func != null) - { - func(this, args); - } - - } - - //public ClientEngine Engine - //{ - // get; - // private set; - //} - - //public ManagerHelper Managers - //{ - // get; - // private set; - //} - - //protected virtual void ServerThread() - //{ - // //// TODO: read info from configuration - // //Socket rawSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - - // //bool connected = false; - // //while (!connected) - // //{ - // // try - // // { - // // rawSocket.Connect("127.0.0.1", 4000); - // // connected = true; - // // } - // // catch (SocketException) - // // { - // // OnConnectionResponse(new ConnectionResponseEventArgs() { IsSuccessful = false }); - // // return; - // // } - // //} - - // //// wrap the socket - // //socket = new ZipSocket(rawSocket, Guid.NewGuid()); - // //NegotiateKeys(); - - // //OnConnectionResponse(new ConnectionResponseEventArgs() { IsSuccessful = true }); - // //_connected = true; - - // ////Thread messageThread = new Thread(new ThreadStart(PumpMessages)); - // ////messageThread.Start(); - // //PumpMessages(); - //} - - protected void PumpMessages() - { - bool serverDown = false; - - while (!serverDown && !_serverDisconnectedEvent.WaitOne(0)) - { - IList readList = new List() { socket.RawSocket }; - - // now let's wait for messages - Socket.Select(readList, null, null, 100); - - object message = null; - - // there is only one socket in the poll list - // so if the count is greater than 0 then - // the only one available should be the client socket - if (readList.Count > 0) - { - // if socket is selected, and if available byes is 0, - // then socket has been closed - serverDown = socket.RawSocket.Available == 0; - if (!serverDown) - { - byte[] objectData = socket.ReceiveData(); - - // it should be a server message, we can look - // at other message types later - message = ObjectSerialize.Deserialize(objectData); - - DispatchMessage(message); - } - - } - } - - _serverDisconnectedEvent.Set(); - } - - private void DispatchMessage(object message) - { - if (message is IResponse) - { - OnServerResponse(new ServerResponseEventArgs() { Response = message as IResponse }); - } - else if (message is IEvent) - { - OnServerEvent(new ServerEventEventArgs() { ServerEvent = message as IEvent }); - } - else - { - // TODO: Handle unknown message types - this might be hacking attempts - } - - } - - protected void OnServerEvent(ServerEventEventArgs args) - { - var func = ServerEvent; - if (func != null) - { - func(this, args); - } - } - - protected void OnServerResponse(ServerResponseEventArgs args) - { - var func = ServerResponse; - if (func != null) - { - func(this, args); - } - } - - private void NegotiateKeys() - { - SendRequest(new GetCentralAuthorityRequest()); - - bool doneHandshaking = false; - int step = 0; - - // wait for central authority - IList readList = new List() { socket.RawSocket }; - while (!doneHandshaking) - { - Socket.Select(readList, null, null, -1); - - // there is only one socket in the poll list - // so if the count is greater than 0 then - // the only one available should be the client socket - if (readList.Count > 0) - { - int availableBytes = socket.RawSocket.Available; - if (availableBytes > 0) - { - byte[] objectData = socket.ReceiveData(); - switch (step) - { - case 0: - CentralAuthority ca = ObjectSerialize.Deserialize(objectData); - if (ca != null) - { - _provider = ca.GetProvider(); - - // Send Negotiate Key Command - // Read Response when it comes back - SendRequest(new NegotiateKeysRequest(_provider.PublicKey.ToByteArray())); - - step++; - } - break; - - case 1: - // record server key - NegotiateKeysResponse response = ObjectSerialize.Deserialize(objectData); - if (response != null) - { - _remotePublicKey = _provider.Import(response.RemotePublicKey); - doneHandshaking = true; - } - break; - - } - } - } - } - } - - public void SendRequest(object requestData) - { - socket.SendData(CreateRequest(requestData, false)); - } - - public void SendRequestEncrypted(object requestData) - { - socket.SendData(CreateRequest(requestData, true)); - } - - - private byte[] CreateRequest(object requestData, bool encrypt) - { - if (encrypt) - { - using (Wrapper cryptoWrapper = - Wrapper.CreateEncryptor(AlgorithmType.TripleDES, - _provider.CreatePrivateKey(_remotePublicKey).ToByteArray())) - { - return ObjectSerialize.Serialize( - new ClientRequest(cryptoWrapper.IV, - EncryptionType.TripleDES, - DateTime.Now, 0, - cryptoWrapper.Encrypt(ObjectSerialize.Serialize(requestData)) - ) - ); - } - } - else - { - return ObjectSerialize.Serialize( - new ClientRequest(new byte[0] { }, - EncryptionType.None, - DateTime.Now, 0, - ObjectSerialize.Serialize(requestData) - ) - ); - } - } - //private IRequest CreateRequest(EncryptionType encryptionType, object requestData) - //{ - // if (encryptionType != EncryptionType.None) - // { - // using (Wrapper cryptoWrapper = - // Wrapper.CreateEncryptor(AlgorithmType.TripleDES, - // _provider.CreatePrivateKey(_remotePublicKey).ToByteArray())) - // { - // return new ClientRequest(cryptoWrapper.IV, - // EncryptionType.TripleDES, - // DateTime.Now, 0, - // cryptoWrapper.Encrypt(ObjectSerialize.Serialize(requestData))); - // } - // } - // else - // { - // return new ClientRequest(new byte[0] { }, - // EncryptionType.None, - // DateTime.Now, 0, - // ObjectSerialize.Serialize(requestData)); - // } - //} - - - } -} diff --git a/SocketService.Client.API/SocketService.Client.API.csproj b/SocketService.Client.API/SocketService.Client.API.csproj deleted file mode 100644 index 870faed..0000000 --- a/SocketService.Client.API/SocketService.Client.API.csproj +++ /dev/null @@ -1,80 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {5C1838A8-CD45-450F-9065-1ED7CF6557C5} - Library - Properties - SocketService.Client.API - SocketService.Client.API - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {93FD4F32-5214-40E3-8E36-5B4E354F10C4} - SocketService.Framework.Client - - - {4138075A-49CD-4A46-92CB-DFF64A0BB0B6} - SocketService.Crypto - - - - - \ No newline at end of file diff --git a/SocketService.Framework.Client/API/IPlugin.cs b/SocketService.Framework.Client/API/IPlugin.cs deleted file mode 100644 index 7886b3b..0000000 --- a/SocketService.Framework.Client/API/IPlugin.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.API -{ - public interface IPlugin - { - ChainAction UserSendPublicMessage(UserPublicMessageContext context); - } - - public enum ChainAction - { - Fail, - Continue, - Stop, - NoAction - } -} diff --git a/SocketService.Framework.Client/API/PluginBase.cs b/SocketService.Framework.Client/API/PluginBase.cs deleted file mode 100644 index 80d0d5c..0000000 --- a/SocketService.Framework.Client/API/PluginBase.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; - -namespace SocketService.Framework.Client.API -{ - [InheritedExport(typeof(IPlugin))] - public class PluginBase : IPlugin - { - public virtual ChainAction UserSendPublicMessage(UserPublicMessageContext context) - { - return ChainAction.NoAction; - } - } -} diff --git a/SocketService.Framework.Client/API/UserPublicMessageContext.cs b/SocketService.Framework.Client/API/UserPublicMessageContext.cs deleted file mode 100644 index 5c5539d..0000000 --- a/SocketService.Framework.Client/API/UserPublicMessageContext.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.API -{ - public class UserPublicMessageContext - { - public string Zone - { - get; - set; - } - - public string User - { - get; - set; - } - - public string Room - { - get; - set; - } - - public string Message - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Composition/IPluginMetaData.cs b/SocketService.Framework.Client/Composition/IPluginMetaData.cs deleted file mode 100644 index 40d053c..0000000 --- a/SocketService.Framework.Client/Composition/IPluginMetaData.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Composition -{ - public interface IPluginMetaData - { - } -} diff --git a/SocketService.Framework.Client/Composition/PluginMetaDataAttribute.cs b/SocketService.Framework.Client/Composition/PluginMetaDataAttribute.cs deleted file mode 100644 index 3594096..0000000 --- a/SocketService.Framework.Client/Composition/PluginMetaDataAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; - -namespace SocketService.Framework.Client.Composition -{ - [MetadataAttribute] - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] - public class PluginMetaDataAttribute : ExportAttribute, IPluginMetaData - { - } -} diff --git a/SocketService.Framework.Client/Crypto/BigInteger.cs b/SocketService.Framework.Client/Crypto/BigInteger.cs deleted file mode 100644 index 93ce3a7..0000000 --- a/SocketService.Framework.Client/Crypto/BigInteger.cs +++ /dev/null @@ -1,3035 +0,0 @@ -//************************************************************************************ -// BigInteger Class Version 1.03 -// -// Copyright (c) 2002 Chew Keong TAN -// All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, and/or sell copies of the Software, and to permit persons -// to whom the Software is furnished to do so, provided that the above -// copyright notice(s) and this permission notice appear in all copies of -// the Software and that both the above copyright notice(s) and this -// permission notice appear in supporting documentation. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -// OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -// HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL -// INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING -// FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION -// WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -// -// -// Disclaimer -// ---------- -// Although reasonable care has been taken to ensure the correctness of this -// implementation, this code should never be used in any application without -// proper verification and testing. I disclaim all liability and responsibility -// to any person or entity with respect to any loss or damage caused, or alleged -// to be caused, directly or indirectly, by the use of this BigInteger class. -// -// Comments, bugs and suggestions to -// (http://www.codeproject.com/csharp/biginteger.asp) -// -// -// Overloaded Operators +, -, *, /, %, >>, <<, ==, !=, >, <, >=, <=, &, |, ^, ++, --, ~ -// -// Features -// -------- -// 1) Arithmetic operations involving large signed integers (2's complement). -// 2) Primality test using Fermat little theorm, Rabin Miller's method, -// Solovay Strassen's method and Lucas strong pseudoprime. -// 3) Modulo exponential with Barrett's reduction. -// 4) Inverse modulo. -// 5) Pseudo prime generation. -// 6) Co-prime generation. -// -// -// Known Problem -// ------------- -// This pseudoprime passes my implementation of -// primality test but failed in JDK's isProbablePrime test. -// -// byte[] pseudoPrime1 = { (byte)0x00, -// (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A, -// (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C, -// (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3, -// (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41, -// (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56, -// (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE, -// (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41, -// (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA, -// (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF, -// (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D, -// (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3, -// }; -// -// -// Change Log -// ---------- -// 1) September 23, 2002 (Version 1.03) -// - Fixed operator- to give correct data length. -// - Added Lucas sequence generation. -// - Added Strong Lucas Primality test. -// - Added integer square root method. -// - Added setBit/unsetBit methods. -// - New isProbablePrime() method which do not require the -// confident parameter. -// -// 2) August 29, 2002 (Version 1.02) -// - Fixed bug in the exponentiation of negative numbers. -// - Faster modular exponentiation using Barrett reduction. -// - Added getBytes() method. -// - Fixed bug in ToHexString method. -// - Added overloading of ^ operator. -// - Faster computation of Jacobi symbol. -// -// 3) August 19, 2002 (Version 1.01) -// - Big integer is stored and manipulated as unsigned integers (4 bytes) instead of -// individual bytes this gives significant performance improvement. -// - Updated Fermat's Little Theorem test to use a^(p-1) mod p = 1 -// - Added isProbablePrime method. -// - Updated documentation. -// -// 4) August 9, 2002 (Version 1.0) -// - Initial Release. -// -// -// References -// [1] D. E. Knuth, "Seminumerical Algorithms", The Art of Computer Programming Vol. 2, -// 3rd Edition, Addison-Wesley, 1998. -// -// [2] K. H. Rosen, "Elementary Number Theory and Its Applications", 3rd Ed, -// Addison-Wesley, 1993. -// -// [3] B. Schneier, "Applied Cryptography", 2nd Ed, John Wiley & Sons, 1996. -// -// [4] A. Menezes, P. van Oorschot, and S. Vanstone, "Handbook of Applied Cryptography", -// CRC Press, 1996, www.cacr.math.uwaterloo.ca/hac -// -// [5] A. Bosselaers, R. Govaerts, and J. Vandewalle, "Comparison of Three Modular -// Reduction Functions," Proc. CRYPTO'93, pp.175-186. -// -// [6] R. Baillie and S. S. Wagstaff Jr, "Lucas Pseudoprimes", Mathematics of Computation, -// Vol. 35, No. 152, Oct 1980, pp. 1391-1417. -// -// [7] H. C. Williams, "Édouard Lucas and Primality Testing", Canadian Mathematical -// Society Series of Monographs and Advance Texts, vol. 22, John Wiley & Sons, New York, -// NY, 1998. -// -// [8] P. Ribenboim, "The new book of prime number records", 3rd edition, Springer-Verlag, -// New York, NY, 1995. -// -// [9] M. Joye and J.-J. Quisquater, "Efficient computation of full Lucas sequences", -// Electronics Letters, 32(6), 1996, pp 537-538. -// -//************************************************************************************ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace SocketService.Framework.Client.Crypto -{ - [Serializable] - public class BigInteger //: IDisposable - { - // maximum length of the BigInteger in uint (4 bytes) - // change this to suit the required level of precision. - - public const int MaxLength = 180; - - // primes smaller than 2000 to test the generated prime number - - public static readonly int[] primesBelow2000 = { - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, - 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, - 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, - 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, - 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, - 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, - 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, - 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, - 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, - 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, - 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, - 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, - 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, - 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, - 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, - 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, - 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999 }; - - - private uint[] data = null; // stores bytes from the Big Integer - public int dataLength; // number of actual chars used - - - public uint[] Data - { - get { return data; } - } - //*********************************************************************** - // Constructor (Default value for BigInteger is 0 - //*********************************************************************** - - public BigInteger() - { - data = new uint[MaxLength]; - dataLength = 1; - } - - - //*********************************************************************** - // Constructor (Default value provided by long) - //*********************************************************************** - - public BigInteger(long value) - { - data = new uint[MaxLength]; - long tempVal = value; - - // copy bytes from long to BigInteger without any assumption of - // the length of the long datatype - - dataLength = 0; - while (value != 0 && dataLength < MaxLength) - { - data[dataLength] = (uint)(value & 0xFFFFFFFF); - value >>= 32; - dataLength++; - } - - if (tempVal > 0) // overflow check for +ve value - { - if (value != 0 || (data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - } - else if (tempVal < 0) // underflow check for -ve value - { - if (value != -1 || (data[dataLength - 1] & 0x80000000) == 0) - throw (new ArithmeticException("Negative underflow in constructor.")); - } - - if (dataLength == 0) - dataLength = 1; - } - - - //*********************************************************************** - // Constructor (Default value provided by ulong) - //*********************************************************************** - - public BigInteger(ulong value) - { - data = new uint[MaxLength]; - - // copy bytes from ulong to BigInteger without any assumption of - // the length of the ulong datatype - - dataLength = 0; - while (value != 0 && dataLength < MaxLength) - { - data[dataLength] = (uint)(value & 0xFFFFFFFF); - value >>= 32; - dataLength++; - } - - if (value != 0 || (data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - - if (dataLength == 0) - dataLength = 1; - } - - - - //*********************************************************************** - // Constructor (Default value provided by BigInteger) - //*********************************************************************** - - public BigInteger(BigInteger bi) - { - data = new uint[MaxLength]; - - dataLength = bi.dataLength; - - for (int i = 0; i < dataLength; i++) - data[i] = bi.data[i]; - } - - - //*********************************************************************** - // Constructor (Default value provided by a string of digits of the - // specified base) - // - // Example (base 10) - // ----------------- - // To initialize "a" with the default value of 1234 in base 10 - // BigInteger a = new BigInteger("1234", 10) - // - // To initialize "a" with the default value of -1234 - // BigInteger a = new BigInteger("-1234", 10) - // - // Example (base 16) - // ----------------- - // To initialize "a" with the default value of 0x1D4F in base 16 - // BigInteger a = new BigInteger("1D4F", 16) - // - // To initialize "a" with the default value of -0x1D4F - // BigInteger a = new BigInteger("-1D4F", 16) - // - // Note that string values are specified in the - // format. - // - //*********************************************************************** - - public BigInteger(string value, int radix) - { - BigInteger multiplier = new BigInteger(1); - BigInteger result = new BigInteger(); - value = (value.ToUpper()).Trim(); - int limit = 0; - - if (value[0] == '-') - limit = 1; - - for (int i = value.Length - 1; i >= limit; i--) - { - int posVal = (int)value[i]; - - if (posVal >= '0' && posVal <= '9') - posVal -= '0'; - else if (posVal >= 'A' && posVal <= 'Z') - posVal = (posVal - 'A') + 10; - else - posVal = 9999999; // arbitrary large - - - if (posVal >= radix) - throw (new ArithmeticException("Invalid string in constructor.")); - else - { - if (value[0] == '-') - posVal = -posVal; - - result = result + (multiplier * posVal); - - if ((i - 1) >= limit) - multiplier = multiplier * radix; - } - } - - if (value[0] == '-') // negative values - { - if ((result.data[MaxLength - 1] & 0x80000000) == 0) - throw (new ArithmeticException("Negative underflow in constructor.")); - } - else // positive values - { - if ((result.data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - } - - data = new uint[MaxLength]; - for (int i = 0; i < result.dataLength; i++) - data[i] = result.data[i]; - - dataLength = result.dataLength; - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of bytes) - // - // The lowest index of the input byte array (i.e [0]) should contain the - // most significant byte of the number, and the highest index should - // contain the least significant byte. - // - // E.g. - // To initialize "a" with the default value of 0x1D4F in base 16 - // byte[] temp = { 0x1D, 0x4F }; - // BigInteger a = new BigInteger(temp) - // - // Note that this method of initialization does not allow the - // sign to be specified. - // - //*********************************************************************** - - public BigInteger(byte[] inData) - { - dataLength = inData.Length >> 2; - - int leftOver = inData.Length & 0x3; - if (leftOver != 0) // length not multiples of 4 - dataLength++; - - - if (dataLength > MaxLength) - throw (new ArithmeticException("Byte overflow in constructor.")); - - data = new uint[MaxLength]; - - for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++) - { - data[j] = (uint)((inData[i - 3] << 24) + (inData[i - 2] << 16) + - (inData[i - 1] << 8) + inData[i]); - } - - if (leftOver == 1) - data[dataLength - 1] = (uint)inData[0]; - else if (leftOver == 2) - data[dataLength - 1] = (uint)((inData[0] << 8) + inData[1]); - else if (leftOver == 3) - data[dataLength - 1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]); - - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of bytes of the - // specified length.) - //*********************************************************************** - - public BigInteger(byte[] inData, int inLen) - { - dataLength = inLen >> 2; - - int leftOver = inLen & 0x3; - if (leftOver != 0) // length not multiples of 4 - dataLength++; - - if (dataLength > MaxLength || inLen > inData.Length) - throw (new ArithmeticException("Byte overflow in constructor.")); - - - data = new uint[MaxLength]; - - for (int i = inLen - 1, j = 0; i >= 3; i -= 4, j++) - { - data[j] = (uint)((inData[i - 3] << 24) + (inData[i - 2] << 16) + - (inData[i - 1] << 8) + inData[i]); - } - - if (leftOver == 1) - data[dataLength - 1] = (uint)inData[0]; - else if (leftOver == 2) - data[dataLength - 1] = (uint)((inData[0] << 8) + inData[1]); - else if (leftOver == 3) - data[dataLength - 1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]); - - - if (dataLength == 0) - dataLength = 1; - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of unsigned integers) - //********************************************************************* - - public BigInteger(uint[] inData) - { - dataLength = inData.Length; - - if (dataLength > MaxLength) - throw (new ArithmeticException("Byte overflow in constructor.")); - - data = new uint[MaxLength]; - - for (int i = dataLength - 1, j = 0; i >= 0; i--, j++) - data[j] = inData[i]; - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Overloading of the typecast operator. - // For BigInteger bi = 10; - //*********************************************************************** - - public static implicit operator BigInteger(long value) - { - return (new BigInteger(value)); - } - - public static implicit operator BigInteger(ulong value) - { - return (new BigInteger(value)); - } - - public static implicit operator BigInteger(int value) - { - return (new BigInteger((long)value)); - } - - public static implicit operator BigInteger(uint value) - { - return (new BigInteger((ulong)value)); - } - - - //*********************************************************************** - // Overloading of addition operator - //*********************************************************************** - - public static BigInteger operator +(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - long carry = 0; - for (int i = 0; i < result.dataLength; i++) - { - long sum = (long)bi1.data[i] + (long)bi2.data[i] + carry; - carry = sum >> 32; - result.data[i] = (uint)(sum & 0xFFFFFFFF); - } - - if (carry != 0 && result.dataLength < MaxLength) - { - result.data[result.dataLength] = (uint)(carry); - result.dataLength++; - } - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - - // overflow check - int lastPos = MaxLength - 1; - if ((bi1.data[lastPos] & 0x80000000) == (bi2.data[lastPos] & 0x80000000) && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException()); - } - - return result; - } - - - //*********************************************************************** - // Overloading of the unary ++ operator - //*********************************************************************** - - public static BigInteger operator ++(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - long val, carry = 1; - int index = 0; - - while (carry != 0 && index < MaxLength) - { - val = (long)(result.data[index]); - val++; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - - index++; - } - - if (index > result.dataLength) - result.dataLength = index; - else - { - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - } - - // overflow check - int lastPos = MaxLength - 1; - - // overflow if initial value was +ve but ++ caused a sign - // change to negative. - - if ((bi1.data[lastPos] & 0x80000000) == 0 && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException("Overflow in ++.")); - } - return result; - } - - - //*********************************************************************** - // Overloading of subtraction operator - //*********************************************************************** - - public static BigInteger operator -(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - long carryIn = 0; - for (int i = 0; i < result.dataLength; i++) - { - long diff; - - diff = (long)bi1.data[i] - (long)bi2.data[i] - carryIn; - result.data[i] = (uint)(diff & 0xFFFFFFFF); - - if (diff < 0) - carryIn = 1; - else - carryIn = 0; - } - - // roll over to negative - if (carryIn != 0) - { - for (int i = result.dataLength; i < MaxLength; i++) - result.data[i] = 0xFFFFFFFF; - result.dataLength = MaxLength; - } - - // fixed in v1.03 to give correct datalength for a - (-b) - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check - - int lastPos = MaxLength - 1; - if ((bi1.data[lastPos] & 0x80000000) != (bi2.data[lastPos] & 0x80000000) && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException()); - } - - return result; - } - - - //*********************************************************************** - // Overloading of the unary -- operator - //*********************************************************************** - - public static BigInteger operator --(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - long val; - bool carryIn = true; - int index = 0; - - while (carryIn && index < MaxLength) - { - val = (long)(result.data[index]); - val--; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - - if (val >= 0) - carryIn = false; - - index++; - } - - if (index > result.dataLength) - result.dataLength = index; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check - int lastPos = MaxLength - 1; - - // overflow if initial value was -ve but -- caused a sign - // change to positive. - - if ((bi1.data[lastPos] & 0x80000000) != 0 && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException("Underflow in --.")); - } - - return result; - } - - - //*********************************************************************** - // Overloading of multiplication operator - //*********************************************************************** - - public static BigInteger operator *(BigInteger bi1, BigInteger bi2) - { - int lastPos = MaxLength - 1; - bool bi1Neg = false, bi2Neg = false; - - // take the absolute value of the inputs - try - { - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1Neg = true; bi1 = -bi1; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - { - bi2Neg = true; bi2 = -bi2; - } - } - catch (Exception) { } - - BigInteger result = new BigInteger(); - - // multiply the absolute values - try - { - for (int i = 0; i < bi1.dataLength; i++) - { - if (bi1.data[i] == 0) continue; - - ulong mcarry = 0; - for (int j = 0, k = i; j < bi2.dataLength; j++, k++) - { - // k = i + j - ulong val = ((ulong)bi1.data[i] * (ulong)bi2.data[j]) + - (ulong)result.data[k] + mcarry; - - result.data[k] = (uint)(val & 0xFFFFFFFF); - mcarry = (val >> 32); - } - - if (mcarry != 0) - result.data[i + bi2.dataLength] = (uint)mcarry; - } - } - catch (Exception) - { - throw (new ArithmeticException("Multiplication overflow.")); - } - - - result.dataLength = bi1.dataLength + bi2.dataLength; - if (result.dataLength > MaxLength) - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check (result is -ve) - if ((result.data[lastPos] & 0x80000000) != 0) - { - if (bi1Neg != bi2Neg && result.data[lastPos] == 0x80000000) // different sign - { - // handle the special case where multiplication produces - // a max negative number in 2's complement. - - if (result.dataLength == 1) - return result; - else - { - bool isMaxNeg = true; - for (int i = 0; i < result.dataLength - 1 && isMaxNeg; i++) - { - if (result.data[i] != 0) - isMaxNeg = false; - } - - if (isMaxNeg) - return result; - } - } - - throw (new ArithmeticException("Multiplication overflow.")); - } - - // if input has different signs, then result is -ve - if (bi1Neg != bi2Neg) - return -result; - - return result; - } - - - - //*********************************************************************** - // Overloading of unary << operators - //*********************************************************************** - - public static BigInteger operator <<(BigInteger bi1, int shiftVal) - { - BigInteger result = new BigInteger(bi1); - result.dataLength = ShiftLeft(result.data, shiftVal); - - return result; - } - - - // least significant bits at lower part of buffer - - private static int ShiftLeft(uint[] buffer, int shiftVal) - { - int shiftAmount = 32; - int bufLen = buffer.Length; - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - for (int count = shiftVal; count > 0; ) - { - if (count < shiftAmount) - shiftAmount = count; - - //Console.WriteLine("shiftAmount = {0}", shiftAmount); - - ulong carry = 0; - for (int i = 0; i < bufLen; i++) - { - ulong val = ((ulong)buffer[i]) << shiftAmount; - val |= carry; - - buffer[i] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - } - - if (carry != 0) - { - if (bufLen + 1 <= buffer.Length) - { - buffer[bufLen] = (uint)carry; - bufLen++; - } - } - count -= shiftAmount; - } - return bufLen; - } - - - //*********************************************************************** - // Overloading of unary >> operators - //*********************************************************************** - - public static BigInteger operator >>(BigInteger bi1, int shiftVal) - { - BigInteger result = new BigInteger(bi1); - result.dataLength = ShiftRight(result.data, shiftVal); - - - if ((bi1.data[MaxLength - 1] & 0x80000000) != 0) // negative - { - for (int i = MaxLength - 1; i >= result.dataLength; i--) - result.data[i] = 0xFFFFFFFF; - - uint mask = 0x80000000; - for (int i = 0; i < 32; i++) - { - if ((result.data[result.dataLength - 1] & mask) != 0) - break; - - result.data[result.dataLength - 1] |= mask; - mask >>= 1; - } - result.dataLength = MaxLength; - } - - return result; - } - - - private static int ShiftRight(uint[] buffer, int shiftVal) - { - int shiftAmount = 32; - int invShift = 0; - int bufLen = buffer.Length; - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - //Console.WriteLine("bufLen = " + bufLen + " buffer.Length = " + buffer.Length); - - for (int count = shiftVal; count > 0; ) - { - if (count < shiftAmount) - { - shiftAmount = count; - invShift = 32 - shiftAmount; - } - - //Console.WriteLine("shiftAmount = {0}", shiftAmount); - - ulong carry = 0; - for (int i = bufLen - 1; i >= 0; i--) - { - ulong val = ((ulong)buffer[i]) >> shiftAmount; - val |= carry; - - carry = ((ulong)buffer[i]) << invShift; - buffer[i] = (uint)(val); - } - - count -= shiftAmount; - } - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - return bufLen; - } - - - //*********************************************************************** - // Overloading of the NOT operator (1's complement) - //*********************************************************************** - - public static BigInteger operator ~(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - for (int i = 0; i < MaxLength; i++) - result.data[i] = (uint)(~(bi1.data[i])); - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of the NEGATE operator (2's complement) - //*********************************************************************** - - public static BigInteger operator -(BigInteger bi1) - { - // handle neg of zero separately since it'll cause an overflow - // if we proceed. - - if (bi1.dataLength == 1 && bi1.data[0] == 0) - return (new BigInteger()); - - BigInteger result = new BigInteger(bi1); - - // 1's complement - for (int i = 0; i < MaxLength; i++) - result.data[i] = (uint)(~(bi1.data[i])); - - // add one to result of 1's complement - long val, carry = 1; - int index = 0; - - while (carry != 0 && index < MaxLength) - { - val = (long)(result.data[index]); - val++; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - - index++; - } - - if ((bi1.data[MaxLength - 1] & 0x80000000) == (result.data[MaxLength - 1] & 0x80000000)) - throw (new ArithmeticException("Overflow in negation.\n")); - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - return result; - } - - - //*********************************************************************** - // Overloading of equality operator - //*********************************************************************** - - public static bool operator ==(BigInteger bi1, BigInteger bi2) - { - return bi1.Equals(bi2); - } - - - public static bool operator !=(BigInteger bi1, BigInteger bi2) - { - return !(bi1.Equals(bi2)); - } - - - public override bool Equals(object o) - { - BigInteger bi = (BigInteger)o; - - if (this.dataLength != bi.dataLength) - return false; - - for (int i = 0; i < this.dataLength; i++) - { - if (this.data[i] != bi.data[i]) - return false; - } - return true; - } - - - public override int GetHashCode() - { - return this.ToString().GetHashCode(); - } - - - //*********************************************************************** - // Overloading of inequality operator - //*********************************************************************** - - public static bool operator >(BigInteger bi1, BigInteger bi2) - { - int pos = MaxLength - 1; - - // bi1 is negative, bi2 is positive - if ((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0) - return false; - - // bi1 is positive, bi2 is negative - else if ((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0) - return true; - - // same sign - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - for (pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--) ; - - if (pos >= 0) - { - if (bi1.data[pos] > bi2.data[pos]) - return true; - return false; - } - return false; - } - - - public static bool operator <(BigInteger bi1, BigInteger bi2) - { - int pos = MaxLength - 1; - - // bi1 is negative, bi2 is positive - if ((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0) - return true; - - // bi1 is positive, bi2 is negative - else if ((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0) - return false; - - // same sign - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - for (pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--) ; - - if (pos >= 0) - { - if (bi1.data[pos] < bi2.data[pos]) - return true; - return false; - } - return false; - } - - - public static bool operator >=(BigInteger bi1, BigInteger bi2) - { - return (bi1 == bi2 || bi1 > bi2); - } - - - public static bool operator <=(BigInteger bi1, BigInteger bi2) - { - return (bi1 == bi2 || bi1 < bi2); - } - - - //*********************************************************************** - // Private function that supports the division of two numbers with - // a divisor that has more than 1 digit. - // - // Algorithm taken from [1] - //*********************************************************************** - - private static void MultiByteDivide(BigInteger bi1, BigInteger bi2, - BigInteger outQuotient, BigInteger outRemainder) - { - uint[] result = new uint[MaxLength]; - - int remainderLen = bi1.dataLength + 1; - uint[] remainder = new uint[remainderLen]; - - uint mask = 0x80000000; - uint val = bi2.data[bi2.dataLength - 1]; - int shift = 0, resultPos = 0; - - while (mask != 0 && (val & mask) == 0) - { - shift++; mask >>= 1; - } - - //Console.WriteLine("shift = {0}", shift); - //Console.WriteLine("Before bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength); - - for (int i = 0; i < bi1.dataLength; i++) - remainder[i] = bi1.data[i]; - ShiftLeft(remainder, shift); - bi2 = bi2 << shift; - - /* - Console.WriteLine("bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength); - Console.WriteLine("dividend = " + bi1 + "\ndivisor = " + bi2); - for(int q = remainderLen - 1; q >= 0; q--) - Console.Write("{0:x2}", remainder[q]); - Console.WriteLine(); - */ - - int j = remainderLen - bi2.dataLength; - int pos = remainderLen - 1; - - ulong firstDivisorByte = bi2.data[bi2.dataLength - 1]; - ulong secondDivisorByte = bi2.data[bi2.dataLength - 2]; - - int divisorLen = bi2.dataLength + 1; - uint[] dividendPart = new uint[divisorLen]; - - while (j > 0) - { - ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos - 1]; - //Console.WriteLine("dividend = {0}", dividend); - - ulong q_hat = dividend / firstDivisorByte; - ulong r_hat = dividend % firstDivisorByte; - - //Console.WriteLine("q_hat = {0:X}, r_hat = {1:X}", q_hat, r_hat); - - bool done = false; - while (!done) - { - done = true; - - if (q_hat == 0x100000000 || - (q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos - 2])) - { - q_hat--; - r_hat += firstDivisorByte; - - if (r_hat < 0x100000000) - done = false; - } - } - - for (int h = 0; h < divisorLen; h++) - dividendPart[h] = remainder[pos - h]; - - BigInteger kk = new BigInteger(dividendPart); - BigInteger ss = bi2 * (long)q_hat; - - //Console.WriteLine("ss before = " + ss); - while (ss > kk) - { - q_hat--; - ss -= bi2; - //Console.WriteLine(ss); - } - BigInteger yy = kk - ss; - - //Console.WriteLine("ss = " + ss); - //Console.WriteLine("kk = " + kk); - //Console.WriteLine("yy = " + yy); - - for (int h = 0; h < divisorLen; h++) - remainder[pos - h] = yy.data[bi2.dataLength - h]; - - /* - Console.WriteLine("dividend = "); - for(int q = remainderLen - 1; q >= 0; q--) - Console.Write("{0:x2}", remainder[q]); - Console.WriteLine("\n************ q_hat = {0:X}\n", q_hat); - */ - - result[resultPos++] = (uint)q_hat; - - pos--; - j--; - } - - outQuotient.dataLength = resultPos; - int y = 0; - for (int x = outQuotient.dataLength - 1; x >= 0; x--, y++) - outQuotient.data[y] = result[x]; - for (; y < MaxLength; y++) - outQuotient.data[y] = 0; - - while (outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength - 1] == 0) - outQuotient.dataLength--; - - if (outQuotient.dataLength == 0) - outQuotient.dataLength = 1; - - outRemainder.dataLength = ShiftRight(remainder, shift); - - for (y = 0; y < outRemainder.dataLength; y++) - outRemainder.data[y] = remainder[y]; - for (; y < MaxLength; y++) - outRemainder.data[y] = 0; - } - - - //*********************************************************************** - // Private function that supports the division of two numbers with - // a divisor that has only 1 digit. - //*********************************************************************** - - private static void SingleByteDivide(BigInteger bi1, BigInteger bi2, - BigInteger outQuotient, BigInteger outRemainder) - { - uint[] result = new uint[MaxLength]; - int resultPos = 0; - - // copy dividend to reminder - for (int i = 0; i < MaxLength; i++) - outRemainder.data[i] = bi1.data[i]; - outRemainder.dataLength = bi1.dataLength; - - while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0) - outRemainder.dataLength--; - - ulong divisor = (ulong)bi2.data[0]; - int pos = outRemainder.dataLength - 1; - ulong dividend = (ulong)outRemainder.data[pos]; - - //Console.WriteLine("divisor = " + divisor + " dividend = " + dividend); - //Console.WriteLine("divisor = " + bi2 + "\ndividend = " + bi1); - - if (dividend >= divisor) - { - ulong quotient = dividend / divisor; - result[resultPos++] = (uint)quotient; - - outRemainder.data[pos] = (uint)(dividend % divisor); - } - pos--; - - while (pos >= 0) - { - //Console.WriteLine(pos); - - dividend = ((ulong)outRemainder.data[pos + 1] << 32) + (ulong)outRemainder.data[pos]; - ulong quotient = dividend / divisor; - result[resultPos++] = (uint)quotient; - - outRemainder.data[pos + 1] = 0; - outRemainder.data[pos--] = (uint)(dividend % divisor); - //Console.WriteLine(">>>> " + bi1); - } - - outQuotient.dataLength = resultPos; - int j = 0; - for (int i = outQuotient.dataLength - 1; i >= 0; i--, j++) - outQuotient.data[j] = result[i]; - for (; j < MaxLength; j++) - outQuotient.data[j] = 0; - - while (outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength - 1] == 0) - outQuotient.dataLength--; - - if (outQuotient.dataLength == 0) - outQuotient.dataLength = 1; - - while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0) - outRemainder.dataLength--; - } - - - //*********************************************************************** - // Overloading of division operator - //*********************************************************************** - - public static BigInteger operator /(BigInteger bi1, BigInteger bi2) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - - int lastPos = MaxLength - 1; - bool divisorNeg = false, dividendNeg = false; - - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1 = -bi1; - dividendNeg = true; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - { - bi2 = -bi2; - divisorNeg = true; - } - - if (bi1 < bi2) - { - return quotient; - } - - else - { - if (bi2.dataLength == 1) - SingleByteDivide(bi1, bi2, quotient, remainder); - else - MultiByteDivide(bi1, bi2, quotient, remainder); - - if (dividendNeg != divisorNeg) - return -quotient; - - return quotient; - } - } - - - //*********************************************************************** - // Overloading of modulus operator - //*********************************************************************** - - public static BigInteger operator %(BigInteger bi1, BigInteger bi2) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(bi1); - - int lastPos = MaxLength - 1; - bool dividendNeg = false; - - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1 = -bi1; - dividendNeg = true; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - bi2 = -bi2; - - if (bi1 < bi2) - { - return remainder; - } - - else - { - if (bi2.dataLength == 1) - SingleByteDivide(bi1, bi2, quotient, remainder); - else - MultiByteDivide(bi1, bi2, quotient, remainder); - - if (dividendNeg) - return -remainder; - - return remainder; - } - } - - - //*********************************************************************** - // Overloading of bitwise AND operator - //*********************************************************************** - - public static BigInteger operator &(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] & bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of bitwise OR operator - //*********************************************************************** - - public static BigInteger operator |(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] | bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of bitwise XOR operator - //*********************************************************************** - - public static BigInteger operator ^(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] ^ bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Returns max(this, bi) - //*********************************************************************** - - public BigInteger Max(BigInteger bi) - { - if (this > bi) - return (new BigInteger(this)); - else - return (new BigInteger(bi)); - } - - - //*********************************************************************** - // Returns min(this, bi) - //*********************************************************************** - - public BigInteger Min(BigInteger bi) - { - if (this < bi) - return (new BigInteger(this)); - else - return (new BigInteger(bi)); - - } - - - //*********************************************************************** - // Returns the absolute value - //*********************************************************************** - - public BigInteger Abs() - { - if ((this.data[MaxLength - 1] & 0x80000000) != 0) - return (-this); - else - return (new BigInteger(this)); - } - - - //*********************************************************************** - // Returns a string representing the BigInteger in base 10. - //*********************************************************************** - - public override string ToString() - { - return ToString(10); - } - - - //*********************************************************************** - // Returns a string representing the BigInteger in sign-and-magnitude - // format in the specified radix. - // - // Example - // ------- - // If the value of BigInteger is -255 in base 10, then - // ToString(16) returns "-FF" - // - //*********************************************************************** - - public string ToString(int radix) - { - if (radix < 2 || radix > 36) - throw (new ArgumentException("Radix must be >= 2 and <= 36")); - - string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - string result = ""; - - BigInteger a = this; - - bool negative = false; - if ((a.data[MaxLength - 1] & 0x80000000) != 0) - { - negative = true; - try - { - a = -a; - } - catch (Exception) { } - } - - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - BigInteger biRadix = new BigInteger(radix); - - if (a.dataLength == 1 && a.data[0] == 0) - result = "0"; - else - { - while (a.dataLength > 1 || (a.dataLength == 1 && a.data[0] != 0)) - { - SingleByteDivide(a, biRadix, quotient, remainder); - - if (remainder.data[0] < 10) - result = remainder.data[0] + result; - else - result = charSet[(int)remainder.data[0] - 10] + result; - - a = quotient; - } - if (negative) - result = "-" + result; - } - - return result; - } - - - //*********************************************************************** - // Returns a hex string showing the contains of the BigInteger - // - // Examples - // ------- - // 1) If the value of BigInteger is 255 in base 10, then - // ToHexString() returns "FF" - // - // 2) If the value of BigInteger is -255 in base 10, then - // ToHexString() returns ".....FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01", - // which is the 2's complement representation of -255. - // - //*********************************************************************** - - public string ToHexString() - { - string result = data[dataLength - 1].ToString("X"); - - for (int i = dataLength - 2; i >= 0; i--) - { - result += data[i].ToString("X8"); - } - - return result; - } - - public byte[] ToByteArray() - { - List result = new List(); - - //int dataLength = data.Length; - result.AddRange(BitConverter.GetBytes(data[dataLength - 1])); - for (int i = dataLength - 2; i >= 0; i--) - { - result.AddRange(BitConverter.GetBytes(data[i])); - } - - return result.ToArray(); - } - - private static System.Xml.Serialization.XmlSerializer serializer; - - private static System.Xml.Serialization.XmlSerializer Serializer - { - get - { - if ((serializer == null)) - { - serializer = new System.Xml.Serialization.XmlSerializer(typeof(BigInteger)); - } - return serializer; - } - } - - public string ToXml() - { - // return an xml representation - return Serialize(); - } - - public virtual string Serialize() - { - System.IO.StreamReader streamReader = null; - System.IO.MemoryStream memoryStream = null; - try - { - memoryStream = new System.IO.MemoryStream(); - Serializer.Serialize(memoryStream, this); - memoryStream.Seek(0, System.IO.SeekOrigin.Begin); - streamReader = new System.IO.StreamReader(memoryStream); - return streamReader.ReadToEnd(); - } - finally - { - if ((streamReader != null)) - { - streamReader.Dispose(); - } - if ((memoryStream != null)) - { - memoryStream.Dispose(); - } - } - } - //*********************************************************************** - // Modulo Exponentiation - //*********************************************************************** - - public BigInteger ModPow(BigInteger exp, BigInteger n) - { - if ((exp.data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive exponents only.")); - - BigInteger resultNum = 1; - BigInteger tempNum; - bool thisNegative = false; - - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative this - { - tempNum = -this % n; - thisNegative = true; - } - else - tempNum = this % n; // ensures (tempNum * tempNum) < b^(2k) - - if ((n.data[MaxLength - 1] & 0x80000000) != 0) // negative n - n = -n; - - // calculate constant = b^(2k) / m - BigInteger constant = new BigInteger(); - - int i = n.dataLength << 1; - constant.data[i] = 0x00000001; - constant.dataLength = i + 1; - - constant = constant / n; - int totalBits = exp.BitCount(); - int count = 0; - - // perform squaring and multiply exponentiation - for (int pos = 0; pos < exp.dataLength; pos++) - { - uint mask = 0x01; - //Console.WriteLine("pos = " + pos); - - for (int index = 0; index < 32; index++) - { - if ((exp.data[pos] & mask) != 0) - resultNum = BarrettReduction(resultNum * tempNum, n, constant); - - mask <<= 1; - - tempNum = BarrettReduction(tempNum * tempNum, n, constant); - - - if (tempNum.dataLength == 1 && tempNum.data[0] == 1) - { - if (thisNegative && (exp.data[0] & 0x1) != 0) //odd exp - return -resultNum; - return resultNum; - } - count++; - if (count == totalBits) - break; - } - } - - if (thisNegative && (exp.data[0] & 0x1) != 0) //odd exp - return -resultNum; - - return resultNum; - } - - - - //*********************************************************************** - // Fast calculation of modular reduction using Barrett's reduction. - // Requires x < b^(2k), where b is the base. In this case, base is - // 2^32 (uint). - // - // Reference [4] - //*********************************************************************** - - public static BigInteger BarrettReduction(BigInteger x, BigInteger n, BigInteger constant) - { - int k = n.dataLength, - kPlusOne = k + 1, - kMinusOne = k - 1; - - BigInteger q1 = new BigInteger(); - - // q1 = x / b^(k-1) - for (int i = kMinusOne, j = 0; i < x.dataLength; i++, j++) - q1.data[j] = x.data[i]; - q1.dataLength = x.dataLength - kMinusOne; - if (q1.dataLength <= 0) - q1.dataLength = 1; - - - BigInteger q2 = q1 * constant; - BigInteger q3 = new BigInteger(); - - // q3 = q2 / b^(k+1) - for (int i = kPlusOne, j = 0; i < q2.dataLength; i++, j++) - q3.data[j] = q2.data[i]; - q3.dataLength = q2.dataLength - kPlusOne; - if (q3.dataLength <= 0) - q3.dataLength = 1; - - - // r1 = x mod b^(k+1) - // i.e. keep the lowest (k+1) words - BigInteger r1 = new BigInteger(); - int lengthToCopy = (x.dataLength > kPlusOne) ? kPlusOne : x.dataLength; - for (int i = 0; i < lengthToCopy; i++) - r1.data[i] = x.data[i]; - r1.dataLength = lengthToCopy; - - - // r2 = (q3 * n) mod b^(k+1) - // partial multiplication of q3 and n - - BigInteger r2 = new BigInteger(); - for (int i = 0; i < q3.dataLength; i++) - { - if (q3.data[i] == 0) continue; - - ulong mcarry = 0; - int t = i; - for (int j = 0; j < n.dataLength && t < kPlusOne; j++, t++) - { - // t = i + j - ulong val = ((ulong)q3.data[i] * (ulong)n.data[j]) + - (ulong)r2.data[t] + mcarry; - - r2.data[t] = (uint)(val & 0xFFFFFFFF); - mcarry = (val >> 32); - } - - if (t < kPlusOne) - r2.data[t] = (uint)mcarry; - } - r2.dataLength = kPlusOne; - while (r2.dataLength > 1 && r2.data[r2.dataLength - 1] == 0) - r2.dataLength--; - - r1 -= r2; - if ((r1.data[MaxLength - 1] & 0x80000000) != 0) // negative - { - BigInteger val = new BigInteger(); - val.data[kPlusOne] = 0x00000001; - val.dataLength = kPlusOne + 1; - r1 += val; - } - - while (r1 >= n) - r1 -= n; - - return r1; - } - - - //*********************************************************************** - // Returns gcd(this, bi) - //*********************************************************************** - - public BigInteger Gcd(BigInteger bi) - { - BigInteger x; - BigInteger y; - - if ((data[MaxLength - 1] & 0x80000000) != 0) // negative - x = -this; - else - x = this; - - if ((bi.data[MaxLength - 1] & 0x80000000) != 0) // negative - y = -bi; - else - y = bi; - - BigInteger g = y; - - while (x.dataLength > 1 || (x.dataLength == 1 && x.data[0] != 0)) - { - g = x; - x = y % x; - y = g; - } - - return g; - } - - - //*********************************************************************** - // Populates "this" with the specified amount of random bits - //*********************************************************************** - - public void GenRandomBits(int bits, StrongNumberProvider rand) - { - int dwords = bits >> 5; - int remBits = bits & 0x1F; - - if (remBits != 0) - dwords++; - - if (dwords > MaxLength) - throw (new ArithmeticException("Number of required bits > maxLength.")); - - for (int i = 0; i < dwords; i++) - data[i] = (uint)rand.GetNextUInt32(); - - for (int i = dwords; i < MaxLength; i++) - data[i] = 0; - - if (remBits != 0) - { - uint mask = (uint)(0x01 << (remBits - 1)); - data[dwords - 1] |= mask; - - mask = (uint)(0xFFFFFFFF >> (32 - remBits)); - data[dwords - 1] &= mask; - } - else - data[dwords - 1] |= 0x80000000; - - dataLength = dwords; - - if (dataLength == 0) - dataLength = 1; - } - - - //*********************************************************************** - // Returns the position of the most significant bit in the BigInteger. - // - // Eg. The result is 0, if the value of BigInteger is 0...0000 0000 - // The result is 1, if the value of BigInteger is 0...0000 0001 - // The result is 2, if the value of BigInteger is 0...0000 0010 - // The result is 2, if the value of BigInteger is 0...0000 0011 - // - //*********************************************************************** - - public int BitCount() - { - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - uint value = data[dataLength - 1]; - uint mask = 0x80000000; - int bits = 32; - - while (bits > 0 && (value & mask) == 0) - { - bits--; - mask >>= 1; - } - bits += ((dataLength - 1) << 5); - - return bits; - } - - - //*********************************************************************** - // Probabilistic prime test based on Fermat's little theorem - // - // for any a < p (p does not divide a) if - // a^(p-1) mod p != 1 then p is not prime. - // - // Otherwise, p is probably prime (pseudoprime to the chosen base). - // - // Returns - // ------- - // True if "this" is a pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - // Note - this method is fast but fails for Carmichael numbers except - // when the randomly chosen base is a factor of the number. - // - //*********************************************************************** - - public bool FermatLittleTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = rand.GetNextInt() * bits; - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - // calculate a^(p-1) mod p - BigInteger expResult = a.ModPow(p_sub1, thisVal); - - int resultLen = expResult.dataLength; - - // is NOT prime is a^(p-1) mod p != 1 - - if (resultLen > 1 || (resultLen == 1 && expResult.data[0] != 1)) - { - //Console.WriteLine("a = " + a.ToString()); - return false; - } - } - - return true; - } - - - //*********************************************************************** - // Probabilistic prime test based on Rabin-Miller's - // - // for any p > 0 with p - 1 = 2^s * t - // - // p is probably prime (strong pseudoprime) if for any a < p, - // 1) a^t mod p = 1 or - // 2) a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - // - // Otherwise, p is composite. - // - // Returns - // ------- - // True if "this" is a strong pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - //*********************************************************************** - - public bool RabinMillerTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - // calculate values of s and t - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - int s = 0; - - for (int index = 0; index < p_sub1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_sub1.data[index] & mask) != 0) - { - index = p_sub1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_sub1 >> s; - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = (int)(rand.GetNextSingle() * bits); - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - BigInteger b = a.ModPow(t, thisVal); - - bool result = false; - - if (b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1 - result = true; - - for (int j = 0; result == false && j < s; j++) - { - if (b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - { - result = true; - break; - } - - b = (b * b) % thisVal; - } - - if (result == false) - return false; - } - return true; - } - - - //*********************************************************************** - // Probabilistic prime test based on Solovay-Strassen (Euler Criterion) - // - // p is probably prime if for any a < p (a is not multiple of p), - // a^((p-1)/2) mod p = J(a, p) - // - // where J is the Jacobi symbol. - // - // Otherwise, p is composite. - // - // Returns - // ------- - // True if "this" is a Euler pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - //*********************************************************************** - - public bool SolovayStrassenTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - BigInteger p_sub1 = thisVal - 1; - BigInteger p_sub1_shift = p_sub1 >> 1; - - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = (int)(rand.GetNextSingle() * bits); - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - // calculate a^((p-1)/2) mod p - - BigInteger expResult = a.ModPow(p_sub1_shift, thisVal); - if (expResult == p_sub1) - expResult = -1; - - // calculate Jacobi symbol - BigInteger jacob = Jacobi(a, thisVal); - - //Console.WriteLine("a = " + a.ToString(10) + " b = " + thisVal.ToString(10)); - //Console.WriteLine("expResult = " + expResult.ToString(10) + " Jacob = " + jacob.ToString(10)); - - // if they are different then it is not prime - if (expResult != jacob) - return false; - } - - return true; - } - - - //*********************************************************************** - // Implementation of the Lucas Strong Pseudo Prime test. - // - // Let n be an odd number with gcd(n,D) = 1, and n - J(D, n) = 2^s * d - // with d odd and s >= 0. - // - // If Ud mod n = 0 or V2^r*d mod n = 0 for some 0 <= r < s, then n - // is a strong Lucas pseudoprime with parameters (P, Q). We select - // P and Q based on Selfridge. - // - // Returns True if number is a strong Lucus pseudo prime. - // Otherwise, returns False indicating that number is composite. - //*********************************************************************** - - public bool LucasStrongTest() - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - return LucasStrongTestHelper(thisVal); - } - - - private bool LucasStrongTestHelper(BigInteger thisVal) - { - // Do the test (selects D based on Selfridge) - // Let D be the first element of the sequence - // 5, -7, 9, -11, 13, ... for which J(D,n) = -1 - // Let P = 1, Q = (1-D) / 4 - - long D = 5, sign = -1, dCount = 0; - bool done = false; - - while (!done) - { - int Jresult = BigInteger.Jacobi(D, thisVal); - - if (Jresult == -1) - done = true; // J(D, this) = 1 - else - { - if (Jresult == 0 && Math.Abs(D) < thisVal) // divisor found - return false; - - if (dCount == 20) - { - // check for square - BigInteger root = thisVal.Sqrt(); - if (root * root == thisVal) - return false; - } - - //Console.WriteLine(D); - D = (Math.Abs(D) + 2) * sign; - sign = -sign; - } - dCount++; - } - - long Q = (1 - D) >> 2; - - BigInteger p_add1 = thisVal + 1; - int s = 0; - - for (int index = 0; index < p_add1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_add1.data[index] & mask) != 0) - { - index = p_add1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_add1 >> s; - - // calculate constant = b^(2k) / m - // for Barrett Reduction - BigInteger constant = new BigInteger(); - - int nLen = thisVal.dataLength << 1; - constant.data[nLen] = 0x00000001; - constant.dataLength = nLen + 1; - - constant = constant / thisVal; - - BigInteger[] lucas = LucasSequenceHelper(1, Q, t, thisVal, constant, 0); - bool isPrime = false; - - if ((lucas[0].dataLength == 1 && lucas[0].data[0] == 0) || - (lucas[1].dataLength == 1 && lucas[1].data[0] == 0)) - { - // u(t) = 0 or V(t) = 0 - isPrime = true; - } - - for (int i = 1; i < s; i++) - { - if (!isPrime) - { - // doubling of index - lucas[1] = BigInteger.BarrettReduction(lucas[1] * lucas[1], thisVal, constant); - lucas[1] = (lucas[1] - (lucas[2] << 1)) % thisVal; - - //lucas[1] = ((lucas[1] * lucas[1]) - (lucas[2] << 1)) % thisVal; - - if ((lucas[1].dataLength == 1 && lucas[1].data[0] == 0)) - isPrime = true; - } - - lucas[2] = BigInteger.BarrettReduction(lucas[2] * lucas[2], thisVal, constant); //Q^k - } - - - if (isPrime) // additional checks for composite numbers - { - // If n is prime and gcd(n, Q) == 1, then - // Q^((n+1)/2) = Q * Q^((n-1)/2) is congruent to (Q * J(Q, n)) mod n - - BigInteger g = thisVal.Gcd(Q); - if (g.dataLength == 1 && g.data[0] == 1) // gcd(this, Q) == 1 - { - if ((lucas[2].data[MaxLength - 1] & 0x80000000) != 0) - lucas[2] += thisVal; - - BigInteger temp = (Q * BigInteger.Jacobi(Q, thisVal)) % thisVal; - if ((temp.data[MaxLength - 1] & 0x80000000) != 0) - temp += thisVal; - - if (lucas[2] != temp) - isPrime = false; - } - } - - return isPrime; - } - - - //*********************************************************************** - // Determines whether a number is probably prime, using the Rabin-Miller's - // test. Before applying the test, the number is tested for divisibility - // by primes < 2000 - // - // Returns true if number is probably prime. - //*********************************************************************** - - public bool IsProbablePrime(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - - // test for divisibility by primes < 2000 - for (int p = 0; p < primesBelow2000.Length; p++) - { - BigInteger divisor = primesBelow2000[p]; - - if (divisor >= thisVal) - break; - - BigInteger resultNum = thisVal % divisor; - if (resultNum.IntValue() == 0) - { - /* - Console.WriteLine("Not prime! Divisible by {0}\n", - primesBelow2000[p]); - */ - return false; - } - } - - if (thisVal.RabinMillerTest(confidence)) - return true; - else - { - //Console.WriteLine("Not prime! Failed primality test\n"); - return false; - } - } - - - //*********************************************************************** - // Determines whether this BigInteger is probably prime using a - // combination of base 2 strong pseudoprime test and Lucas strong - // pseudoprime test. - // - // The sequence of the primality test is as follows, - // - // 1) Trial divisions are carried out using prime numbers below 2000. - // if any of the primes divides this BigInteger, then it is not prime. - // - // 2) Perform base 2 strong pseudoprime test. If this BigInteger is a - // base 2 strong pseudoprime, proceed on to the next step. - // - // 3) Perform strong Lucas pseudoprime test. - // - // Returns True if this BigInteger is both a base 2 strong pseudoprime - // and a strong Lucas pseudoprime. - // - // For a detailed discussion of this primality test, see [6]. - // - //*********************************************************************** - - public bool IsProbablePrime() - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - // test for divisibility by primes < 2000 - for (int p = 0; p < primesBelow2000.Length; p++) - { - BigInteger divisor = primesBelow2000[p]; - - if (divisor >= thisVal) - break; - - BigInteger resultNum = thisVal % divisor; - if (resultNum.IntValue() == 0) - { - //Console.WriteLine("Not prime! Divisible by {0}\n", - // primesBelow2000[p]); - - return false; - } - } - - // Perform BASE 2 Rabin-Miller Test - - // calculate values of s and t - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - int s = 0; - - for (int index = 0; index < p_sub1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_sub1.data[index] & mask) != 0) - { - index = p_sub1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_sub1 >> s; - - int bits = thisVal.BitCount(); - BigInteger a = 2; - - // b = a^t mod p - BigInteger b = a.ModPow(t, thisVal); - bool result = false; - - if (b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1 - result = true; - - for (int j = 0; result == false && j < s; j++) - { - if (b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - { - result = true; - break; - } - - b = (b * b) % thisVal; - } - - // if number is strong pseudoprime to base 2, then do a strong lucas test - if (result) - result = LucasStrongTestHelper(thisVal); - - return result; - } - - - - //*********************************************************************** - // Returns the lowest 4 bytes of the BigInteger as an int. - //*********************************************************************** - - public int IntValue() - { - return (int)data[0]; - } - - - //*********************************************************************** - // Returns the lowest 8 bytes of the BigInteger as a long. - //*********************************************************************** - - public long LongValue() - { - long val = 0; - - val = (long)data[0]; - try - { // exception if maxLength = 1 - val |= (long)data[1] << 32; - } - catch (Exception) - { - if ((data[0] & 0x80000000) != 0) // negative - val = (int)data[0]; - } - - return val; - } - - - //*********************************************************************** - // Computes the Jacobi Symbol for a and b. - // Algorithm adapted from [3] and [4] with some optimizations - //*********************************************************************** - - public static int Jacobi(BigInteger a, BigInteger b) - { - // Jacobi defined only for odd integers - if ((b.data[0] & 0x1) == 0) - throw (new ArgumentException("Jacobi defined only for odd integers.")); - - if (a >= b) a %= b; - if (a.dataLength == 1 && a.data[0] == 0) return 0; // a == 0 - if (a.dataLength == 1 && a.data[0] == 1) return 1; // a == 1 - - if (a < 0) - { - if ((((b - 1).data[0]) & 0x2) == 0) //if( (((b-1) >> 1).data[0] & 0x1) == 0) - return Jacobi(-a, b); - else - return -Jacobi(-a, b); - } - - int e = 0; - for (int index = 0; index < a.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((a.data[index] & mask) != 0) - { - index = a.dataLength; // to break the outer loop - break; - } - mask <<= 1; - e++; - } - } - - BigInteger a1 = a >> e; - - int s = 1; - if ((e & 0x1) != 0 && ((b.data[0] & 0x7) == 3 || (b.data[0] & 0x7) == 5)) - s = -1; - - if ((b.data[0] & 0x3) == 3 && (a1.data[0] & 0x3) == 3) - s = -s; - - if (a1.dataLength == 1 && a1.data[0] == 1) - return s; - else - return (s * Jacobi(b % a1, a1)); - } - - - - //*********************************************************************** - // Generates a positive BigInteger that is probably prime. - //*********************************************************************** - - public static BigInteger GenPseudoPrime(int bits, int confidence, StrongNumberProvider rand) - { - BigInteger result = new BigInteger(); - bool done = false; - - while (!done) - { - result.GenRandomBits(bits, rand); - result.data[0] |= 0x01; // make it odd - - // prime test - done = result.IsProbablePrime(confidence); - } - return result; - } - - - //*********************************************************************** - // Generates a random number with the specified number of bits such - // that gcd(number, this) = 1 - //*********************************************************************** - - public BigInteger GenCoPrime(int bits, StrongNumberProvider rand) - { - bool done = false; - BigInteger result = new BigInteger(); - - while (!done) - { - result.GenRandomBits(bits, rand); - //Console.WriteLine(result.ToString(16)); - - // gcd test - BigInteger g = result.Gcd(this); - if (g.dataLength == 1 && g.data[0] == 1) - done = true; - } - - return result; - } - - - //*********************************************************************** - // Returns the modulo inverse of this. Throws ArithmeticException if - // the inverse does not exist. (i.e. gcd(this, modulus) != 1) - //*********************************************************************** - - public BigInteger ModInverse(BigInteger modulus) - { - BigInteger[] p = { 0, 1 }; - BigInteger[] q = new BigInteger[2]; // quotients - BigInteger[] r = { 0, 0 }; // remainders - - int step = 0; - - BigInteger a = modulus; - BigInteger b = this; - - while (b.dataLength > 1 || (b.dataLength == 1 && b.data[0] != 0)) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - - if (step > 1) - { - BigInteger pval = (p[0] - (p[1] * q[0])) % modulus; - p[0] = p[1]; - p[1] = pval; - } - - if (b.dataLength == 1) - SingleByteDivide(a, b, quotient, remainder); - else - MultiByteDivide(a, b, quotient, remainder); - - /* - Console.WriteLine(quotient.dataLength); - Console.WriteLine("{0} = {1}({2}) + {3} p = {4}", a.ToString(10), - b.ToString(10), quotient.ToString(10), remainder.ToString(10), - p[1].ToString(10)); - */ - - q[0] = q[1]; - r[0] = r[1]; - q[1] = quotient; r[1] = remainder; - - a = b; - b = remainder; - - step++; - } - - if (r[0].dataLength > 1 || (r[0].dataLength == 1 && r[0].data[0] != 1)) - throw (new ArithmeticException("No inverse!")); - - BigInteger result = ((p[0] - (p[1] * q[0])) % modulus); - - if ((result.data[MaxLength - 1] & 0x80000000) != 0) - result += modulus; // get the least positive modulus - - return result; - } - - - //*********************************************************************** - // Returns the value of the BigInteger as a byte array. The lowest - // index contains the MSB. - //*********************************************************************** - - public byte[] GetBytes() - { - int numBits = BitCount(); - - int numBytes = numBits >> 3; - if ((numBits & 0x7) != 0) - numBytes++; - - byte[] result = new byte[numBytes]; - - //Console.WriteLine(result.Length); - - int pos = 0; - uint tempVal, val = data[dataLength - 1]; - - if ((tempVal = (val >> 24 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val >> 16 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val >> 8 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - - for (int i = dataLength - 2; i >= 0; i--, pos += 4) - { - val = data[i]; - result[pos + 3] = (byte)(val & 0xFF); - val >>= 8; - result[pos + 2] = (byte)(val & 0xFF); - val >>= 8; - result[pos + 1] = (byte)(val & 0xFF); - val >>= 8; - result[pos] = (byte)(val & 0xFF); - } - - return result; - } - - - //*********************************************************************** - // Sets the value of the specified bit to 1 - // The Least Significant Bit position is 0. - //*********************************************************************** - - public void SetBit(uint bitNum) - { - uint bytePos = bitNum >> 5; // divide by 32 - byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits - - uint mask = (uint)1 << bitPos; - this.data[bytePos] |= mask; - - if (bytePos >= this.dataLength) - this.dataLength = (int)bytePos + 1; - } - - - //*********************************************************************** - // Sets the value of the specified bit to 0 - // The Least Significant Bit position is 0. - //*********************************************************************** - - public void UnsetBit(uint bitNum) - { - uint bytePos = bitNum >> 5; - - if (bytePos < this.dataLength) - { - byte bitPos = (byte)(bitNum & 0x1F); - - uint mask = (uint)1 << bitPos; - uint mask2 = 0xFFFFFFFF ^ mask; - - this.data[bytePos] &= mask2; - - if (this.dataLength > 1 && this.data[this.dataLength - 1] == 0) - this.dataLength--; - } - } - - - //*********************************************************************** - // Returns a value that is equivalent to the integer square root - // of the BigInteger. - // - // The integer square root of "this" is defined as the largest integer n - // such that (n * n) <= this - // - //*********************************************************************** - - public BigInteger Sqrt() - { - uint numBits = (uint)this.BitCount(); - - if ((numBits & 0x1) != 0) // odd number of bits - numBits = (numBits >> 1) + 1; - else - numBits = (numBits >> 1); - - uint bytePos = numBits >> 5; - byte bitPos = (byte)(numBits & 0x1F); - - uint mask; - - BigInteger result = new BigInteger(); - if (bitPos == 0) - mask = 0x80000000; - else - { - mask = (uint)1 << bitPos; - bytePos++; - } - result.dataLength = (int)bytePos; - - for (int i = (int)bytePos - 1; i >= 0; i--) - { - while (mask != 0) - { - // guess - result.data[i] ^= mask; - - // undo the guess if its square is larger than this - if ((result * result) > this) - result.data[i] ^= mask; - - mask >>= 1; - } - mask = 0x80000000; - } - return result; - } - - - //*********************************************************************** - // Returns the k_th number in the Lucas Sequence reduced modulo n. - // - // Uses index doubling to speed up the process. For example, to calculate V(k), - // we maintain two numbers in the sequence V(n) and V(n+1). - // - // To obtain V(2n), we use the identity - // V(2n) = (V(n) * V(n)) - (2 * Q^n) - // To obtain V(2n+1), we first write it as - // V(2n+1) = V((n+1) + n) - // and use the identity - // V(m+n) = V(m) * V(n) - Q * V(m-n) - // Hence, - // V((n+1) + n) = V(n+1) * V(n) - Q^n * V((n+1) - n) - // = V(n+1) * V(n) - Q^n * V(1) - // = V(n+1) * V(n) - Q^n * P - // - // We use k in its binary expansion and perform index doubling for each - // bit position. For each bit position that is set, we perform an - // index doubling followed by an index addition. This means that for V(n), - // we need to update it to V(2n+1). For V(n+1), we need to update it to - // V((2n+1)+1) = V(2*(n+1)) - // - // This function returns - // [0] = U(k) - // [1] = V(k) - // [2] = Q^n - // - // Where U(0) = 0 % n, U(1) = 1 % n - // V(0) = 2 % n, V(1) = P % n - //*********************************************************************** - - public static BigInteger[] LucasSequence(BigInteger P, BigInteger Q, - BigInteger k, BigInteger n) - { - if (k.dataLength == 1 && k.data[0] == 0) - { - BigInteger[] result = new BigInteger[3]; - - result[0] = 0; result[1] = 2 % n; result[2] = 1 % n; - return result; - } - - // calculate constant = b^(2k) / m - // for Barrett Reduction - BigInteger constant = new BigInteger(); - - int nLen = n.dataLength << 1; - constant.data[nLen] = 0x00000001; - constant.dataLength = nLen + 1; - - constant = constant / n; - - // calculate values of s and t - int s = 0; - - for (int index = 0; index < k.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((k.data[index] & mask) != 0) - { - index = k.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = k >> s; - - //Console.WriteLine("s = " + s + " t = " + t); - return LucasSequenceHelper(P, Q, t, n, constant, s); - } - - - //*********************************************************************** - // Performs the calculation of the kth term in the Lucas Sequence. - // For details of the algorithm, see reference [9]. - // - // k must be odd. i.e LSB == 1 - //*********************************************************************** - - private static BigInteger[] LucasSequenceHelper(BigInteger P, BigInteger Q, - BigInteger k, BigInteger n, - BigInteger constant, int s) - { - BigInteger[] result = new BigInteger[3]; - - if ((k.data[0] & 0x00000001) == 0) - throw (new ArgumentException("Argument k must be odd.")); - - int numbits = k.BitCount(); - uint mask = (uint)0x1 << ((numbits & 0x1F) - 1); - - // v = v0, v1 = v1, u1 = u1, Q_k = Q^0 - - BigInteger v = 2 % n, Q_k = 1 % n, - v1 = P % n, u1 = Q_k; - bool flag = true; - - for (int i = k.dataLength - 1; i >= 0; i--) // iterate on the binary expansion of k - { - //Console.WriteLine("round"); - while (mask != 0) - { - if (i == 0 && mask == 0x00000001) // last bit - break; - - if ((k.data[i] & mask) != 0) // bit is set - { - // index doubling with addition - - u1 = (u1 * v1) % n; - - v = ((v * v1) - (P * Q_k)) % n; - v1 = BigInteger.BarrettReduction(v1 * v1, n, constant); - v1 = (v1 - ((Q_k * Q) << 1)) % n; - - if (flag) - flag = false; - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - - Q_k = (Q_k * Q) % n; - } - else - { - // index doubling - u1 = ((u1 * v) - Q_k) % n; - - v1 = ((v * v1) - (P * Q_k)) % n; - v = BigInteger.BarrettReduction(v * v, n, constant); - v = (v - (Q_k << 1)) % n; - - if (flag) - { - Q_k = Q % n; - flag = false; - } - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - } - - mask >>= 1; - } - mask = 0x80000000; - } - - // at this point u1 = u(n+1) and v = v(n) - // since the last bit always 1, we need to transform u1 to u(2n+1) and v to v(2n+1) - - u1 = ((u1 * v) - Q_k) % n; - v = ((v * v1) - (P * Q_k)) % n; - if (flag) - flag = false; - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - - Q_k = (Q_k * Q) % n; - - - for (int i = 0; i < s; i++) - { - // index doubling - u1 = (u1 * v) % n; - v = ((v * v) - (Q_k << 1)) % n; - - if (flag) - { - Q_k = Q % n; - flag = false; - } - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - } - - result[0] = u1; - result[1] = v; - result[2] = Q_k; - - return result; - } - - //#region IDisposable Members - - //public void Dispose() - //{ - // data = new uint[0]; - // data = null; - // GC.Collect(); - // GC.Collect(); - //} - - //#endregion - } -} diff --git a/SocketService.Framework.Client/Crypto/CentralAuthority.cs b/SocketService.Framework.Client/Crypto/CentralAuthority.cs deleted file mode 100644 index 5c1e81d..0000000 --- a/SocketService.Framework.Client/Crypto/CentralAuthority.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Crypto -{ - [Serializable] - public class CentralAuthority - { - // higher numbers result in more accuracy at the expense of processing time - private const int Confidence = 30; - - private readonly BigInteger _prime; - private readonly BigInteger _g; - private readonly int _bits = 64; - private readonly StrongNumberProvider _rand = new StrongNumberProvider(); - - /// - /// Initializes a new instance of the class. - /// - /// The protocol. - public CentralAuthority(CAKeyProtocol protocol) - { - _bits = (int)protocol; - _prime = BigInteger.GenPseudoPrime(_bits, Confidence, _rand); - _g = (BigInteger)7; - } - - /// - /// Initializes a new instance of the class. - /// - public CentralAuthority() - { - _prime = BigInteger.GenPseudoPrime(_bits, Confidence, _rand); - _g = (BigInteger)7; - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - public CentralAuthority(BigInteger prime, BigInteger g) - { - _prime = prime; - _g = g; - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - public CentralAuthority(byte [] prime, byte [] g) - { - _prime = new BigInteger(prime); - _g = new BigInteger(g); - } - - /// - /// Gets the provider. - /// - /// - public DiffieHellmanProvider GetProvider() - { - return new DiffieHellmanProvider( - _prime, - _g, - BigInteger.GenPseudoPrime(_bits, Confidence, _rand)); - } - - } - - public enum CAKeyProtocol - { - DH64 = 64, - DH128 = 128, - DH256 = 256, - DH512 = 512, - DH768 = 768, - DH1024 = 1024 - } -} diff --git a/SocketService.Framework.Client/Crypto/Crc32.cs b/SocketService.Framework.Client/Crypto/Crc32.cs deleted file mode 100644 index 4cb4986..0000000 --- a/SocketService.Framework.Client/Crypto/Crc32.cs +++ /dev/null @@ -1,123 +0,0 @@ -/* Copyright (c) 2009. Tom Kaminski - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. */ -// CRC32 Code deriving from HashAlgorithm -using System; -using System.Security.Cryptography; - -public class Crc32 : HashAlgorithm -{ - public const uint DefaultSeed = 0xffffffff; - - readonly static uint[] CrcTable = new uint[] { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D - }; - - uint crcValue = 0; - - public override void Initialize() - { - crcValue = 0; - } - - protected override void HashCore(byte[] buffer, int start, int length) - { - crcValue ^= DefaultSeed; - - unchecked - { - while (--length >= 0) - { - crcValue = CrcTable[(crcValue ^ buffer[start++]) & 0xFF] ^ (crcValue >> 8); - } - } - - crcValue ^= DefaultSeed; - } - protected override byte[] HashFinal() - { - this.HashValue = new byte[] { (byte)((crcValue >> 24) & 0xff), - (byte)((crcValue >> 16) & 0xff), - (byte)((crcValue >> 8) & 0xff), - (byte)(crcValue & 0xff) }; - return this.HashValue; - } - public uint CrcValue - { - get - { - return (uint)((HashValue[0] << 24) | (HashValue[1] << 16) | (HashValue[2] << 8) | HashValue[3]); - } - } - public override int HashSize - { - get { return 32; } - } -} diff --git a/SocketService.Framework.Client/Crypto/DiffieHellmanKey.cs b/SocketService.Framework.Client/Crypto/DiffieHellmanKey.cs deleted file mode 100644 index 59356a3..0000000 --- a/SocketService.Framework.Client/Crypto/DiffieHellmanKey.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Crypto -{ - /// - /// - /// - [Serializable] - public class DiffieHellmanKey - { - private readonly BigInteger _value; - private readonly BigInteger _g; - private readonly BigInteger _prime; - - private DiffieHellmanKey() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - /// The y. - public DiffieHellmanKey(BigInteger prime, BigInteger g, BigInteger y) - { - _g = g; - _prime = prime; - _value = y; - } - - /// - /// Gets the G. - /// - public BigInteger G - { - get { return _g; } - } - - /// - /// Gets the prime. - /// - public BigInteger Prime - { - get { return _prime; } - } - - /// - /// Gets the value. - /// - public BigInteger Value - { - get - { - return _value; - } - } - - /// - /// Convert to byte array. - /// - /// - public byte[] ToByteArray() - { - return _value.ToByteArray(); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - return _value.ToString(10); - } - } -} diff --git a/SocketService.Framework.Client/Crypto/DiffieHellmanProvider.cs b/SocketService.Framework.Client/Crypto/DiffieHellmanProvider.cs deleted file mode 100644 index 1fc3d1b..0000000 --- a/SocketService.Framework.Client/Crypto/DiffieHellmanProvider.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Crypto -{ - /// - /// - /// - public class DiffieHellmanProvider - { - private readonly BigInteger _prime; - private readonly BigInteger _g; - private readonly BigInteger _secret; - - protected DiffieHellmanProvider() - { - throw new NotImplementedException(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - /// The secret. - public DiffieHellmanProvider( - BigInteger prime, - BigInteger g, - BigInteger secret) - { - _prime = prime; - _g = g; - _secret = secret; - } - - /// - /// Gets the public key. - /// - public DiffieHellmanKey PublicKey - { - get - { - return new DiffieHellmanKey(_prime, _g, _g.ModPow(_secret, _prime)); - } - } - - /// - /// Creates the private key. - /// - /// The public key. - /// - public DiffieHellmanKey CreatePrivateKey(DiffieHellmanKey publicKey) - { - BigInteger yother = new BigInteger(publicKey.ToByteArray()); - return new DiffieHellmanKey(_prime, _g, yother.ModPow(_secret, _prime)); - } - - /// - /// Creates the private key. - /// - /// The public key. - /// - public DiffieHellmanKey CreatePrivateKey(byte[] publicKey) - { - BigInteger yother = new BigInteger(publicKey); - return new DiffieHellmanKey(_prime, _g, yother.ModPow(_secret, _prime)); - } - - /// - /// Imports the specified key data. - /// - /// The key data. - /// - public DiffieHellmanKey Import(byte[] keyData) - { - return new DiffieHellmanKey(_prime, _g, new BigInteger(keyData)); - } - } - -} diff --git a/SocketService.Framework.Client/Crypto/StringExtentions.cs b/SocketService.Framework.Client/Crypto/StringExtentions.cs deleted file mode 100644 index c828dad..0000000 --- a/SocketService.Framework.Client/Crypto/StringExtentions.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.Cryptography; -using System.IO; - -namespace SocketService.Framework.Client.Crypto -{ - public static class StringExtentions - { - private static byte[] salt = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xF1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xF1 }; - - /// - /// Encrypts the specified secret. - /// - /// The secret. - /// The key. - /// The iv. - /// - public static byte[] Encrypt(this string secret, byte[] key, out byte[] iv) - { - using( TripleDES des = new TripleDESCryptoServiceProvider()) - { - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, des.IV, 50); - des.Key = db.GetBytes(des.KeySize / 8); - iv = des.IV; - - // Encrypt the message - byte[] plaintextMessage = Encoding.UTF8.GetBytes(secret); - - using (MemoryStream ciphertext = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(ciphertext, des.CreateEncryptor(), CryptoStreamMode.Write)) - { - cs.Write(plaintextMessage, 0, plaintextMessage.Length); - } - - return ciphertext.ToArray(); - } - } - } - - /// - /// Decrypts the specified cipher. - /// - /// The cipher. - /// The key. - /// The iv. - /// - public static string Decrypt(this byte[] cipher, byte[] key, byte[] iv) - { - using (TripleDES aes = new TripleDESCryptoServiceProvider()) - { - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, iv, 50); - aes.Key = db.GetBytes(aes.KeySize / 8); - aes.IV = iv; - - // Encrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, aes.CreateDecryptor(), CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - } - } -} diff --git a/SocketService.Framework.Client/Crypto/StrongNumberProvider.cs b/SocketService.Framework.Client/Crypto/StrongNumberProvider.cs deleted file mode 100644 index f04b958..0000000 --- a/SocketService.Framework.Client/Crypto/StrongNumberProvider.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Security.Cryptography; - -namespace SocketService.Framework.Client.Crypto -{ - [Serializable] - public class StrongNumberProvider - { - private static RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider(); - - /// - /// Gets the next U int32. - /// - /// - public uint GetNextUInt32() - { - byte[] res = new byte[4]; - csp.GetBytes(res); - return BitConverter.ToUInt32(res, 0); - } - - /// - /// Gets the next int. - /// - /// - public int GetNextInt() - { - byte[] res = new byte[4]; - csp.GetBytes(res); - return BitConverter.ToInt32(res, 0); - } - - /// - /// Gets the next single. - /// - /// - public Single GetNextSingle() - { - float numerator = GetNextUInt32(); - float denominator = uint.MaxValue; - return numerator / denominator; - } - } -} diff --git a/SocketService.Framework.Client/Crypto/Wrapper.cs b/SocketService.Framework.Client/Crypto/Wrapper.cs deleted file mode 100644 index 6b23d2c..0000000 --- a/SocketService.Framework.Client/Crypto/Wrapper.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.IO; -using System.Security.Cryptography; - -namespace SocketService.Framework.Client.Crypto -{ - public class Wrapper : IDisposable - { - private readonly SymmetricAlgorithm _algorithm; - private readonly ICryptoTransform _transformer; - - private Wrapper() - { - throw new NotImplementedException(); - } - - private Wrapper(SymmetricAlgorithm algorithm, ICryptoTransform transform) - { - _algorithm = algorithm; - _transformer = transform; - } - - ~Wrapper() - { - Dispose(false); - } - - /// - /// Gets the IV. - /// - public byte[] IV - { - get { return _algorithm.IV; } - } - - /// - /// Creates the encryptor. - /// - /// Type of the alg. - /// The key. - /// The entropy. - /// - public static Wrapper CreateEncryptor(AlgorithmType algType, byte [] key, int entropy = 50) - { - SymmetricAlgorithm algorithm = null; - switch (algType) - { - case AlgorithmType.AES: - algorithm = new AesCryptoServiceProvider(); - break; - - case AlgorithmType.DES: - algorithm = new DESCryptoServiceProvider(); - break; - - case AlgorithmType.TripleDES: - algorithm = new TripleDESCryptoServiceProvider(); - break; - } - - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, algorithm.IV, entropy); - algorithm.Key = db.GetBytes(algorithm.KeySize / 8); - - return new Wrapper(algorithm, algorithm.CreateEncryptor()); - } - - /// - /// Creates the decryptor. - /// - /// Type of the alg. - /// The key. - /// The iv. - /// The entropy. - /// - public static Wrapper CreateDecryptor(AlgorithmType algType, byte[] key, byte[] iv, int entropy = 50) - { - SymmetricAlgorithm algorithm = null; - switch (algType) - { - case AlgorithmType.AES: - algorithm = new AesCryptoServiceProvider(); - break; - - case AlgorithmType.DES: - algorithm = new DESCryptoServiceProvider(); - break; - - case AlgorithmType.TripleDES: - algorithm = new TripleDESCryptoServiceProvider(); - break; - } - - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, iv, entropy); - algorithm.Key = db.GetBytes(algorithm.KeySize / 8); - algorithm.IV = iv; - - return new Wrapper(algorithm, algorithm.CreateDecryptor()); - } - - /// - /// Gets the crypto transformer. - /// - public ICryptoTransform CryptoTransformer - { - get - { - return _transformer; - } - - } - - /// - /// Encrypts the string. - /// - /// The secret. - /// - public byte[] EncryptString(string secret) - { - using (MemoryStream cipherText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(cipherText, _transformer, CryptoStreamMode.Write)) - { - byte[] plainText = Encoding.UTF8.GetBytes(secret); - cs.Write(plainText, 0, plainText.Length); - } - - return cipherText.ToArray(); - } - } - - /// - /// Encrypts the specified sensitive. - /// - /// The sensitive. - /// - public byte[] Encrypt(byte[] sensitive) - { - using (MemoryStream cipherStream = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(cipherStream, _transformer, CryptoStreamMode.Write)) - { - cs.Write(sensitive, 0, sensitive.Length); - } - - return cipherStream.ToArray(); - } - } - - /// - /// Decrypts the specified cipher. - /// - /// The cipher. - /// - public byte[] Decrypt(byte[] cipher) - { - // Decrypt the message - using (MemoryStream decrypted = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(decrypted, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return decrypted.ToArray(); - } - - } - - /// - /// Decrypts the string. - /// - /// The cipher string. - /// - public string DecryptString(string cipherString) - { - byte[] cipher = System.Text.Encoding.UTF8.GetBytes(cipherString); - - // Decrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - - /// - /// Decrypts the string. - /// - /// The cipher. - /// - public string DecryptString(byte [] cipher) - { - // Decrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - - private bool disposed = false; - - // Implement IDisposable. - // Do not make this method virtual. - // A derived class should not be able to override this method. - public void Dispose() - { - Dispose(true); - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SupressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - // Dispose(bool disposing) executes in two distinct scenarios. - // If disposing equals true, the method has been called directly - // or indirectly by a user's code. Managed and unmanaged resources - // can be disposed. - // If disposing equals false, the method has been called by the - // runtime from inside the finalizer and you should not reference - // other objects. Only unmanaged resources can be disposed. - protected virtual void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - _algorithm.Dispose(); - } - - // Note disposing has been done. - disposed = true; - - } - } - - } - - public enum AlgorithmType - { - AES, - DES, - TripleDES, - Rjindal, - None - } -} diff --git a/SocketService.Framework.Client/Data/Domain/Room.cs b/SocketService.Framework.Client/Data/Domain/Room.cs deleted file mode 100644 index 2c1d749..0000000 --- a/SocketService.Framework.Client/Data/Domain/Room.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Data.Domain -{ - public class Room - { - public Room() - { - Id = NextId(); - } - - private static int nextId = 0; - protected static int NextId() - { - return nextId++; - } - - private Dictionary _roomVariables = new Dictionary(); - private List _users = new List(); - - /// - /// Gets or sets the name. - /// - /// - /// The name. - /// - public string Name - { - get; - set; - } - - /// - /// Gets the variable. - /// - /// The name. - /// - public RoomVariable GetVariable(string name) - { - if (_roomVariables.ContainsKey(name)) - { - return _roomVariables[name]; - } - - return null; - } - - /// - /// Adds the variable. - /// - /// The name. - /// The so. - public void AddVariable(string name, RoomVariable so) - { - if (!_roomVariables.ContainsKey(name)) - { - _roomVariables.Add(name, so); - } - } - - public int Id { get; private set; } - - public List Variables - { - get { return _roomVariables.Values.ToList(); } - } - - public List Users { get { return _users.ToList(); } } - - public void AddUser(UserListEntry user) - { - if (!_users.Contains(user)) - { - _users.Add(user); - } - } - - public void RemoveUser(UserListEntry user) - { - if (_users.Contains(user)) - { - _users.Remove(user); - } - } - } -} diff --git a/SocketService.Framework.Client/Data/Domain/User.cs b/SocketService.Framework.Client/Data/Domain/User.cs deleted file mode 100644 index f009bfe..0000000 --- a/SocketService.Framework.Client/Data/Domain/User.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Data.Domain -{ - public class User - { - public string UserName - { - get; - set; - } - - public Room Room - { - get; - set; - } - - public Guid ClientKey - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Data/RoomRepository.cs b/SocketService.Framework.Client/Data/RoomRepository.cs deleted file mode 100644 index 5ef9fe6..0000000 --- a/SocketService.Framework.Client/Data/RoomRepository.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Data.Domain; - -namespace SocketService.Framework.Client.Data -{ - public class RoomRepository - { - private object _listLock = new object(); - private List _roomList = new List(); - - private static RoomRepository _instance = new RoomRepository(); - - /// - /// Gets the instance. - /// - public static RoomRepository Instance - { - get - { - if (_instance == null) - { - _instance = new RoomRepository(); - } - - return _instance; - } - } - /// - /// Adds the room. - /// - /// The room. - public void AddRoom(Room room) - { - lock (_listLock) - { - _roomList.Add(room); - } - } - - /// - /// Finds the name of the by. - /// - /// The name. - /// - public Room FindByName(string name) - { - lock (_listLock) - { - var query = from room in _roomList - where room.Name == name - select room; - - return query.FirstOrDefault(); - } - } - } -} diff --git a/SocketService.Framework.Client/Data/UserRepository.cs b/SocketService.Framework.Client/Data/UserRepository.cs deleted file mode 100644 index d57a68f..0000000 --- a/SocketService.Framework.Client/Data/UserRepository.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Client.Data.Domain; - -namespace SocketService.Framework.Client.Data -{ - public class UserRepository - { - private object _listLock = new object(); - private List _userList = new List(); - - private static UserRepository _instance = new UserRepository(); - - /// - /// Gets the instance. - /// - public static UserRepository Instance - { - get - { - if (_instance == null) - { - _instance = new UserRepository(); - } - - return _instance; - } - } - - /// - /// Finds the users by room. - /// - /// The roomname. - /// - public List FindUsersByRoom(string roomname) - { - lock (_listLock) - { - var query = from user in _userList - where user.Room != null && user.Room.Name == roomname - select user; - - return query.ToList(); - } - } - - public List FindClientKeysByRoomFiltered(string roomname, Guid filteredClient) - { - lock (_listLock) - { - var query = from user in _userList - where user.Room != null && user.Room.Name == roomname && user.ClientKey != filteredClient - select user.ClientKey; - - return query.ToList(); - } - } - - /// - /// Finds the name of the user by. - /// - /// The username. - /// - public User FindUserByName(string username) - { - lock (_listLock) - { - var query = from user in _userList - where user.UserName == username - select user; - - return query.FirstOrDefault(); - } - } - - /// - /// Finds the user by client key. - /// - /// The client key. - /// - public User FindUserByClientKey(Guid clientKey) - { - lock (_listLock) - { - var query = from user in _userList - where user.ClientKey == clientKey - select user; - - return query.FirstOrDefault(); - } - } - - /// - /// Adds the user. - /// - /// The user. - public void AddUser(User user) - { - lock (_listLock) - { - _userList.Add(user); - } - } - - /// - /// Removes the user. - /// - /// The user. - public void RemoveUser(User user) - { - lock (_listLock) - { - _userList.Remove(user); - } - } - } -} diff --git a/SocketService.Framework.Client/Event/IEvent.cs b/SocketService.Framework.Client/Event/IEvent.cs deleted file mode 100644 index 93d0f05..0000000 --- a/SocketService.Framework.Client/Event/IEvent.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Event -{ - public interface IEvent - { - string EventName - { - get; - } - - } -} diff --git a/SocketService.Framework.Client/Event/JoinRoomEvent.cs b/SocketService.Framework.Client/Event/JoinRoomEvent.cs deleted file mode 100644 index 5dbcc19..0000000 --- a/SocketService.Framework.Client/Event/JoinRoomEvent.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Event -{ - [Serializable] - public class JoinRoomEvent : IEvent - { - public long ZoneId { get; set; } - public long RoomId { get; set; } - public string RoomName { get; set; } - public string RoomDescription { get; set; } - public bool Protected { get; set; } - public int Capacity { get; set; } - public bool Hidden { get; set; } - - public string EventName - { - get { return "JoinRoomEvent"; } - } - - public SharedObject [] RoomVariables { get; set; } - - public UserListEntry [] Users { get; set; } - } -} diff --git a/SocketService.Framework.Client/Event/LeaveRoomEvent.cs b/SocketService.Framework.Client/Event/LeaveRoomEvent.cs deleted file mode 100644 index 262e271..0000000 --- a/SocketService.Framework.Client/Event/LeaveRoomEvent.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Event -{ - [Serializable] - public class LeaveRoomEvent : IEvent - { - #region IEvent Members - - public string EventName - { - get { return "LeaveRoomEvent"; } - } - - #endregion - - public int RoomId { get; set; } - public string UserName { get; set; } - } -} diff --git a/SocketService.Framework.Client/Event/PublicMessageEvent.cs b/SocketService.Framework.Client/Event/PublicMessageEvent.cs deleted file mode 100644 index f56014c..0000000 --- a/SocketService.Framework.Client/Event/PublicMessageEvent.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Event -{ - [Serializable] - public class PublicMessageEvent : IEvent - { - public string EventName - { - get { return "PublicMessageEvent"; } - } - - public int ZoneId - { - get; - set; - } - - public int RoomId - { - get; - set; - } - - public string UserName - { - get; - set; - } - - public string Message - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Event/RoomUserUpdateEvent.cs b/SocketService.Framework.Client/Event/RoomUserUpdateEvent.cs deleted file mode 100644 index 3131819..0000000 --- a/SocketService.Framework.Client/Event/RoomUserUpdateEvent.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Event -{ - [Serializable] - public class RoomUserUpdateEvent : IEvent - { - public string EventName - { - get { return "RoomUserUpdateEvent"; } - } - - public long RoomId { get; set; } - public long ZoneId { get; set; } - public RoomUserUpdateAction Action { get; set; } - public string UserName { get; set; } - - public string RoomName { get; set; } - } - - public enum RoomUserUpdateAction - { - AddUser, - DeleteUser - } -} diff --git a/SocketService.Framework.Client/Event/RoomVariableUpdateEvent.cs b/SocketService.Framework.Client/Event/RoomVariableUpdateEvent.cs deleted file mode 100644 index 66b8a74..0000000 --- a/SocketService.Framework.Client/Event/RoomVariableUpdateEvent.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Event -{ - [Serializable] - public class RoomVariableUpdateEvent : IEvent - { - public string EventName - { - get { return "RoomVariableUpdateEvent"; } - } - - public long ZoneId { get; set; } - public long RoomId { get; set; } - public string Name { get; set; } - public SharedObject Value { get; set; } - public RoomVariableUpdateAction Action { get; set; } - } - - public enum RoomVariableUpdateAction - { - Add, - Delete, - Update - } -} diff --git a/SocketService.Framework.Client/Properties/AssemblyInfo.cs b/SocketService.Framework.Client/Properties/AssemblyInfo.cs deleted file mode 100644 index f0424b4..0000000 --- a/SocketService.Framework.Client/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SocketService.Framework.Client")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SocketService.Framework.Client")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4385a4c2-dbde-4325-bd29-2900251c0a45")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketService.Framework.Client/Request/ClientRequest.cs b/SocketService.Framework.Client/Request/ClientRequest.cs deleted file mode 100644 index 1c86051..0000000 --- a/SocketService.Framework.Client/Request/ClientRequest.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class ClientRequest //: IRequest - { - private readonly byte[] _publicKey; - private readonly EncryptionType _encryption; - private readonly DateTime _timestamp; - private readonly uint _crc32; - private readonly byte [] _request; - - /// - /// Initializes a new instance of the class. - /// - /// The encryption public key. - /// The encryption. - /// The time stamp. - /// The CR C32. - /// The request. - public ClientRequest(byte[] EncryptionPublicKey, - EncryptionType Encryption, DateTime TimeStamp, - uint CRC32, byte [] Request) - { - _publicKey = EncryptionPublicKey; - _encryption = Encryption; - _timestamp = TimeStamp; - _crc32 = CRC32; - _request = Request; - } - - /// - /// Gets the encryption public key. - /// - public byte[] EncryptionPublicKey - { - get { return _publicKey; } - } - - /// - /// Gets the encryption. - /// - public EncryptionType Encryption - { - get { return _encryption; } - } - - /// - /// Gets the time stamp. - /// - public DateTime TimeStamp - { - get { return _timestamp; } - } - - /// - /// Gets the CR C32. - /// - public uint CRC32 - { - get { return _crc32; } - } - - /// - /// Gets the request data. - /// - public byte[] RequestData - { - get { return _request; } - } - } - - public enum EncryptionType - { - - /// - AES, - - /// - DES, - - /// - TripleDES, - - /// - Rijindal, - None, - } -} diff --git a/SocketService.Framework.Client/Request/CreateRoomRequest.cs b/SocketService.Framework.Client/Request/CreateRoomRequest.cs deleted file mode 100644 index 69193e5..0000000 --- a/SocketService.Framework.Client/Request/CreateRoomRequest.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - /// - /// Creates a room if it doesn't exist and switches requestor to that room - /// - public class CreateRoomRequest - { - public string ZoneName - { - get; - set; - } - - /// - /// Gets or sets the name of the room. - /// - /// - /// The name of the room. - /// - public string RoomName - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/CreateRoomVariableRequest.cs b/SocketService.Framework.Client/Request/CreateRoomVariableRequest.cs deleted file mode 100644 index 0aa69ab..0000000 --- a/SocketService.Framework.Client/Request/CreateRoomVariableRequest.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class CreateRoomVariableRequest - { - public int ZoneId - { - get; - set; - } - - /// - /// Gets or sets the room. - /// - /// - /// The room. - /// - public int RoomId - { - get; - set; - } - - /// - /// Gets or sets the name of the variable. - /// - /// - /// The name of the variable. - /// - public string Name - { - get; - set; - } - - /// - /// Gets or sets the value. - /// - /// - /// The value. - /// - public SharedObject Value - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/DeleteRoomVariableRequest.cs b/SocketService.Framework.Client/Request/DeleteRoomVariableRequest.cs deleted file mode 100644 index 65e0779..0000000 --- a/SocketService.Framework.Client/Request/DeleteRoomVariableRequest.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class DeleteRoomVariableRequest - { - public int ZoneId - { - get; - set; - } - - - public int RoomId - { - get; - set; - } - - public string Name - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/GetCentralAuthorityRequest.cs b/SocketService.Framework.Client/Request/GetCentralAuthorityRequest.cs deleted file mode 100644 index a9d6f44..0000000 --- a/SocketService.Framework.Client/Request/GetCentralAuthorityRequest.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Crypto; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class GetCentralAuthorityRequest - { - /// - /// Gets or sets the central authority. - /// - /// - /// The central authority. - /// - public CentralAuthority CentralAuthority - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/GetRoomVariableRequest.cs b/SocketService.Framework.Client/Request/GetRoomVariableRequest.cs deleted file mode 100644 index 08a7021..0000000 --- a/SocketService.Framework.Client/Request/GetRoomVariableRequest.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class GetRoomVariableRequest - { - public int ZoneId - { - get; - set; - } - - /// - /// Gets or sets the name of the room. - /// - /// - /// The name of the room. - /// - public int RoomId - { - get; - set; - } - - /// - /// Gets or sets the name of the variable. - /// - /// - /// The name of the variable. - /// - public string VariableName - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/LoginRequest.cs b/SocketService.Framework.Client/Request/LoginRequest.cs deleted file mode 100644 index 1115ed9..0000000 --- a/SocketService.Framework.Client/Request/LoginRequest.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class LoginRequest - { - /// - /// Gets or sets the name of the login. - /// - /// - /// The name of the login. - /// - public string LoginName - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Request/NegotiateKeysRequest.cs b/SocketService.Framework.Client/Request/NegotiateKeysRequest.cs deleted file mode 100644 index 8f99b27..0000000 --- a/SocketService.Framework.Client/Request/NegotiateKeysRequest.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class NegotiateKeysRequest - { - /// - /// Initializes a new instance of the class. - /// - public NegotiateKeysRequest() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The key. - public NegotiateKeysRequest(byte[] key) - { - PublicKey = key; - } - - /// - /// Gets or sets the public key. - /// - /// - /// The public key. - /// - public byte[] PublicKey - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Request/PublicMessageRequest.cs b/SocketService.Framework.Client/Request/PublicMessageRequest.cs deleted file mode 100644 index 980253e..0000000 --- a/SocketService.Framework.Client/Request/PublicMessageRequest.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class PublicMessageRequest - { - public int ZoneId - { - get; - set; - } - - public int RoomId - { - get; - set; - } - - public string User - { - get; - set; - } - - public string Message - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Request/UpdateRoomVariableRequest.cs b/SocketService.Framework.Client/Request/UpdateRoomVariableRequest.cs deleted file mode 100644 index dc638b8..0000000 --- a/SocketService.Framework.Client/Request/UpdateRoomVariableRequest.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Request -{ - [Serializable] - public class UpdateRoomVariableRequest - { - public int ZoneId - { - get; - set; - } - - /// - /// Gets or sets the room. - /// - /// - /// The room. - /// - public int RoomId - { - get; - set; - } - - /// - /// Gets or sets the name of the variable. - /// - /// - /// The name of the variable. - /// - public string Name - { - get; - set; - } - - /// - /// Gets or sets the value. - /// - /// - /// The value. - /// - public SharedObject Value - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Response/ConnectionResponse.cs b/SocketService.Framework.Client/Response/ConnectionResponse.cs deleted file mode 100644 index 5103356..0000000 --- a/SocketService.Framework.Client/Response/ConnectionResponse.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - public class ConnectionResponse : EventArgs - { - /// - /// Gets or sets a value indicating whether this is success. - /// - /// - /// true if success; otherwise, false. - /// - public bool Success - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Response/DeleteRoomVariableResponse.cs b/SocketService.Framework.Client/Response/DeleteRoomVariableResponse.cs deleted file mode 100644 index 1ec0869..0000000 --- a/SocketService.Framework.Client/Response/DeleteRoomVariableResponse.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class DeleteRoomVariableResponse : IResponse - { - public string Room - { - get; - set; - } - - public string Name - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Response/GetRoomVariableResponse.cs b/SocketService.Framework.Client/Response/GetRoomVariableResponse.cs deleted file mode 100644 index 48a1a4d..0000000 --- a/SocketService.Framework.Client/Response/GetRoomVariableResponse.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class GetRoomVariableResponse : IResponse - { - public long ZoneId - { - get; - set; - } - - public long RoomId - { - get; - set; - } - - public string Name - { - get; - set; - } - - public SharedObject Value - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Response/IResponse.cs b/SocketService.Framework.Client/Response/IResponse.cs deleted file mode 100644 index ed0ec42..0000000 --- a/SocketService.Framework.Client/Response/IResponse.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - /// - /// IResponse is a marker interface - /// - public interface IResponse - { - } -} diff --git a/SocketService.Framework.Client/Response/ListUsersInRoomResponse.cs b/SocketService.Framework.Client/Response/ListUsersInRoomResponse.cs deleted file mode 100644 index 31b6bb1..0000000 --- a/SocketService.Framework.Client/Response/ListUsersInRoomResponse.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class ListUsersInRoomResponse - { - /// - /// Gets or sets the users. - /// - /// - /// The users. - /// - public ServerUser[] Users - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/Response/LoginResponse.cs b/SocketService.Framework.Client/Response/LoginResponse.cs deleted file mode 100644 index 8ce5bff..0000000 --- a/SocketService.Framework.Client/Response/LoginResponse.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class LoginResponse : IResponse - { - /// - /// Gets or sets a value indicating whether this is success. - /// - /// - /// true if success; otherwise, false. - /// - public bool Success - { - get; - set; - } - - public string UserName - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Response/NegotiateKeysResponse.cs b/SocketService.Framework.Client/Response/NegotiateKeysResponse.cs deleted file mode 100644 index 56ef6d9..0000000 --- a/SocketService.Framework.Client/Response/NegotiateKeysResponse.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class NegotiateKeysResponse : IResponse - { - /// - /// Gets or sets the remote public key. - /// - /// - /// The remote public key. - /// - public byte[] RemotePublicKey - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Response/ServerMessage.cs b/SocketService.Framework.Client/Response/ServerMessage.cs deleted file mode 100644 index 28d89db..0000000 --- a/SocketService.Framework.Client/Response/ServerMessage.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class ServerMessage - { - private readonly string _message; - /// - /// Initializes a new instance of the class. - /// - /// The message. - public ServerMessage(string message) - { - _message = message; - } - - /// - /// Initializes a new instance of the class. - /// - /// The format. - /// The args. - public ServerMessage(string format, params object[] args) - { - _message = string.Format(format, args); - } - - /// - /// Gets the message. - /// - public string Message - { - get - { - return _message; - } - } - } -} diff --git a/SocketService.Framework.Client/Response/UpdateRoomVariableResponse.cs b/SocketService.Framework.Client/Response/UpdateRoomVariableResponse.cs deleted file mode 100644 index c8f4764..0000000 --- a/SocketService.Framework.Client/Response/UpdateRoomVariableResponse.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.SharedObjects; - -namespace SocketService.Framework.Client.Response -{ - [Serializable] - public class UpdateRoomVariableResponse : IResponse - { - public string Room - { - get; - set; - } - - public string Name - { - get; - set; - } - - public RoomVariable Value - { - get; - set; - } - - } -} diff --git a/SocketService.Framework.Client/Serialize/ObjectSerialize.cs b/SocketService.Framework.Client/Serialize/ObjectSerialize.cs deleted file mode 100644 index 79ad44f..0000000 --- a/SocketService.Framework.Client/Serialize/ObjectSerialize.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; - -namespace SocketService.Framework.Client.Serialize -{ - static public class ObjectSerialize - { - /// - /// Serializes the specified graph. - /// - /// The graph. - /// - static public byte[] Serialize(object graph) - { - using (MemoryStream ms = new MemoryStream()) - { - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Serialize(ms, graph); - - return ms.ToArray(); - } - } - - /// - /// Deserializes the specified data. - /// - /// The data. - /// - static public object Deserialize(byte[] data) - { - using (MemoryStream ms = new MemoryStream(data)) - { - BinaryFormatter formatter = new BinaryFormatter(); - return formatter.Deserialize(ms); - } - } - - /// - /// Deserializes the specified data. - /// - /// - /// The data. - /// - static public T Deserialize(byte[] data) where T : class - { - using (MemoryStream ms = new MemoryStream(data)) - { - BinaryFormatter formatter = new BinaryFormatter(); - return formatter.Deserialize(ms) as T; - } - } - - } -} diff --git a/SocketService.Framework.Client/SharedObjects/SharedObject.cs b/SocketService.Framework.Client/SharedObjects/SharedObject.cs deleted file mode 100644 index 6073ff8..0000000 --- a/SocketService.Framework.Client/SharedObjects/SharedObject.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Collections; - -namespace SocketService.Framework.SharedObjects -{ - [Serializable] - public class SharedObject - { - private Hashtable data = new Hashtable(); - - public SharedObject() - { - } - - public SharedObject(object value) - { - SharedObjectDataType dt = DataTypeFromType(value.GetType()); - SetElementValue("", value, dt); - } - - private SharedObjectDataType DataTypeFromType(Type t) - { - if (t.IsAssignableFrom(typeof(string))) - { - return SharedObjectDataType.String; - } - else if (t.IsAssignableFrom(typeof(int))) - { - return SharedObjectDataType.Integer; - } - else if(t.IsAssignableFrom(typeof(long))) - { - return SharedObjectDataType.Long; - } - else if (t.IsAssignableFrom(typeof(double))) - { - return SharedObjectDataType.Double; - } - else if(t.IsAssignableFrom(typeof(byte))) - { - return SharedObjectDataType.Byte; - } - else if (t.IsAssignableFrom(typeof(char))) - { - return SharedObjectDataType.Character; - } - else if (t.IsClass) - { - return SharedObjectDataType.BzObject; - } - else if( t.IsArray) - { - // check array type - return DataTypeFromType(t.GetElementType()); - } - else - { - return SharedObjectDataType.BzObject; - } - - - } - - /// - /// Gets the read only copy. - /// - /// - public SharedObjectRO GetReadOnlyCopy() - { - return new SharedObjectRO(data); - } - - /// - /// Sets the element value. - /// - /// Name of the element. - /// The value. - /// Type of the data. - public void SetElementValue(string elementName, object value, SharedObjectDataType dataType) - { - if (!data.ContainsKey(elementName)) - { - data.Add(elementName, new SharedObjectDataHolder()); - } - - (data[elementName] as SharedObjectDataHolder).Value = value; - - (data[elementName] as SharedObjectDataHolder).DataType = dataType; - - } - - - /// - /// Gets the value for element. - /// - /// Name of the element. - /// - public object GetValueForElement(string elementName) - { - object value = null; - if (data.ContainsKey(elementName)) - { - value = (data[elementName] as SharedObjectDataHolder).Value; - } - - return value; - } - - /// - /// Gets the data type for element. - /// - /// Name of the element. - /// - public SharedObjectDataType GetDataTypeForElement(string elementName) - { - if( !data.ContainsKey(elementName) ) - { - throw new ArgumentException(); - } - - return (data[elementName] as SharedObjectDataHolder).DataType; - } - } -} diff --git a/SocketService.Framework.Client/SharedObjects/SharedObjectDataHolder.cs b/SocketService.Framework.Client/SharedObjects/SharedObjectDataHolder.cs deleted file mode 100644 index 295bf32..0000000 --- a/SocketService.Framework.Client/SharedObjects/SharedObjectDataHolder.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.SharedObjects -{ - [Serializable] - public class SharedObjectDataHolder - { - private int dataType; - private object value; - - /// - /// Gets or sets the value. - /// - /// - /// The value. - /// - public object Value - { - get { return this.value; } - set { SetValue(value); } - } - - /// - /// Gets or sets the type of the data. - /// - /// - /// The type of the data. - /// - public SharedObjectDataType DataType - { - get { return (SharedObjectDataType)dataType; } - set { dataType = (int)value; } - } - - private void SetValue(object value) - { - this.value = value; - - // default to an object - int dataType = (int)SharedObjectDataType.BzObject; - - if (value != null) - { - if (value is Int32) - { - dataType = (int)SharedObjectDataType.Integer; - } - else if (value is Int16) - { - dataType = (int)SharedObjectDataType.Short; - } - else if (value is Int64) - { - dataType = (int)SharedObjectDataType.Long; - } - else if (value is String) - { - dataType = (int)SharedObjectDataType.String; - } - else if (value is float) - { - dataType = (int)SharedObjectDataType.Float; - } - else if (value is Double) - { - dataType = (int)SharedObjectDataType.Double; - } - else if (value is Char) - { - dataType = (int)SharedObjectDataType.Character; - } - else if (value is Byte) - { - dataType = (int)SharedObjectDataType.Byte; - } - else if (value is Array) - { - Type valueType = value.GetType(); - - if (valueType.GetElementType() == typeof(int)) - { - dataType = (int)SharedObjectDataType.IntegerArray; - } - else if (value is Int16) - { - dataType = (int)SharedObjectDataType.ShortArray; - } - else if (value is Int64) - { - dataType = (int)SharedObjectDataType.LongArray; - } - else if (value is String) - { - dataType = (int)SharedObjectDataType.StringArray; - } - else if (value is float) - { - dataType = (int)SharedObjectDataType.FloatArray; - } - else if (value is Double) - { - dataType = (int)SharedObjectDataType.DoubleArray; - } - else if (value is Char) - { - dataType = (int)SharedObjectDataType.CharacterArray; - } - else if (value is Byte) - { - dataType = (int)SharedObjectDataType.ByteArray; - } - } - } - } - } -} diff --git a/SocketService.Framework.Client/SharedObjects/SharedObjectDataType.cs b/SocketService.Framework.Client/SharedObjects/SharedObjectDataType.cs deleted file mode 100644 index 2d8dfef..0000000 --- a/SocketService.Framework.Client/SharedObjects/SharedObjectDataType.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.SharedObjects -{ - public enum SharedObjectDataType : int - { - Integer, - Double, - Float, - String, - Boolean, - Byte, - Character, - Long, - Short, - BzObject, - IntegerArray, - DoubleArray, - FloatArray, - StringArray, - BooleanArray, - ByteArray, - CharacterArray, - LongArray, - ShortArray, - BzObjectArray - } -} diff --git a/SocketService.Framework.Client/SharedObjects/SharedObjectRO.cs b/SocketService.Framework.Client/SharedObjects/SharedObjectRO.cs deleted file mode 100644 index 49bb5c2..0000000 --- a/SocketService.Framework.Client/SharedObjects/SharedObjectRO.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Collections; - -namespace SocketService.Framework.SharedObjects -{ - - [Serializable] - public class SharedObjectRO - { - SharedObject innerObject; - private Hashtable data; - - /// - /// Initializes a new instance of the class. - /// - /// The name. - /// The value. - /// Type of the data. - public SharedObjectRO(string name, object value, SharedObjectDataType dataType) - { - innerObject = new SharedObject(); - innerObject.SetElementValue(name, value, dataType); - } - - /// - /// Initializes a new instance of the class. - /// - /// The data. - public SharedObjectRO(Hashtable data) - { - this.data = data; - } - - /// - /// Gets the value for element. - /// - /// The name. - /// - public object GetValueForElement(string name) - { - return innerObject.GetValueForElement(name); - } - } -} diff --git a/SocketService.Framework.Client/SharedObjects/UserListEntry.cs b/SocketService.Framework.Client/SharedObjects/UserListEntry.cs deleted file mode 100644 index e6348fd..0000000 --- a/SocketService.Framework.Client/SharedObjects/UserListEntry.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.SharedObjects -{ - [Serializable] - public class UserListEntry - { - public string UserName - { - get; - set; - } - } -} diff --git a/SocketService.Framework.Client/SocketService.Framework.Client.csproj b/SocketService.Framework.Client/SocketService.Framework.Client.csproj deleted file mode 100644 index 1a02300..0000000 --- a/SocketService.Framework.Client/SocketService.Framework.Client.csproj +++ /dev/null @@ -1,92 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {93FD4F32-5214-40E3-8E36-5B4E354F10C4} - Library - Properties - SocketService.Framework.Client - SocketService.Framework.Client - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {4138075A-49CD-4A46-92CB-DFF64A0BB0B6} - SocketService.Crypto - - - - - \ No newline at end of file diff --git a/SocketService.Framework.Client/Sockets/ZipSocket.cs b/SocketService.Framework.Client/Sockets/ZipSocket.cs deleted file mode 100644 index 73f0b81..0000000 --- a/SocketService.Framework.Client/Sockets/ZipSocket.cs +++ /dev/null @@ -1,170 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Net.Sockets; -using System.Net; -using System.IO; -using System.IO.Compression; -using System.Threading; - -namespace SocketService.Framework.Client.Sockets -{ - public class ZipSocket - { - private Mutex _sendMutex = new Mutex(); - /// - /// Initializes a new instance of the class. - /// - /// The socket. - /// The client id. - public ZipSocket(Socket socket, Guid clientId) - { - ClientId = clientId; - RawSocket = socket; - RemoteAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(); - } - - /// - /// Gets the raw socket. - /// - public Socket RawSocket - { - get; - private set; - } - - /// - /// Sends the data. - /// - /// The data. - public virtual void SendData(string data) - { - SendData(Encoding.UTF8.GetBytes(data)); - } - - /// - /// Sends the data. - /// - /// The buffer. - public virtual void SendData(byte[] buffer) - { - _sendMutex.WaitOne(); - try - { - - RawSocket.Send(Compress(buffer)); - } - finally - { - _sendMutex.ReleaseMutex(); - } - - } - - /// - /// Closes this instance. - /// - public void Close() - { - RawSocket.Shutdown(SocketShutdown.Both); - RawSocket.Close(); - } - - /// - /// Determines whether the specified socket is equal. - /// - /// The socket. - /// - /// true if the specified socket is equal; otherwise, false. - /// - public bool IsEqual(Socket socket) - { - return socket == RawSocket; - } - - /// - /// Gets the client id. - /// - public Guid ClientId - { - get; - private set; - } - - /// - /// Gets the remote address. - /// - public string RemoteAddress - { - get; - private set; - } - - /// - /// Receives the data. - /// - /// - public byte[] ReceiveData() - { - byte[] zippedData = new byte[RawSocket.Available]; - RawSocket.Receive(zippedData); - return Decompress(zippedData); - } - - /// - /// Compresses the specified data. - /// - /// The data. - /// - private byte[] Compress(byte[] data) - { - using (MemoryStream msData = new MemoryStream()) - { - using (MemoryStream ms = new MemoryStream(data)) - { - using (GZipStream gz = new GZipStream(msData, CompressionMode.Compress)) - { - byte[] bytes = new byte[4096]; - int n; - while ((n = ms.Read(bytes, 0, bytes.Length)) != 0) - { - gz.Write(bytes, 0, n); - } - } - } - - return msData.ToArray(); - } - - } - - /// - /// Decompresses the specified data. - /// - /// The data. - /// - private byte[] Decompress(byte[] data) - { - using (MemoryStream ms = new MemoryStream(data)) - { - using (GZipStream gs = new GZipStream(ms, CompressionMode.Decompress)) - { - using (MemoryStream msOut = new MemoryStream()) - { - byte[] bytes = new byte[4096]; - int n; - - while ((n = gs.Read(bytes, 0, bytes.Length)) != 0) - { - msOut.Write(bytes, 0, n); - } - - return msOut.ToArray(); - } - } - } - } - - } -} diff --git a/SocketService.Framework.Crypto/BigInteger.cs b/SocketService.Framework.Crypto/BigInteger.cs deleted file mode 100644 index ebfe884..0000000 --- a/SocketService.Framework.Crypto/BigInteger.cs +++ /dev/null @@ -1,3035 +0,0 @@ -//************************************************************************************ -// BigInteger Class Version 1.03 -// -// Copyright (c) 2002 Chew Keong TAN -// All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, and/or sell copies of the Software, and to permit persons -// to whom the Software is furnished to do so, provided that the above -// copyright notice(s) and this permission notice appear in all copies of -// the Software and that both the above copyright notice(s) and this -// permission notice appear in supporting documentation. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -// OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -// HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL -// INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING -// FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, -// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION -// WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -// -// -// Disclaimer -// ---------- -// Although reasonable care has been taken to ensure the correctness of this -// implementation, this code should never be used in any application without -// proper verification and testing. I disclaim all liability and responsibility -// to any person or entity with respect to any loss or damage caused, or alleged -// to be caused, directly or indirectly, by the use of this BigInteger class. -// -// Comments, bugs and suggestions to -// (http://www.codeproject.com/csharp/biginteger.asp) -// -// -// Overloaded Operators +, -, *, /, %, >>, <<, ==, !=, >, <, >=, <=, &, |, ^, ++, --, ~ -// -// Features -// -------- -// 1) Arithmetic operations involving large signed integers (2's complement). -// 2) Primality test using Fermat little theorm, Rabin Miller's method, -// Solovay Strassen's method and Lucas strong pseudoprime. -// 3) Modulo exponential with Barrett's reduction. -// 4) Inverse modulo. -// 5) Pseudo prime generation. -// 6) Co-prime generation. -// -// -// Known Problem -// ------------- -// This pseudoprime passes my implementation of -// primality test but failed in JDK's isProbablePrime test. -// -// byte[] pseudoPrime1 = { (byte)0x00, -// (byte)0x85, (byte)0x84, (byte)0x64, (byte)0xFD, (byte)0x70, (byte)0x6A, -// (byte)0x9F, (byte)0xF0, (byte)0x94, (byte)0x0C, (byte)0x3E, (byte)0x2C, -// (byte)0x74, (byte)0x34, (byte)0x05, (byte)0xC9, (byte)0x55, (byte)0xB3, -// (byte)0x85, (byte)0x32, (byte)0x98, (byte)0x71, (byte)0xF9, (byte)0x41, -// (byte)0x21, (byte)0x5F, (byte)0x02, (byte)0x9E, (byte)0xEA, (byte)0x56, -// (byte)0x8D, (byte)0x8C, (byte)0x44, (byte)0xCC, (byte)0xEE, (byte)0xEE, -// (byte)0x3D, (byte)0x2C, (byte)0x9D, (byte)0x2C, (byte)0x12, (byte)0x41, -// (byte)0x1E, (byte)0xF1, (byte)0xC5, (byte)0x32, (byte)0xC3, (byte)0xAA, -// (byte)0x31, (byte)0x4A, (byte)0x52, (byte)0xD8, (byte)0xE8, (byte)0xAF, -// (byte)0x42, (byte)0xF4, (byte)0x72, (byte)0xA1, (byte)0x2A, (byte)0x0D, -// (byte)0x97, (byte)0xB1, (byte)0x31, (byte)0xB3, -// }; -// -// -// Change Log -// ---------- -// 1) September 23, 2002 (Version 1.03) -// - Fixed operator- to give correct data length. -// - Added Lucas sequence generation. -// - Added Strong Lucas Primality test. -// - Added integer square root method. -// - Added setBit/unsetBit methods. -// - New isProbablePrime() method which do not require the -// confident parameter. -// -// 2) August 29, 2002 (Version 1.02) -// - Fixed bug in the exponentiation of negative numbers. -// - Faster modular exponentiation using Barrett reduction. -// - Added getBytes() method. -// - Fixed bug in ToHexString method. -// - Added overloading of ^ operator. -// - Faster computation of Jacobi symbol. -// -// 3) August 19, 2002 (Version 1.01) -// - Big integer is stored and manipulated as unsigned integers (4 bytes) instead of -// individual bytes this gives significant performance improvement. -// - Updated Fermat's Little Theorem test to use a^(p-1) mod p = 1 -// - Added isProbablePrime method. -// - Updated documentation. -// -// 4) August 9, 2002 (Version 1.0) -// - Initial Release. -// -// -// References -// [1] D. E. Knuth, "Seminumerical Algorithms", The Art of Computer Programming Vol. 2, -// 3rd Edition, Addison-Wesley, 1998. -// -// [2] K. H. Rosen, "Elementary Number Theory and Its Applications", 3rd Ed, -// Addison-Wesley, 1993. -// -// [3] B. Schneier, "Applied Cryptography", 2nd Ed, John Wiley & Sons, 1996. -// -// [4] A. Menezes, P. van Oorschot, and S. Vanstone, "Handbook of Applied Cryptography", -// CRC Press, 1996, www.cacr.math.uwaterloo.ca/hac -// -// [5] A. Bosselaers, R. Govaerts, and J. Vandewalle, "Comparison of Three Modular -// Reduction Functions," Proc. CRYPTO'93, pp.175-186. -// -// [6] R. Baillie and S. S. Wagstaff Jr, "Lucas Pseudoprimes", Mathematics of Computation, -// Vol. 35, No. 152, Oct 1980, pp. 1391-1417. -// -// [7] H. C. Williams, "Édouard Lucas and Primality Testing", Canadian Mathematical -// Society Series of Monographs and Advance Texts, vol. 22, John Wiley & Sons, New York, -// NY, 1998. -// -// [8] P. Ribenboim, "The new book of prime number records", 3rd edition, Springer-Verlag, -// New York, NY, 1995. -// -// [9] M. Joye and J.-J. Quisquater, "Efficient computation of full Lucas sequences", -// Electronics Letters, 32(6), 1996, pp 537-538. -// -//************************************************************************************ - -using System; -using System.Collections.Generic; -using System.Text; - -namespace SocketService.Crypto -{ - [Serializable] - public class BigInteger //: IDisposable - { - // maximum length of the BigInteger in uint (4 bytes) - // change this to suit the required level of precision. - - public const int MaxLength = 180; - - // primes smaller than 2000 to test the generated prime number - - public static readonly int[] primesBelow2000 = { - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, - 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, - 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, - 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, - 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, - 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, - 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, - 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, - 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, - 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, - 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, - 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, - 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, - 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, - 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, - 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, - 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, - 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, - 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999 }; - - - private uint[] data = null; // stores bytes from the Big Integer - public int dataLength; // number of actual chars used - - - public uint[] Data - { - get { return data; } - } - //*********************************************************************** - // Constructor (Default value for BigInteger is 0 - //*********************************************************************** - - public BigInteger() - { - data = new uint[MaxLength]; - dataLength = 1; - } - - - //*********************************************************************** - // Constructor (Default value provided by long) - //*********************************************************************** - - public BigInteger(long value) - { - data = new uint[MaxLength]; - long tempVal = value; - - // copy bytes from long to BigInteger without any assumption of - // the length of the long datatype - - dataLength = 0; - while (value != 0 && dataLength < MaxLength) - { - data[dataLength] = (uint)(value & 0xFFFFFFFF); - value >>= 32; - dataLength++; - } - - if (tempVal > 0) // overflow check for +ve value - { - if (value != 0 || (data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - } - else if (tempVal < 0) // underflow check for -ve value - { - if (value != -1 || (data[dataLength - 1] & 0x80000000) == 0) - throw (new ArithmeticException("Negative underflow in constructor.")); - } - - if (dataLength == 0) - dataLength = 1; - } - - - //*********************************************************************** - // Constructor (Default value provided by ulong) - //*********************************************************************** - - public BigInteger(ulong value) - { - data = new uint[MaxLength]; - - // copy bytes from ulong to BigInteger without any assumption of - // the length of the ulong datatype - - dataLength = 0; - while (value != 0 && dataLength < MaxLength) - { - data[dataLength] = (uint)(value & 0xFFFFFFFF); - value >>= 32; - dataLength++; - } - - if (value != 0 || (data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - - if (dataLength == 0) - dataLength = 1; - } - - - - //*********************************************************************** - // Constructor (Default value provided by BigInteger) - //*********************************************************************** - - public BigInteger(BigInteger bi) - { - data = new uint[MaxLength]; - - dataLength = bi.dataLength; - - for (int i = 0; i < dataLength; i++) - data[i] = bi.data[i]; - } - - - //*********************************************************************** - // Constructor (Default value provided by a string of digits of the - // specified base) - // - // Example (base 10) - // ----------------- - // To initialize "a" with the default value of 1234 in base 10 - // BigInteger a = new BigInteger("1234", 10) - // - // To initialize "a" with the default value of -1234 - // BigInteger a = new BigInteger("-1234", 10) - // - // Example (base 16) - // ----------------- - // To initialize "a" with the default value of 0x1D4F in base 16 - // BigInteger a = new BigInteger("1D4F", 16) - // - // To initialize "a" with the default value of -0x1D4F - // BigInteger a = new BigInteger("-1D4F", 16) - // - // Note that string values are specified in the - // format. - // - //*********************************************************************** - - public BigInteger(string value, int radix) - { - BigInteger multiplier = new BigInteger(1); - BigInteger result = new BigInteger(); - value = (value.ToUpper()).Trim(); - int limit = 0; - - if (value[0] == '-') - limit = 1; - - for (int i = value.Length - 1; i >= limit; i--) - { - int posVal = (int)value[i]; - - if (posVal >= '0' && posVal <= '9') - posVal -= '0'; - else if (posVal >= 'A' && posVal <= 'Z') - posVal = (posVal - 'A') + 10; - else - posVal = 9999999; // arbitrary large - - - if (posVal >= radix) - throw (new ArithmeticException("Invalid string in constructor.")); - else - { - if (value[0] == '-') - posVal = -posVal; - - result = result + (multiplier * posVal); - - if ((i - 1) >= limit) - multiplier = multiplier * radix; - } - } - - if (value[0] == '-') // negative values - { - if ((result.data[MaxLength - 1] & 0x80000000) == 0) - throw (new ArithmeticException("Negative underflow in constructor.")); - } - else // positive values - { - if ((result.data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive overflow in constructor.")); - } - - data = new uint[MaxLength]; - for (int i = 0; i < result.dataLength; i++) - data[i] = result.data[i]; - - dataLength = result.dataLength; - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of bytes) - // - // The lowest index of the input byte array (i.e [0]) should contain the - // most significant byte of the number, and the highest index should - // contain the least significant byte. - // - // E.g. - // To initialize "a" with the default value of 0x1D4F in base 16 - // byte[] temp = { 0x1D, 0x4F }; - // BigInteger a = new BigInteger(temp) - // - // Note that this method of initialization does not allow the - // sign to be specified. - // - //*********************************************************************** - - public BigInteger(byte[] inData) - { - dataLength = inData.Length >> 2; - - int leftOver = inData.Length & 0x3; - if (leftOver != 0) // length not multiples of 4 - dataLength++; - - - if (dataLength > MaxLength) - throw (new ArithmeticException("Byte overflow in constructor.")); - - data = new uint[MaxLength]; - - for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++) - { - data[j] = (uint)((inData[i - 3] << 24) + (inData[i - 2] << 16) + - (inData[i - 1] << 8) + inData[i]); - } - - if (leftOver == 1) - data[dataLength - 1] = (uint)inData[0]; - else if (leftOver == 2) - data[dataLength - 1] = (uint)((inData[0] << 8) + inData[1]); - else if (leftOver == 3) - data[dataLength - 1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]); - - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of bytes of the - // specified length.) - //*********************************************************************** - - public BigInteger(byte[] inData, int inLen) - { - dataLength = inLen >> 2; - - int leftOver = inLen & 0x3; - if (leftOver != 0) // length not multiples of 4 - dataLength++; - - if (dataLength > MaxLength || inLen > inData.Length) - throw (new ArithmeticException("Byte overflow in constructor.")); - - - data = new uint[MaxLength]; - - for (int i = inLen - 1, j = 0; i >= 3; i -= 4, j++) - { - data[j] = (uint)((inData[i - 3] << 24) + (inData[i - 2] << 16) + - (inData[i - 1] << 8) + inData[i]); - } - - if (leftOver == 1) - data[dataLength - 1] = (uint)inData[0]; - else if (leftOver == 2) - data[dataLength - 1] = (uint)((inData[0] << 8) + inData[1]); - else if (leftOver == 3) - data[dataLength - 1] = (uint)((inData[0] << 16) + (inData[1] << 8) + inData[2]); - - - if (dataLength == 0) - dataLength = 1; - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Constructor (Default value provided by an array of unsigned integers) - //********************************************************************* - - public BigInteger(uint[] inData) - { - dataLength = inData.Length; - - if (dataLength > MaxLength) - throw (new ArithmeticException("Byte overflow in constructor.")); - - data = new uint[MaxLength]; - - for (int i = dataLength - 1, j = 0; i >= 0; i--, j++) - data[j] = inData[i]; - - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - //Console.WriteLine("Len = " + dataLength); - } - - - //*********************************************************************** - // Overloading of the typecast operator. - // For BigInteger bi = 10; - //*********************************************************************** - - public static implicit operator BigInteger(long value) - { - return (new BigInteger(value)); - } - - public static implicit operator BigInteger(ulong value) - { - return (new BigInteger(value)); - } - - public static implicit operator BigInteger(int value) - { - return (new BigInteger((long)value)); - } - - public static implicit operator BigInteger(uint value) - { - return (new BigInteger((ulong)value)); - } - - - //*********************************************************************** - // Overloading of addition operator - //*********************************************************************** - - public static BigInteger operator +(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - long carry = 0; - for (int i = 0; i < result.dataLength; i++) - { - long sum = (long)bi1.data[i] + (long)bi2.data[i] + carry; - carry = sum >> 32; - result.data[i] = (uint)(sum & 0xFFFFFFFF); - } - - if (carry != 0 && result.dataLength < MaxLength) - { - result.data[result.dataLength] = (uint)(carry); - result.dataLength++; - } - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - - // overflow check - int lastPos = MaxLength - 1; - if ((bi1.data[lastPos] & 0x80000000) == (bi2.data[lastPos] & 0x80000000) && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException()); - } - - return result; - } - - - //*********************************************************************** - // Overloading of the unary ++ operator - //*********************************************************************** - - public static BigInteger operator ++(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - long val, carry = 1; - int index = 0; - - while (carry != 0 && index < MaxLength) - { - val = (long)(result.data[index]); - val++; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - - index++; - } - - if (index > result.dataLength) - result.dataLength = index; - else - { - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - } - - // overflow check - int lastPos = MaxLength - 1; - - // overflow if initial value was +ve but ++ caused a sign - // change to negative. - - if ((bi1.data[lastPos] & 0x80000000) == 0 && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException("Overflow in ++.")); - } - return result; - } - - - //*********************************************************************** - // Overloading of subtraction operator - //*********************************************************************** - - public static BigInteger operator -(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - result.dataLength = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - long carryIn = 0; - for (int i = 0; i < result.dataLength; i++) - { - long diff; - - diff = (long)bi1.data[i] - (long)bi2.data[i] - carryIn; - result.data[i] = (uint)(diff & 0xFFFFFFFF); - - if (diff < 0) - carryIn = 1; - else - carryIn = 0; - } - - // roll over to negative - if (carryIn != 0) - { - for (int i = result.dataLength; i < MaxLength; i++) - result.data[i] = 0xFFFFFFFF; - result.dataLength = MaxLength; - } - - // fixed in v1.03 to give correct datalength for a - (-b) - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check - - int lastPos = MaxLength - 1; - if ((bi1.data[lastPos] & 0x80000000) != (bi2.data[lastPos] & 0x80000000) && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException()); - } - - return result; - } - - - //*********************************************************************** - // Overloading of the unary -- operator - //*********************************************************************** - - public static BigInteger operator --(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - long val; - bool carryIn = true; - int index = 0; - - while (carryIn && index < MaxLength) - { - val = (long)(result.data[index]); - val--; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - - if (val >= 0) - carryIn = false; - - index++; - } - - if (index > result.dataLength) - result.dataLength = index; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check - int lastPos = MaxLength - 1; - - // overflow if initial value was -ve but -- caused a sign - // change to positive. - - if ((bi1.data[lastPos] & 0x80000000) != 0 && - (result.data[lastPos] & 0x80000000) != (bi1.data[lastPos] & 0x80000000)) - { - throw (new ArithmeticException("Underflow in --.")); - } - - return result; - } - - - //*********************************************************************** - // Overloading of multiplication operator - //*********************************************************************** - - public static BigInteger operator *(BigInteger bi1, BigInteger bi2) - { - int lastPos = MaxLength - 1; - bool bi1Neg = false, bi2Neg = false; - - // take the absolute value of the inputs - try - { - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1Neg = true; bi1 = -bi1; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - { - bi2Neg = true; bi2 = -bi2; - } - } - catch (Exception) { } - - BigInteger result = new BigInteger(); - - // multiply the absolute values - try - { - for (int i = 0; i < bi1.dataLength; i++) - { - if (bi1.data[i] == 0) continue; - - ulong mcarry = 0; - for (int j = 0, k = i; j < bi2.dataLength; j++, k++) - { - // k = i + j - ulong val = ((ulong)bi1.data[i] * (ulong)bi2.data[j]) + - (ulong)result.data[k] + mcarry; - - result.data[k] = (uint)(val & 0xFFFFFFFF); - mcarry = (val >> 32); - } - - if (mcarry != 0) - result.data[i + bi2.dataLength] = (uint)mcarry; - } - } - catch (Exception) - { - throw (new ArithmeticException("Multiplication overflow.")); - } - - - result.dataLength = bi1.dataLength + bi2.dataLength; - if (result.dataLength > MaxLength) - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - // overflow check (result is -ve) - if ((result.data[lastPos] & 0x80000000) != 0) - { - if (bi1Neg != bi2Neg && result.data[lastPos] == 0x80000000) // different sign - { - // handle the special case where multiplication produces - // a max negative number in 2's complement. - - if (result.dataLength == 1) - return result; - else - { - bool isMaxNeg = true; - for (int i = 0; i < result.dataLength - 1 && isMaxNeg; i++) - { - if (result.data[i] != 0) - isMaxNeg = false; - } - - if (isMaxNeg) - return result; - } - } - - throw (new ArithmeticException("Multiplication overflow.")); - } - - // if input has different signs, then result is -ve - if (bi1Neg != bi2Neg) - return -result; - - return result; - } - - - - //*********************************************************************** - // Overloading of unary << operators - //*********************************************************************** - - public static BigInteger operator <<(BigInteger bi1, int shiftVal) - { - BigInteger result = new BigInteger(bi1); - result.dataLength = ShiftLeft(result.data, shiftVal); - - return result; - } - - - // least significant bits at lower part of buffer - - private static int ShiftLeft(uint[] buffer, int shiftVal) - { - int shiftAmount = 32; - int bufLen = buffer.Length; - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - for (int count = shiftVal; count > 0; ) - { - if (count < shiftAmount) - shiftAmount = count; - - //Console.WriteLine("shiftAmount = {0}", shiftAmount); - - ulong carry = 0; - for (int i = 0; i < bufLen; i++) - { - ulong val = ((ulong)buffer[i]) << shiftAmount; - val |= carry; - - buffer[i] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - } - - if (carry != 0) - { - if (bufLen + 1 <= buffer.Length) - { - buffer[bufLen] = (uint)carry; - bufLen++; - } - } - count -= shiftAmount; - } - return bufLen; - } - - - //*********************************************************************** - // Overloading of unary >> operators - //*********************************************************************** - - public static BigInteger operator >>(BigInteger bi1, int shiftVal) - { - BigInteger result = new BigInteger(bi1); - result.dataLength = ShiftRight(result.data, shiftVal); - - - if ((bi1.data[MaxLength - 1] & 0x80000000) != 0) // negative - { - for (int i = MaxLength - 1; i >= result.dataLength; i--) - result.data[i] = 0xFFFFFFFF; - - uint mask = 0x80000000; - for (int i = 0; i < 32; i++) - { - if ((result.data[result.dataLength - 1] & mask) != 0) - break; - - result.data[result.dataLength - 1] |= mask; - mask >>= 1; - } - result.dataLength = MaxLength; - } - - return result; - } - - - private static int ShiftRight(uint[] buffer, int shiftVal) - { - int shiftAmount = 32; - int invShift = 0; - int bufLen = buffer.Length; - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - //Console.WriteLine("bufLen = " + bufLen + " buffer.Length = " + buffer.Length); - - for (int count = shiftVal; count > 0; ) - { - if (count < shiftAmount) - { - shiftAmount = count; - invShift = 32 - shiftAmount; - } - - //Console.WriteLine("shiftAmount = {0}", shiftAmount); - - ulong carry = 0; - for (int i = bufLen - 1; i >= 0; i--) - { - ulong val = ((ulong)buffer[i]) >> shiftAmount; - val |= carry; - - carry = ((ulong)buffer[i]) << invShift; - buffer[i] = (uint)(val); - } - - count -= shiftAmount; - } - - while (bufLen > 1 && buffer[bufLen - 1] == 0) - bufLen--; - - return bufLen; - } - - - //*********************************************************************** - // Overloading of the NOT operator (1's complement) - //*********************************************************************** - - public static BigInteger operator ~(BigInteger bi1) - { - BigInteger result = new BigInteger(bi1); - - for (int i = 0; i < MaxLength; i++) - result.data[i] = (uint)(~(bi1.data[i])); - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of the NEGATE operator (2's complement) - //*********************************************************************** - - public static BigInteger operator -(BigInteger bi1) - { - // handle neg of zero separately since it'll cause an overflow - // if we proceed. - - if (bi1.dataLength == 1 && bi1.data[0] == 0) - return (new BigInteger()); - - BigInteger result = new BigInteger(bi1); - - // 1's complement - for (int i = 0; i < MaxLength; i++) - result.data[i] = (uint)(~(bi1.data[i])); - - // add one to result of 1's complement - long val, carry = 1; - int index = 0; - - while (carry != 0 && index < MaxLength) - { - val = (long)(result.data[index]); - val++; - - result.data[index] = (uint)(val & 0xFFFFFFFF); - carry = val >> 32; - - index++; - } - - if ((bi1.data[MaxLength - 1] & 0x80000000) == (result.data[MaxLength - 1] & 0x80000000)) - throw (new ArithmeticException("Overflow in negation.\n")); - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - return result; - } - - - //*********************************************************************** - // Overloading of equality operator - //*********************************************************************** - - public static bool operator ==(BigInteger bi1, BigInteger bi2) - { - return bi1.Equals(bi2); - } - - - public static bool operator !=(BigInteger bi1, BigInteger bi2) - { - return !(bi1.Equals(bi2)); - } - - - public override bool Equals(object o) - { - BigInteger bi = (BigInteger)o; - - if (this.dataLength != bi.dataLength) - return false; - - for (int i = 0; i < this.dataLength; i++) - { - if (this.data[i] != bi.data[i]) - return false; - } - return true; - } - - - public override int GetHashCode() - { - return this.ToString().GetHashCode(); - } - - - //*********************************************************************** - // Overloading of inequality operator - //*********************************************************************** - - public static bool operator >(BigInteger bi1, BigInteger bi2) - { - int pos = MaxLength - 1; - - // bi1 is negative, bi2 is positive - if ((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0) - return false; - - // bi1 is positive, bi2 is negative - else if ((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0) - return true; - - // same sign - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - for (pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--) ; - - if (pos >= 0) - { - if (bi1.data[pos] > bi2.data[pos]) - return true; - return false; - } - return false; - } - - - public static bool operator <(BigInteger bi1, BigInteger bi2) - { - int pos = MaxLength - 1; - - // bi1 is negative, bi2 is positive - if ((bi1.data[pos] & 0x80000000) != 0 && (bi2.data[pos] & 0x80000000) == 0) - return true; - - // bi1 is positive, bi2 is negative - else if ((bi1.data[pos] & 0x80000000) == 0 && (bi2.data[pos] & 0x80000000) != 0) - return false; - - // same sign - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - for (pos = len - 1; pos >= 0 && bi1.data[pos] == bi2.data[pos]; pos--) ; - - if (pos >= 0) - { - if (bi1.data[pos] < bi2.data[pos]) - return true; - return false; - } - return false; - } - - - public static bool operator >=(BigInteger bi1, BigInteger bi2) - { - return (bi1 == bi2 || bi1 > bi2); - } - - - public static bool operator <=(BigInteger bi1, BigInteger bi2) - { - return (bi1 == bi2 || bi1 < bi2); - } - - - //*********************************************************************** - // Private function that supports the division of two numbers with - // a divisor that has more than 1 digit. - // - // Algorithm taken from [1] - //*********************************************************************** - - private static void MultiByteDivide(BigInteger bi1, BigInteger bi2, - BigInteger outQuotient, BigInteger outRemainder) - { - uint[] result = new uint[MaxLength]; - - int remainderLen = bi1.dataLength + 1; - uint[] remainder = new uint[remainderLen]; - - uint mask = 0x80000000; - uint val = bi2.data[bi2.dataLength - 1]; - int shift = 0, resultPos = 0; - - while (mask != 0 && (val & mask) == 0) - { - shift++; mask >>= 1; - } - - //Console.WriteLine("shift = {0}", shift); - //Console.WriteLine("Before bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength); - - for (int i = 0; i < bi1.dataLength; i++) - remainder[i] = bi1.data[i]; - ShiftLeft(remainder, shift); - bi2 = bi2 << shift; - - /* - Console.WriteLine("bi1 Len = {0}, bi2 Len = {1}", bi1.dataLength, bi2.dataLength); - Console.WriteLine("dividend = " + bi1 + "\ndivisor = " + bi2); - for(int q = remainderLen - 1; q >= 0; q--) - Console.Write("{0:x2}", remainder[q]); - Console.WriteLine(); - */ - - int j = remainderLen - bi2.dataLength; - int pos = remainderLen - 1; - - ulong firstDivisorByte = bi2.data[bi2.dataLength - 1]; - ulong secondDivisorByte = bi2.data[bi2.dataLength - 2]; - - int divisorLen = bi2.dataLength + 1; - uint[] dividendPart = new uint[divisorLen]; - - while (j > 0) - { - ulong dividend = ((ulong)remainder[pos] << 32) + (ulong)remainder[pos - 1]; - //Console.WriteLine("dividend = {0}", dividend); - - ulong q_hat = dividend / firstDivisorByte; - ulong r_hat = dividend % firstDivisorByte; - - //Console.WriteLine("q_hat = {0:X}, r_hat = {1:X}", q_hat, r_hat); - - bool done = false; - while (!done) - { - done = true; - - if (q_hat == 0x100000000 || - (q_hat * secondDivisorByte) > ((r_hat << 32) + remainder[pos - 2])) - { - q_hat--; - r_hat += firstDivisorByte; - - if (r_hat < 0x100000000) - done = false; - } - } - - for (int h = 0; h < divisorLen; h++) - dividendPart[h] = remainder[pos - h]; - - BigInteger kk = new BigInteger(dividendPart); - BigInteger ss = bi2 * (long)q_hat; - - //Console.WriteLine("ss before = " + ss); - while (ss > kk) - { - q_hat--; - ss -= bi2; - //Console.WriteLine(ss); - } - BigInteger yy = kk - ss; - - //Console.WriteLine("ss = " + ss); - //Console.WriteLine("kk = " + kk); - //Console.WriteLine("yy = " + yy); - - for (int h = 0; h < divisorLen; h++) - remainder[pos - h] = yy.data[bi2.dataLength - h]; - - /* - Console.WriteLine("dividend = "); - for(int q = remainderLen - 1; q >= 0; q--) - Console.Write("{0:x2}", remainder[q]); - Console.WriteLine("\n************ q_hat = {0:X}\n", q_hat); - */ - - result[resultPos++] = (uint)q_hat; - - pos--; - j--; - } - - outQuotient.dataLength = resultPos; - int y = 0; - for (int x = outQuotient.dataLength - 1; x >= 0; x--, y++) - outQuotient.data[y] = result[x]; - for (; y < MaxLength; y++) - outQuotient.data[y] = 0; - - while (outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength - 1] == 0) - outQuotient.dataLength--; - - if (outQuotient.dataLength == 0) - outQuotient.dataLength = 1; - - outRemainder.dataLength = ShiftRight(remainder, shift); - - for (y = 0; y < outRemainder.dataLength; y++) - outRemainder.data[y] = remainder[y]; - for (; y < MaxLength; y++) - outRemainder.data[y] = 0; - } - - - //*********************************************************************** - // Private function that supports the division of two numbers with - // a divisor that has only 1 digit. - //*********************************************************************** - - private static void SingleByteDivide(BigInteger bi1, BigInteger bi2, - BigInteger outQuotient, BigInteger outRemainder) - { - uint[] result = new uint[MaxLength]; - int resultPos = 0; - - // copy dividend to reminder - for (int i = 0; i < MaxLength; i++) - outRemainder.data[i] = bi1.data[i]; - outRemainder.dataLength = bi1.dataLength; - - while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0) - outRemainder.dataLength--; - - ulong divisor = (ulong)bi2.data[0]; - int pos = outRemainder.dataLength - 1; - ulong dividend = (ulong)outRemainder.data[pos]; - - //Console.WriteLine("divisor = " + divisor + " dividend = " + dividend); - //Console.WriteLine("divisor = " + bi2 + "\ndividend = " + bi1); - - if (dividend >= divisor) - { - ulong quotient = dividend / divisor; - result[resultPos++] = (uint)quotient; - - outRemainder.data[pos] = (uint)(dividend % divisor); - } - pos--; - - while (pos >= 0) - { - //Console.WriteLine(pos); - - dividend = ((ulong)outRemainder.data[pos + 1] << 32) + (ulong)outRemainder.data[pos]; - ulong quotient = dividend / divisor; - result[resultPos++] = (uint)quotient; - - outRemainder.data[pos + 1] = 0; - outRemainder.data[pos--] = (uint)(dividend % divisor); - //Console.WriteLine(">>>> " + bi1); - } - - outQuotient.dataLength = resultPos; - int j = 0; - for (int i = outQuotient.dataLength - 1; i >= 0; i--, j++) - outQuotient.data[j] = result[i]; - for (; j < MaxLength; j++) - outQuotient.data[j] = 0; - - while (outQuotient.dataLength > 1 && outQuotient.data[outQuotient.dataLength - 1] == 0) - outQuotient.dataLength--; - - if (outQuotient.dataLength == 0) - outQuotient.dataLength = 1; - - while (outRemainder.dataLength > 1 && outRemainder.data[outRemainder.dataLength - 1] == 0) - outRemainder.dataLength--; - } - - - //*********************************************************************** - // Overloading of division operator - //*********************************************************************** - - public static BigInteger operator /(BigInteger bi1, BigInteger bi2) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - - int lastPos = MaxLength - 1; - bool divisorNeg = false, dividendNeg = false; - - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1 = -bi1; - dividendNeg = true; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - { - bi2 = -bi2; - divisorNeg = true; - } - - if (bi1 < bi2) - { - return quotient; - } - - else - { - if (bi2.dataLength == 1) - SingleByteDivide(bi1, bi2, quotient, remainder); - else - MultiByteDivide(bi1, bi2, quotient, remainder); - - if (dividendNeg != divisorNeg) - return -quotient; - - return quotient; - } - } - - - //*********************************************************************** - // Overloading of modulus operator - //*********************************************************************** - - public static BigInteger operator %(BigInteger bi1, BigInteger bi2) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(bi1); - - int lastPos = MaxLength - 1; - bool dividendNeg = false; - - if ((bi1.data[lastPos] & 0x80000000) != 0) // bi1 negative - { - bi1 = -bi1; - dividendNeg = true; - } - if ((bi2.data[lastPos] & 0x80000000) != 0) // bi2 negative - bi2 = -bi2; - - if (bi1 < bi2) - { - return remainder; - } - - else - { - if (bi2.dataLength == 1) - SingleByteDivide(bi1, bi2, quotient, remainder); - else - MultiByteDivide(bi1, bi2, quotient, remainder); - - if (dividendNeg) - return -remainder; - - return remainder; - } - } - - - //*********************************************************************** - // Overloading of bitwise AND operator - //*********************************************************************** - - public static BigInteger operator &(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] & bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of bitwise OR operator - //*********************************************************************** - - public static BigInteger operator |(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] | bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Overloading of bitwise XOR operator - //*********************************************************************** - - public static BigInteger operator ^(BigInteger bi1, BigInteger bi2) - { - BigInteger result = new BigInteger(); - - int len = (bi1.dataLength > bi2.dataLength) ? bi1.dataLength : bi2.dataLength; - - for (int i = 0; i < len; i++) - { - uint sum = (uint)(bi1.data[i] ^ bi2.data[i]); - result.data[i] = sum; - } - - result.dataLength = MaxLength; - - while (result.dataLength > 1 && result.data[result.dataLength - 1] == 0) - result.dataLength--; - - return result; - } - - - //*********************************************************************** - // Returns max(this, bi) - //*********************************************************************** - - public BigInteger Max(BigInteger bi) - { - if (this > bi) - return (new BigInteger(this)); - else - return (new BigInteger(bi)); - } - - - //*********************************************************************** - // Returns min(this, bi) - //*********************************************************************** - - public BigInteger Min(BigInteger bi) - { - if (this < bi) - return (new BigInteger(this)); - else - return (new BigInteger(bi)); - - } - - - //*********************************************************************** - // Returns the absolute value - //*********************************************************************** - - public BigInteger Abs() - { - if ((this.data[MaxLength - 1] & 0x80000000) != 0) - return (-this); - else - return (new BigInteger(this)); - } - - - //*********************************************************************** - // Returns a string representing the BigInteger in base 10. - //*********************************************************************** - - public override string ToString() - { - return ToString(10); - } - - - //*********************************************************************** - // Returns a string representing the BigInteger in sign-and-magnitude - // format in the specified radix. - // - // Example - // ------- - // If the value of BigInteger is -255 in base 10, then - // ToString(16) returns "-FF" - // - //*********************************************************************** - - public string ToString(int radix) - { - if (radix < 2 || radix > 36) - throw (new ArgumentException("Radix must be >= 2 and <= 36")); - - string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - string result = ""; - - BigInteger a = this; - - bool negative = false; - if ((a.data[MaxLength - 1] & 0x80000000) != 0) - { - negative = true; - try - { - a = -a; - } - catch (Exception) { } - } - - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - BigInteger biRadix = new BigInteger(radix); - - if (a.dataLength == 1 && a.data[0] == 0) - result = "0"; - else - { - while (a.dataLength > 1 || (a.dataLength == 1 && a.data[0] != 0)) - { - SingleByteDivide(a, biRadix, quotient, remainder); - - if (remainder.data[0] < 10) - result = remainder.data[0] + result; - else - result = charSet[(int)remainder.data[0] - 10] + result; - - a = quotient; - } - if (negative) - result = "-" + result; - } - - return result; - } - - - //*********************************************************************** - // Returns a hex string showing the contains of the BigInteger - // - // Examples - // ------- - // 1) If the value of BigInteger is 255 in base 10, then - // ToHexString() returns "FF" - // - // 2) If the value of BigInteger is -255 in base 10, then - // ToHexString() returns ".....FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF01", - // which is the 2's complement representation of -255. - // - //*********************************************************************** - - public string ToHexString() - { - string result = data[dataLength - 1].ToString("X"); - - for (int i = dataLength - 2; i >= 0; i--) - { - result += data[i].ToString("X8"); - } - - return result; - } - - public byte[] ToByteArray() - { - List result = new List(); - - //int dataLength = data.Length; - result.AddRange(BitConverter.GetBytes(data[dataLength - 1])); - for (int i = dataLength - 2; i >= 0; i--) - { - result.AddRange(BitConverter.GetBytes(data[i])); - } - - return result.ToArray(); - } - - private static System.Xml.Serialization.XmlSerializer serializer; - - private static System.Xml.Serialization.XmlSerializer Serializer - { - get - { - if ((serializer == null)) - { - serializer = new System.Xml.Serialization.XmlSerializer(typeof(BigInteger)); - } - return serializer; - } - } - - public string ToXml() - { - // return an xml representation - return Serialize(); - } - - public virtual string Serialize() - { - System.IO.StreamReader streamReader = null; - System.IO.MemoryStream memoryStream = null; - try - { - memoryStream = new System.IO.MemoryStream(); - Serializer.Serialize(memoryStream, this); - memoryStream.Seek(0, System.IO.SeekOrigin.Begin); - streamReader = new System.IO.StreamReader(memoryStream); - return streamReader.ReadToEnd(); - } - finally - { - if ((streamReader != null)) - { - streamReader.Dispose(); - } - if ((memoryStream != null)) - { - memoryStream.Dispose(); - } - } - } - //*********************************************************************** - // Modulo Exponentiation - //*********************************************************************** - - public BigInteger ModPow(BigInteger exp, BigInteger n) - { - if ((exp.data[MaxLength - 1] & 0x80000000) != 0) - throw (new ArithmeticException("Positive exponents only.")); - - BigInteger resultNum = 1; - BigInteger tempNum; - bool thisNegative = false; - - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative this - { - tempNum = -this % n; - thisNegative = true; - } - else - tempNum = this % n; // ensures (tempNum * tempNum) < b^(2k) - - if ((n.data[MaxLength - 1] & 0x80000000) != 0) // negative n - n = -n; - - // calculate constant = b^(2k) / m - BigInteger constant = new BigInteger(); - - int i = n.dataLength << 1; - constant.data[i] = 0x00000001; - constant.dataLength = i + 1; - - constant = constant / n; - int totalBits = exp.BitCount(); - int count = 0; - - // perform squaring and multiply exponentiation - for (int pos = 0; pos < exp.dataLength; pos++) - { - uint mask = 0x01; - //Console.WriteLine("pos = " + pos); - - for (int index = 0; index < 32; index++) - { - if ((exp.data[pos] & mask) != 0) - resultNum = BarrettReduction(resultNum * tempNum, n, constant); - - mask <<= 1; - - tempNum = BarrettReduction(tempNum * tempNum, n, constant); - - - if (tempNum.dataLength == 1 && tempNum.data[0] == 1) - { - if (thisNegative && (exp.data[0] & 0x1) != 0) //odd exp - return -resultNum; - return resultNum; - } - count++; - if (count == totalBits) - break; - } - } - - if (thisNegative && (exp.data[0] & 0x1) != 0) //odd exp - return -resultNum; - - return resultNum; - } - - - - //*********************************************************************** - // Fast calculation of modular reduction using Barrett's reduction. - // Requires x < b^(2k), where b is the base. In this case, base is - // 2^32 (uint). - // - // Reference [4] - //*********************************************************************** - - public static BigInteger BarrettReduction(BigInteger x, BigInteger n, BigInteger constant) - { - int k = n.dataLength, - kPlusOne = k + 1, - kMinusOne = k - 1; - - BigInteger q1 = new BigInteger(); - - // q1 = x / b^(k-1) - for (int i = kMinusOne, j = 0; i < x.dataLength; i++, j++) - q1.data[j] = x.data[i]; - q1.dataLength = x.dataLength - kMinusOne; - if (q1.dataLength <= 0) - q1.dataLength = 1; - - - BigInteger q2 = q1 * constant; - BigInteger q3 = new BigInteger(); - - // q3 = q2 / b^(k+1) - for (int i = kPlusOne, j = 0; i < q2.dataLength; i++, j++) - q3.data[j] = q2.data[i]; - q3.dataLength = q2.dataLength - kPlusOne; - if (q3.dataLength <= 0) - q3.dataLength = 1; - - - // r1 = x mod b^(k+1) - // i.e. keep the lowest (k+1) words - BigInteger r1 = new BigInteger(); - int lengthToCopy = (x.dataLength > kPlusOne) ? kPlusOne : x.dataLength; - for (int i = 0; i < lengthToCopy; i++) - r1.data[i] = x.data[i]; - r1.dataLength = lengthToCopy; - - - // r2 = (q3 * n) mod b^(k+1) - // partial multiplication of q3 and n - - BigInteger r2 = new BigInteger(); - for (int i = 0; i < q3.dataLength; i++) - { - if (q3.data[i] == 0) continue; - - ulong mcarry = 0; - int t = i; - for (int j = 0; j < n.dataLength && t < kPlusOne; j++, t++) - { - // t = i + j - ulong val = ((ulong)q3.data[i] * (ulong)n.data[j]) + - (ulong)r2.data[t] + mcarry; - - r2.data[t] = (uint)(val & 0xFFFFFFFF); - mcarry = (val >> 32); - } - - if (t < kPlusOne) - r2.data[t] = (uint)mcarry; - } - r2.dataLength = kPlusOne; - while (r2.dataLength > 1 && r2.data[r2.dataLength - 1] == 0) - r2.dataLength--; - - r1 -= r2; - if ((r1.data[MaxLength - 1] & 0x80000000) != 0) // negative - { - BigInteger val = new BigInteger(); - val.data[kPlusOne] = 0x00000001; - val.dataLength = kPlusOne + 1; - r1 += val; - } - - while (r1 >= n) - r1 -= n; - - return r1; - } - - - //*********************************************************************** - // Returns gcd(this, bi) - //*********************************************************************** - - public BigInteger Gcd(BigInteger bi) - { - BigInteger x; - BigInteger y; - - if ((data[MaxLength - 1] & 0x80000000) != 0) // negative - x = -this; - else - x = this; - - if ((bi.data[MaxLength - 1] & 0x80000000) != 0) // negative - y = -bi; - else - y = bi; - - BigInteger g = y; - - while (x.dataLength > 1 || (x.dataLength == 1 && x.data[0] != 0)) - { - g = x; - x = y % x; - y = g; - } - - return g; - } - - - //*********************************************************************** - // Populates "this" with the specified amount of random bits - //*********************************************************************** - - public void GenRandomBits(int bits, StrongNumberProvider rand) - { - int dwords = bits >> 5; - int remBits = bits & 0x1F; - - if (remBits != 0) - dwords++; - - if (dwords > MaxLength) - throw (new ArithmeticException("Number of required bits > maxLength.")); - - for (int i = 0; i < dwords; i++) - data[i] = (uint)rand.GetNextUInt32(); - - for (int i = dwords; i < MaxLength; i++) - data[i] = 0; - - if (remBits != 0) - { - uint mask = (uint)(0x01 << (remBits - 1)); - data[dwords - 1] |= mask; - - mask = (uint)(0xFFFFFFFF >> (32 - remBits)); - data[dwords - 1] &= mask; - } - else - data[dwords - 1] |= 0x80000000; - - dataLength = dwords; - - if (dataLength == 0) - dataLength = 1; - } - - - //*********************************************************************** - // Returns the position of the most significant bit in the BigInteger. - // - // Eg. The result is 0, if the value of BigInteger is 0...0000 0000 - // The result is 1, if the value of BigInteger is 0...0000 0001 - // The result is 2, if the value of BigInteger is 0...0000 0010 - // The result is 2, if the value of BigInteger is 0...0000 0011 - // - //*********************************************************************** - - public int BitCount() - { - while (dataLength > 1 && data[dataLength - 1] == 0) - dataLength--; - - uint value = data[dataLength - 1]; - uint mask = 0x80000000; - int bits = 32; - - while (bits > 0 && (value & mask) == 0) - { - bits--; - mask >>= 1; - } - bits += ((dataLength - 1) << 5); - - return bits; - } - - - //*********************************************************************** - // Probabilistic prime test based on Fermat's little theorem - // - // for any a < p (p does not divide a) if - // a^(p-1) mod p != 1 then p is not prime. - // - // Otherwise, p is probably prime (pseudoprime to the chosen base). - // - // Returns - // ------- - // True if "this" is a pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - // Note - this method is fast but fails for Carmichael numbers except - // when the randomly chosen base is a factor of the number. - // - //*********************************************************************** - - public bool FermatLittleTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = rand.GetNextInt() * bits; - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - // calculate a^(p-1) mod p - BigInteger expResult = a.ModPow(p_sub1, thisVal); - - int resultLen = expResult.dataLength; - - // is NOT prime is a^(p-1) mod p != 1 - - if (resultLen > 1 || (resultLen == 1 && expResult.data[0] != 1)) - { - //Console.WriteLine("a = " + a.ToString()); - return false; - } - } - - return true; - } - - - //*********************************************************************** - // Probabilistic prime test based on Rabin-Miller's - // - // for any p > 0 with p - 1 = 2^s * t - // - // p is probably prime (strong pseudoprime) if for any a < p, - // 1) a^t mod p = 1 or - // 2) a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - // - // Otherwise, p is composite. - // - // Returns - // ------- - // True if "this" is a strong pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - //*********************************************************************** - - public bool RabinMillerTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - // calculate values of s and t - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - int s = 0; - - for (int index = 0; index < p_sub1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_sub1.data[index] & mask) != 0) - { - index = p_sub1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_sub1 >> s; - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = (int)(rand.GetNextSingle() * bits); - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - BigInteger b = a.ModPow(t, thisVal); - - bool result = false; - - if (b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1 - result = true; - - for (int j = 0; result == false && j < s; j++) - { - if (b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - { - result = true; - break; - } - - b = (b * b) % thisVal; - } - - if (result == false) - return false; - } - return true; - } - - - //*********************************************************************** - // Probabilistic prime test based on Solovay-Strassen (Euler Criterion) - // - // p is probably prime if for any a < p (a is not multiple of p), - // a^((p-1)/2) mod p = J(a, p) - // - // where J is the Jacobi symbol. - // - // Otherwise, p is composite. - // - // Returns - // ------- - // True if "this" is a Euler pseudoprime to randomly chosen - // bases. The number of chosen bases is given by the "confidence" - // parameter. - // - // False if "this" is definitely NOT prime. - // - //*********************************************************************** - - public bool SolovayStrassenTest(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - int bits = thisVal.BitCount(); - BigInteger a = new BigInteger(); - BigInteger p_sub1 = thisVal - 1; - BigInteger p_sub1_shift = p_sub1 >> 1; - - StrongNumberProvider rand = new StrongNumberProvider(); - - for (int round = 0; round < confidence; round++) - { - bool done = false; - - while (!done) // generate a < n - { - int testBits = 0; - - // make sure "a" has at least 2 bits - while (testBits < 2) - testBits = (int)(rand.GetNextSingle() * bits); - - a.GenRandomBits(testBits, rand); - - int byteLen = a.dataLength; - - // make sure "a" is not 0 - if (byteLen > 1 || (byteLen == 1 && a.data[0] != 1)) - done = true; - } - - // check whether a factor exists (fix for version 1.03) - BigInteger gcdTest = a.Gcd(thisVal); - if (gcdTest.dataLength == 1 && gcdTest.data[0] != 1) - return false; - - // calculate a^((p-1)/2) mod p - - BigInteger expResult = a.ModPow(p_sub1_shift, thisVal); - if (expResult == p_sub1) - expResult = -1; - - // calculate Jacobi symbol - BigInteger jacob = Jacobi(a, thisVal); - - //Console.WriteLine("a = " + a.ToString(10) + " b = " + thisVal.ToString(10)); - //Console.WriteLine("expResult = " + expResult.ToString(10) + " Jacob = " + jacob.ToString(10)); - - // if they are different then it is not prime - if (expResult != jacob) - return false; - } - - return true; - } - - - //*********************************************************************** - // Implementation of the Lucas Strong Pseudo Prime test. - // - // Let n be an odd number with gcd(n,D) = 1, and n - J(D, n) = 2^s * d - // with d odd and s >= 0. - // - // If Ud mod n = 0 or V2^r*d mod n = 0 for some 0 <= r < s, then n - // is a strong Lucas pseudoprime with parameters (P, Q). We select - // P and Q based on Selfridge. - // - // Returns True if number is a strong Lucus pseudo prime. - // Otherwise, returns False indicating that number is composite. - //*********************************************************************** - - public bool LucasStrongTest() - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - return LucasStrongTestHelper(thisVal); - } - - - private bool LucasStrongTestHelper(BigInteger thisVal) - { - // Do the test (selects D based on Selfridge) - // Let D be the first element of the sequence - // 5, -7, 9, -11, 13, ... for which J(D,n) = -1 - // Let P = 1, Q = (1-D) / 4 - - long D = 5, sign = -1, dCount = 0; - bool done = false; - - while (!done) - { - int Jresult = BigInteger.Jacobi(D, thisVal); - - if (Jresult == -1) - done = true; // J(D, this) = 1 - else - { - if (Jresult == 0 && Math.Abs(D) < thisVal) // divisor found - return false; - - if (dCount == 20) - { - // check for square - BigInteger root = thisVal.Sqrt(); - if (root * root == thisVal) - return false; - } - - //Console.WriteLine(D); - D = (Math.Abs(D) + 2) * sign; - sign = -sign; - } - dCount++; - } - - long Q = (1 - D) >> 2; - - BigInteger p_add1 = thisVal + 1; - int s = 0; - - for (int index = 0; index < p_add1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_add1.data[index] & mask) != 0) - { - index = p_add1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_add1 >> s; - - // calculate constant = b^(2k) / m - // for Barrett Reduction - BigInteger constant = new BigInteger(); - - int nLen = thisVal.dataLength << 1; - constant.data[nLen] = 0x00000001; - constant.dataLength = nLen + 1; - - constant = constant / thisVal; - - BigInteger[] lucas = LucasSequenceHelper(1, Q, t, thisVal, constant, 0); - bool isPrime = false; - - if ((lucas[0].dataLength == 1 && lucas[0].data[0] == 0) || - (lucas[1].dataLength == 1 && lucas[1].data[0] == 0)) - { - // u(t) = 0 or V(t) = 0 - isPrime = true; - } - - for (int i = 1; i < s; i++) - { - if (!isPrime) - { - // doubling of index - lucas[1] = BigInteger.BarrettReduction(lucas[1] * lucas[1], thisVal, constant); - lucas[1] = (lucas[1] - (lucas[2] << 1)) % thisVal; - - //lucas[1] = ((lucas[1] * lucas[1]) - (lucas[2] << 1)) % thisVal; - - if ((lucas[1].dataLength == 1 && lucas[1].data[0] == 0)) - isPrime = true; - } - - lucas[2] = BigInteger.BarrettReduction(lucas[2] * lucas[2], thisVal, constant); //Q^k - } - - - if (isPrime) // additional checks for composite numbers - { - // If n is prime and gcd(n, Q) == 1, then - // Q^((n+1)/2) = Q * Q^((n-1)/2) is congruent to (Q * J(Q, n)) mod n - - BigInteger g = thisVal.Gcd(Q); - if (g.dataLength == 1 && g.data[0] == 1) // gcd(this, Q) == 1 - { - if ((lucas[2].data[MaxLength - 1] & 0x80000000) != 0) - lucas[2] += thisVal; - - BigInteger temp = (Q * BigInteger.Jacobi(Q, thisVal)) % thisVal; - if ((temp.data[MaxLength - 1] & 0x80000000) != 0) - temp += thisVal; - - if (lucas[2] != temp) - isPrime = false; - } - } - - return isPrime; - } - - - //*********************************************************************** - // Determines whether a number is probably prime, using the Rabin-Miller's - // test. Before applying the test, the number is tested for divisibility - // by primes < 2000 - // - // Returns true if number is probably prime. - //*********************************************************************** - - public bool IsProbablePrime(int confidence) - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - - // test for divisibility by primes < 2000 - for (int p = 0; p < primesBelow2000.Length; p++) - { - BigInteger divisor = primesBelow2000[p]; - - if (divisor >= thisVal) - break; - - BigInteger resultNum = thisVal % divisor; - if (resultNum.IntValue() == 0) - { - /* - Console.WriteLine("Not prime! Divisible by {0}\n", - primesBelow2000[p]); - */ - return false; - } - } - - if (thisVal.RabinMillerTest(confidence)) - return true; - else - { - //Console.WriteLine("Not prime! Failed primality test\n"); - return false; - } - } - - - //*********************************************************************** - // Determines whether this BigInteger is probably prime using a - // combination of base 2 strong pseudoprime test and Lucas strong - // pseudoprime test. - // - // The sequence of the primality test is as follows, - // - // 1) Trial divisions are carried out using prime numbers below 2000. - // if any of the primes divides this BigInteger, then it is not prime. - // - // 2) Perform base 2 strong pseudoprime test. If this BigInteger is a - // base 2 strong pseudoprime, proceed on to the next step. - // - // 3) Perform strong Lucas pseudoprime test. - // - // Returns True if this BigInteger is both a base 2 strong pseudoprime - // and a strong Lucas pseudoprime. - // - // For a detailed discussion of this primality test, see [6]. - // - //*********************************************************************** - - public bool IsProbablePrime() - { - BigInteger thisVal; - if ((this.data[MaxLength - 1] & 0x80000000) != 0) // negative - thisVal = -this; - else - thisVal = this; - - if (thisVal.dataLength == 1) - { - // test small numbers - if (thisVal.data[0] == 0 || thisVal.data[0] == 1) - return false; - else if (thisVal.data[0] == 2 || thisVal.data[0] == 3) - return true; - } - - if ((thisVal.data[0] & 0x1) == 0) // even numbers - return false; - - - // test for divisibility by primes < 2000 - for (int p = 0; p < primesBelow2000.Length; p++) - { - BigInteger divisor = primesBelow2000[p]; - - if (divisor >= thisVal) - break; - - BigInteger resultNum = thisVal % divisor; - if (resultNum.IntValue() == 0) - { - //Console.WriteLine("Not prime! Divisible by {0}\n", - // primesBelow2000[p]); - - return false; - } - } - - // Perform BASE 2 Rabin-Miller Test - - // calculate values of s and t - BigInteger p_sub1 = thisVal - (new BigInteger(1)); - int s = 0; - - for (int index = 0; index < p_sub1.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((p_sub1.data[index] & mask) != 0) - { - index = p_sub1.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = p_sub1 >> s; - - int bits = thisVal.BitCount(); - BigInteger a = 2; - - // b = a^t mod p - BigInteger b = a.ModPow(t, thisVal); - bool result = false; - - if (b.dataLength == 1 && b.data[0] == 1) // a^t mod p = 1 - result = true; - - for (int j = 0; result == false && j < s; j++) - { - if (b == p_sub1) // a^((2^j)*t) mod p = p-1 for some 0 <= j <= s-1 - { - result = true; - break; - } - - b = (b * b) % thisVal; - } - - // if number is strong pseudoprime to base 2, then do a strong lucas test - if (result) - result = LucasStrongTestHelper(thisVal); - - return result; - } - - - - //*********************************************************************** - // Returns the lowest 4 bytes of the BigInteger as an int. - //*********************************************************************** - - public int IntValue() - { - return (int)data[0]; - } - - - //*********************************************************************** - // Returns the lowest 8 bytes of the BigInteger as a long. - //*********************************************************************** - - public long LongValue() - { - long val = 0; - - val = (long)data[0]; - try - { // exception if maxLength = 1 - val |= (long)data[1] << 32; - } - catch (Exception) - { - if ((data[0] & 0x80000000) != 0) // negative - val = (int)data[0]; - } - - return val; - } - - - //*********************************************************************** - // Computes the Jacobi Symbol for a and b. - // Algorithm adapted from [3] and [4] with some optimizations - //*********************************************************************** - - public static int Jacobi(BigInteger a, BigInteger b) - { - // Jacobi defined only for odd integers - if ((b.data[0] & 0x1) == 0) - throw (new ArgumentException("Jacobi defined only for odd integers.")); - - if (a >= b) a %= b; - if (a.dataLength == 1 && a.data[0] == 0) return 0; // a == 0 - if (a.dataLength == 1 && a.data[0] == 1) return 1; // a == 1 - - if (a < 0) - { - if ((((b - 1).data[0]) & 0x2) == 0) //if( (((b-1) >> 1).data[0] & 0x1) == 0) - return Jacobi(-a, b); - else - return -Jacobi(-a, b); - } - - int e = 0; - for (int index = 0; index < a.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((a.data[index] & mask) != 0) - { - index = a.dataLength; // to break the outer loop - break; - } - mask <<= 1; - e++; - } - } - - BigInteger a1 = a >> e; - - int s = 1; - if ((e & 0x1) != 0 && ((b.data[0] & 0x7) == 3 || (b.data[0] & 0x7) == 5)) - s = -1; - - if ((b.data[0] & 0x3) == 3 && (a1.data[0] & 0x3) == 3) - s = -s; - - if (a1.dataLength == 1 && a1.data[0] == 1) - return s; - else - return (s * Jacobi(b % a1, a1)); - } - - - - //*********************************************************************** - // Generates a positive BigInteger that is probably prime. - //*********************************************************************** - - public static BigInteger GenPseudoPrime(int bits, int confidence, StrongNumberProvider rand) - { - BigInteger result = new BigInteger(); - bool done = false; - - while (!done) - { - result.GenRandomBits(bits, rand); - result.data[0] |= 0x01; // make it odd - - // prime test - done = result.IsProbablePrime(confidence); - } - return result; - } - - - //*********************************************************************** - // Generates a random number with the specified number of bits such - // that gcd(number, this) = 1 - //*********************************************************************** - - public BigInteger GenCoPrime(int bits, StrongNumberProvider rand) - { - bool done = false; - BigInteger result = new BigInteger(); - - while (!done) - { - result.GenRandomBits(bits, rand); - //Console.WriteLine(result.ToString(16)); - - // gcd test - BigInteger g = result.Gcd(this); - if (g.dataLength == 1 && g.data[0] == 1) - done = true; - } - - return result; - } - - - //*********************************************************************** - // Returns the modulo inverse of this. Throws ArithmeticException if - // the inverse does not exist. (i.e. gcd(this, modulus) != 1) - //*********************************************************************** - - public BigInteger ModInverse(BigInteger modulus) - { - BigInteger[] p = { 0, 1 }; - BigInteger[] q = new BigInteger[2]; // quotients - BigInteger[] r = { 0, 0 }; // remainders - - int step = 0; - - BigInteger a = modulus; - BigInteger b = this; - - while (b.dataLength > 1 || (b.dataLength == 1 && b.data[0] != 0)) - { - BigInteger quotient = new BigInteger(); - BigInteger remainder = new BigInteger(); - - if (step > 1) - { - BigInteger pval = (p[0] - (p[1] * q[0])) % modulus; - p[0] = p[1]; - p[1] = pval; - } - - if (b.dataLength == 1) - SingleByteDivide(a, b, quotient, remainder); - else - MultiByteDivide(a, b, quotient, remainder); - - /* - Console.WriteLine(quotient.dataLength); - Console.WriteLine("{0} = {1}({2}) + {3} p = {4}", a.ToString(10), - b.ToString(10), quotient.ToString(10), remainder.ToString(10), - p[1].ToString(10)); - */ - - q[0] = q[1]; - r[0] = r[1]; - q[1] = quotient; r[1] = remainder; - - a = b; - b = remainder; - - step++; - } - - if (r[0].dataLength > 1 || (r[0].dataLength == 1 && r[0].data[0] != 1)) - throw (new ArithmeticException("No inverse!")); - - BigInteger result = ((p[0] - (p[1] * q[0])) % modulus); - - if ((result.data[MaxLength - 1] & 0x80000000) != 0) - result += modulus; // get the least positive modulus - - return result; - } - - - //*********************************************************************** - // Returns the value of the BigInteger as a byte array. The lowest - // index contains the MSB. - //*********************************************************************** - - public byte[] GetBytes() - { - int numBits = BitCount(); - - int numBytes = numBits >> 3; - if ((numBits & 0x7) != 0) - numBytes++; - - byte[] result = new byte[numBytes]; - - //Console.WriteLine(result.Length); - - int pos = 0; - uint tempVal, val = data[dataLength - 1]; - - if ((tempVal = (val >> 24 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val >> 16 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val >> 8 & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - if ((tempVal = (val & 0xFF)) != 0) - result[pos++] = (byte)tempVal; - - for (int i = dataLength - 2; i >= 0; i--, pos += 4) - { - val = data[i]; - result[pos + 3] = (byte)(val & 0xFF); - val >>= 8; - result[pos + 2] = (byte)(val & 0xFF); - val >>= 8; - result[pos + 1] = (byte)(val & 0xFF); - val >>= 8; - result[pos] = (byte)(val & 0xFF); - } - - return result; - } - - - //*********************************************************************** - // Sets the value of the specified bit to 1 - // The Least Significant Bit position is 0. - //*********************************************************************** - - public void SetBit(uint bitNum) - { - uint bytePos = bitNum >> 5; // divide by 32 - byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits - - uint mask = (uint)1 << bitPos; - this.data[bytePos] |= mask; - - if (bytePos >= this.dataLength) - this.dataLength = (int)bytePos + 1; - } - - - //*********************************************************************** - // Sets the value of the specified bit to 0 - // The Least Significant Bit position is 0. - //*********************************************************************** - - public void UnsetBit(uint bitNum) - { - uint bytePos = bitNum >> 5; - - if (bytePos < this.dataLength) - { - byte bitPos = (byte)(bitNum & 0x1F); - - uint mask = (uint)1 << bitPos; - uint mask2 = 0xFFFFFFFF ^ mask; - - this.data[bytePos] &= mask2; - - if (this.dataLength > 1 && this.data[this.dataLength - 1] == 0) - this.dataLength--; - } - } - - - //*********************************************************************** - // Returns a value that is equivalent to the integer square root - // of the BigInteger. - // - // The integer square root of "this" is defined as the largest integer n - // such that (n * n) <= this - // - //*********************************************************************** - - public BigInteger Sqrt() - { - uint numBits = (uint)this.BitCount(); - - if ((numBits & 0x1) != 0) // odd number of bits - numBits = (numBits >> 1) + 1; - else - numBits = (numBits >> 1); - - uint bytePos = numBits >> 5; - byte bitPos = (byte)(numBits & 0x1F); - - uint mask; - - BigInteger result = new BigInteger(); - if (bitPos == 0) - mask = 0x80000000; - else - { - mask = (uint)1 << bitPos; - bytePos++; - } - result.dataLength = (int)bytePos; - - for (int i = (int)bytePos - 1; i >= 0; i--) - { - while (mask != 0) - { - // guess - result.data[i] ^= mask; - - // undo the guess if its square is larger than this - if ((result * result) > this) - result.data[i] ^= mask; - - mask >>= 1; - } - mask = 0x80000000; - } - return result; - } - - - //*********************************************************************** - // Returns the k_th number in the Lucas Sequence reduced modulo n. - // - // Uses index doubling to speed up the process. For example, to calculate V(k), - // we maintain two numbers in the sequence V(n) and V(n+1). - // - // To obtain V(2n), we use the identity - // V(2n) = (V(n) * V(n)) - (2 * Q^n) - // To obtain V(2n+1), we first write it as - // V(2n+1) = V((n+1) + n) - // and use the identity - // V(m+n) = V(m) * V(n) - Q * V(m-n) - // Hence, - // V((n+1) + n) = V(n+1) * V(n) - Q^n * V((n+1) - n) - // = V(n+1) * V(n) - Q^n * V(1) - // = V(n+1) * V(n) - Q^n * P - // - // We use k in its binary expansion and perform index doubling for each - // bit position. For each bit position that is set, we perform an - // index doubling followed by an index addition. This means that for V(n), - // we need to update it to V(2n+1). For V(n+1), we need to update it to - // V((2n+1)+1) = V(2*(n+1)) - // - // This function returns - // [0] = U(k) - // [1] = V(k) - // [2] = Q^n - // - // Where U(0) = 0 % n, U(1) = 1 % n - // V(0) = 2 % n, V(1) = P % n - //*********************************************************************** - - public static BigInteger[] LucasSequence(BigInteger P, BigInteger Q, - BigInteger k, BigInteger n) - { - if (k.dataLength == 1 && k.data[0] == 0) - { - BigInteger[] result = new BigInteger[3]; - - result[0] = 0; result[1] = 2 % n; result[2] = 1 % n; - return result; - } - - // calculate constant = b^(2k) / m - // for Barrett Reduction - BigInteger constant = new BigInteger(); - - int nLen = n.dataLength << 1; - constant.data[nLen] = 0x00000001; - constant.dataLength = nLen + 1; - - constant = constant / n; - - // calculate values of s and t - int s = 0; - - for (int index = 0; index < k.dataLength; index++) - { - uint mask = 0x01; - - for (int i = 0; i < 32; i++) - { - if ((k.data[index] & mask) != 0) - { - index = k.dataLength; // to break the outer loop - break; - } - mask <<= 1; - s++; - } - } - - BigInteger t = k >> s; - - //Console.WriteLine("s = " + s + " t = " + t); - return LucasSequenceHelper(P, Q, t, n, constant, s); - } - - - //*********************************************************************** - // Performs the calculation of the kth term in the Lucas Sequence. - // For details of the algorithm, see reference [9]. - // - // k must be odd. i.e LSB == 1 - //*********************************************************************** - - private static BigInteger[] LucasSequenceHelper(BigInteger P, BigInteger Q, - BigInteger k, BigInteger n, - BigInteger constant, int s) - { - BigInteger[] result = new BigInteger[3]; - - if ((k.data[0] & 0x00000001) == 0) - throw (new ArgumentException("Argument k must be odd.")); - - int numbits = k.BitCount(); - uint mask = (uint)0x1 << ((numbits & 0x1F) - 1); - - // v = v0, v1 = v1, u1 = u1, Q_k = Q^0 - - BigInteger v = 2 % n, Q_k = 1 % n, - v1 = P % n, u1 = Q_k; - bool flag = true; - - for (int i = k.dataLength - 1; i >= 0; i--) // iterate on the binary expansion of k - { - //Console.WriteLine("round"); - while (mask != 0) - { - if (i == 0 && mask == 0x00000001) // last bit - break; - - if ((k.data[i] & mask) != 0) // bit is set - { - // index doubling with addition - - u1 = (u1 * v1) % n; - - v = ((v * v1) - (P * Q_k)) % n; - v1 = BigInteger.BarrettReduction(v1 * v1, n, constant); - v1 = (v1 - ((Q_k * Q) << 1)) % n; - - if (flag) - flag = false; - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - - Q_k = (Q_k * Q) % n; - } - else - { - // index doubling - u1 = ((u1 * v) - Q_k) % n; - - v1 = ((v * v1) - (P * Q_k)) % n; - v = BigInteger.BarrettReduction(v * v, n, constant); - v = (v - (Q_k << 1)) % n; - - if (flag) - { - Q_k = Q % n; - flag = false; - } - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - } - - mask >>= 1; - } - mask = 0x80000000; - } - - // at this point u1 = u(n+1) and v = v(n) - // since the last bit always 1, we need to transform u1 to u(2n+1) and v to v(2n+1) - - u1 = ((u1 * v) - Q_k) % n; - v = ((v * v1) - (P * Q_k)) % n; - if (flag) - flag = false; - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - - Q_k = (Q_k * Q) % n; - - - for (int i = 0; i < s; i++) - { - // index doubling - u1 = (u1 * v) % n; - v = ((v * v) - (Q_k << 1)) % n; - - if (flag) - { - Q_k = Q % n; - flag = false; - } - else - Q_k = BigInteger.BarrettReduction(Q_k * Q_k, n, constant); - } - - result[0] = u1; - result[1] = v; - result[2] = Q_k; - - return result; - } - - //#region IDisposable Members - - //public void Dispose() - //{ - // data = new uint[0]; - // data = null; - // GC.Collect(); - // GC.Collect(); - //} - - //#endregion - } -} diff --git a/SocketService.Framework.Crypto/CentralAuthority.cs b/SocketService.Framework.Crypto/CentralAuthority.cs deleted file mode 100644 index 3aa8791..0000000 --- a/SocketService.Framework.Crypto/CentralAuthority.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Crypto -{ - [Serializable] - public class CentralAuthority - { - // higher numbers result in more accuracy at the expense of processing time - private const int Confidence = 30; - - private readonly BigInteger _prime; - private readonly BigInteger _g; - private readonly int _bits = 64; - private readonly StrongNumberProvider _rand = new StrongNumberProvider(); - - /// - /// Initializes a new instance of the class. - /// - /// The protocol. - public CentralAuthority(CAKeyProtocol protocol) - { - _bits = (int)protocol; - _prime = BigInteger.GenPseudoPrime(_bits, Confidence, _rand); - _g = (BigInteger)7; - } - - /// - /// Initializes a new instance of the class. - /// - public CentralAuthority() - { - _prime = BigInteger.GenPseudoPrime(_bits, Confidence, _rand); - _g = (BigInteger)7; - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - public CentralAuthority(BigInteger prime, BigInteger g) - { - _prime = prime; - _g = g; - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - public CentralAuthority(byte [] prime, byte [] g) - { - _prime = new BigInteger(prime); - _g = new BigInteger(g); - } - - /// - /// Gets the provider. - /// - /// - public DiffieHellmanProvider GetProvider() - { - return new DiffieHellmanProvider( - _prime, - _g, - BigInteger.GenPseudoPrime(_bits, Confidence, _rand)); - } - - } - - public enum CAKeyProtocol - { - DH64 = 64, - DH128 = 128, - DH256 = 256, - DH512 = 512, - DH768 = 768, - DH1024 = 1024 - } -} diff --git a/SocketService.Framework.Crypto/Crc32.cs b/SocketService.Framework.Crypto/Crc32.cs deleted file mode 100644 index 4cb4986..0000000 --- a/SocketService.Framework.Crypto/Crc32.cs +++ /dev/null @@ -1,123 +0,0 @@ -/* Copyright (c) 2009. Tom Kaminski - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. */ -// CRC32 Code deriving from HashAlgorithm -using System; -using System.Security.Cryptography; - -public class Crc32 : HashAlgorithm -{ - public const uint DefaultSeed = 0xffffffff; - - readonly static uint[] CrcTable = new uint[] { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D - }; - - uint crcValue = 0; - - public override void Initialize() - { - crcValue = 0; - } - - protected override void HashCore(byte[] buffer, int start, int length) - { - crcValue ^= DefaultSeed; - - unchecked - { - while (--length >= 0) - { - crcValue = CrcTable[(crcValue ^ buffer[start++]) & 0xFF] ^ (crcValue >> 8); - } - } - - crcValue ^= DefaultSeed; - } - protected override byte[] HashFinal() - { - this.HashValue = new byte[] { (byte)((crcValue >> 24) & 0xff), - (byte)((crcValue >> 16) & 0xff), - (byte)((crcValue >> 8) & 0xff), - (byte)(crcValue & 0xff) }; - return this.HashValue; - } - public uint CrcValue - { - get - { - return (uint)((HashValue[0] << 24) | (HashValue[1] << 16) | (HashValue[2] << 8) | HashValue[3]); - } - } - public override int HashSize - { - get { return 32; } - } -} diff --git a/SocketService.Framework.Crypto/DiffieHellmanKey.cs b/SocketService.Framework.Crypto/DiffieHellmanKey.cs deleted file mode 100644 index e37787c..0000000 --- a/SocketService.Framework.Crypto/DiffieHellmanKey.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Crypto -{ - /// - /// - /// - [Serializable] - public class DiffieHellmanKey - { - private readonly BigInteger _value; - private readonly BigInteger _g; - private readonly BigInteger _prime; - - private DiffieHellmanKey() - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - /// The y. - public DiffieHellmanKey(BigInteger prime, BigInteger g, BigInteger y) - { - _g = g; - _prime = prime; - _value = y; - } - - /// - /// Gets the G. - /// - public BigInteger G - { - get { return _g; } - } - - /// - /// Gets the prime. - /// - public BigInteger Prime - { - get { return _prime; } - } - - /// - /// Gets the value. - /// - public BigInteger Value - { - get - { - return _value; - } - } - - /// - /// Convert to byte array. - /// - /// - public byte[] ToByteArray() - { - return _value.ToByteArray(); - } - - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - return _value.ToString(10); - } - } -} diff --git a/SocketService.Framework.Crypto/DiffieHellmanProvider.cs b/SocketService.Framework.Crypto/DiffieHellmanProvider.cs deleted file mode 100644 index 989dfcd..0000000 --- a/SocketService.Framework.Crypto/DiffieHellmanProvider.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Crypto -{ - /// - /// - /// - public class DiffieHellmanProvider - { - private readonly BigInteger _prime; - private readonly BigInteger _g; - private readonly BigInteger _secret; - - protected DiffieHellmanProvider() - { - throw new NotImplementedException(); - } - - /// - /// Initializes a new instance of the class. - /// - /// The prime. - /// The g. - /// The secret. - public DiffieHellmanProvider( - BigInteger prime, - BigInteger g, - BigInteger secret) - { - _prime = prime; - _g = g; - _secret = secret; - } - - /// - /// Gets the public key. - /// - public DiffieHellmanKey PublicKey - { - get - { - return new DiffieHellmanKey(_prime, _g, _g.ModPow(_secret, _prime)); - } - } - - /// - /// Creates the private key. - /// - /// The public key. - /// - public DiffieHellmanKey CreatePrivateKey(DiffieHellmanKey publicKey) - { - BigInteger yother = new BigInteger(publicKey.ToByteArray()); - return new DiffieHellmanKey(_prime, _g, yother.ModPow(_secret, _prime)); - } - - /// - /// Creates the private key. - /// - /// The public key. - /// - public DiffieHellmanKey CreatePrivateKey(byte[] publicKey) - { - BigInteger yother = new BigInteger(publicKey); - return new DiffieHellmanKey(_prime, _g, yother.ModPow(_secret, _prime)); - } - - /// - /// Imports the specified key data. - /// - /// The key data. - /// - public DiffieHellmanKey Import(byte[] keyData) - { - return new DiffieHellmanKey(_prime, _g, new BigInteger(keyData)); - } - } - -} diff --git a/SocketService.Framework.Crypto/Properties/AssemblyInfo.cs b/SocketService.Framework.Crypto/Properties/AssemblyInfo.cs deleted file mode 100644 index fea513c..0000000 --- a/SocketService.Framework.Crypto/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SocketService.Crytpo")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SocketService.Crytpo")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("eb8d9897-848e-4a17-9b0e-615a42ceb172")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketService.Framework.Crypto/SocketService.Crypto.csproj b/SocketService.Framework.Crypto/SocketService.Crypto.csproj deleted file mode 100644 index a81420d..0000000 --- a/SocketService.Framework.Crypto/SocketService.Crypto.csproj +++ /dev/null @@ -1,61 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {4138075A-49CD-4A46-92CB-DFF64A0BB0B6} - Library - Properties - SocketService.Crytpo - SocketService.Crytpo - v4.0 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SocketService.Framework.Crypto/StringExtentions.cs b/SocketService.Framework.Crypto/StringExtentions.cs deleted file mode 100644 index 1ff9adb..0000000 --- a/SocketService.Framework.Crypto/StringExtentions.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Security.Cryptography; -using System.IO; - -namespace SocketService.Crypto -{ - public static class StringExtentions - { - private static byte[] salt = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xF1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xF1 }; - - /// - /// Encrypts the specified secret. - /// - /// The secret. - /// The key. - /// The iv. - /// - public static byte[] Encrypt(this string secret, byte[] key, out byte[] iv) - { - using( TripleDES des = new TripleDESCryptoServiceProvider()) - { - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, des.IV, 50); - des.Key = db.GetBytes(des.KeySize / 8); - iv = des.IV; - - // Encrypt the message - byte[] plaintextMessage = Encoding.UTF8.GetBytes(secret); - - using (MemoryStream ciphertext = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(ciphertext, des.CreateEncryptor(), CryptoStreamMode.Write)) - { - cs.Write(plaintextMessage, 0, plaintextMessage.Length); - } - - return ciphertext.ToArray(); - } - } - } - - /// - /// Decrypts the specified cipher. - /// - /// The cipher. - /// The key. - /// The iv. - /// - public static string Decrypt(this byte[] cipher, byte[] key, byte[] iv) - { - using (TripleDES aes = new TripleDESCryptoServiceProvider()) - { - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, iv, 50); - aes.Key = db.GetBytes(aes.KeySize / 8); - aes.IV = iv; - - // Encrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, aes.CreateDecryptor(), CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - } - } -} diff --git a/SocketService.Framework.Crypto/StrongNumberProvider.cs b/SocketService.Framework.Crypto/StrongNumberProvider.cs deleted file mode 100644 index 031833d..0000000 --- a/SocketService.Framework.Crypto/StrongNumberProvider.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Security.Cryptography; - -namespace SocketService.Crypto -{ - [Serializable] - public class StrongNumberProvider - { - private static RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider(); - - /// - /// Gets the next U int32. - /// - /// - public uint GetNextUInt32() - { - byte[] res = new byte[4]; - csp.GetBytes(res); - return BitConverter.ToUInt32(res, 0); - } - - /// - /// Gets the next int. - /// - /// - public int GetNextInt() - { - byte[] res = new byte[4]; - csp.GetBytes(res); - return BitConverter.ToInt32(res, 0); - } - - /// - /// Gets the next single. - /// - /// - public Single GetNextSingle() - { - float numerator = GetNextUInt32(); - float denominator = uint.MaxValue; - return numerator / denominator; - } - } -} diff --git a/SocketService.Framework.Crypto/Wrapper.cs b/SocketService.Framework.Crypto/Wrapper.cs deleted file mode 100644 index ff4e50f..0000000 --- a/SocketService.Framework.Crypto/Wrapper.cs +++ /dev/null @@ -1,264 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.IO; -using System.Security.Cryptography; - -namespace SocketService.Crypto -{ - public class Wrapper : IDisposable - { - private readonly SymmetricAlgorithm _algorithm; - private readonly ICryptoTransform _transformer; - - private Wrapper() - { - throw new NotImplementedException(); - } - - private Wrapper(SymmetricAlgorithm algorithm, ICryptoTransform transform) - { - _algorithm = algorithm; - _transformer = transform; - } - - ~Wrapper() - { - Dispose(false); - } - - /// - /// Gets the IV. - /// - public byte[] IV - { - get { return _algorithm.IV; } - } - - /// - /// Creates the encryptor. - /// - /// Type of the alg. - /// The key. - /// The entropy. - /// - public static Wrapper CreateEncryptor(AlgorithmType algType, byte [] key, int entropy = 50) - { - SymmetricAlgorithm algorithm = null; - switch (algType) - { - case AlgorithmType.AES: - algorithm = new AesCryptoServiceProvider(); - break; - - case AlgorithmType.DES: - algorithm = new DESCryptoServiceProvider(); - break; - - case AlgorithmType.TripleDES: - algorithm = new TripleDESCryptoServiceProvider(); - break; - } - - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, algorithm.IV, entropy); - algorithm.Key = db.GetBytes(algorithm.KeySize / 8); - - return new Wrapper(algorithm, algorithm.CreateEncryptor()); - } - - /// - /// Creates the decryptor. - /// - /// Type of the alg. - /// The key. - /// The iv. - /// The entropy. - /// - public static Wrapper CreateDecryptor(AlgorithmType algType, byte[] key, byte[] iv, int entropy = 50) - { - SymmetricAlgorithm algorithm = null; - switch (algType) - { - case AlgorithmType.AES: - algorithm = new AesCryptoServiceProvider(); - break; - - case AlgorithmType.DES: - algorithm = new DESCryptoServiceProvider(); - break; - - case AlgorithmType.TripleDES: - algorithm = new TripleDESCryptoServiceProvider(); - break; - } - - Rfc2898DeriveBytes db = new Rfc2898DeriveBytes(key, iv, entropy); - algorithm.Key = db.GetBytes(algorithm.KeySize / 8); - algorithm.IV = iv; - - return new Wrapper(algorithm, algorithm.CreateDecryptor()); - } - - /// - /// Gets the crypto transformer. - /// - public ICryptoTransform CryptoTransformer - { - get - { - return _transformer; - } - - } - - /// - /// Encrypts the string. - /// - /// The secret. - /// - public byte[] EncryptString(string secret) - { - using (MemoryStream cipherText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(cipherText, _transformer, CryptoStreamMode.Write)) - { - byte[] plainText = Encoding.UTF8.GetBytes(secret); - cs.Write(plainText, 0, plainText.Length); - } - - return cipherText.ToArray(); - } - } - - /// - /// Encrypts the specified sensitive. - /// - /// The sensitive. - /// - public byte[] Encrypt(byte[] sensitive) - { - using (MemoryStream cipherStream = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(cipherStream, _transformer, CryptoStreamMode.Write)) - { - cs.Write(sensitive, 0, sensitive.Length); - } - - return cipherStream.ToArray(); - } - } - - /// - /// Decrypts the specified cipher. - /// - /// The cipher. - /// - public byte[] Decrypt(byte[] cipher) - { - // Decrypt the message - using (MemoryStream decrypted = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(decrypted, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return decrypted.ToArray(); - } - - } - - /// - /// Decrypts the string. - /// - /// The cipher string. - /// - public string DecryptString(string cipherString) - { - byte[] cipher = System.Text.Encoding.UTF8.GetBytes(cipherString); - - // Decrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - - /// - /// Decrypts the string. - /// - /// The cipher. - /// - public string DecryptString(byte [] cipher) - { - // Decrypt the message - using (MemoryStream plainText = new MemoryStream()) - { - using (CryptoStream cs = new CryptoStream(plainText, _transformer, CryptoStreamMode.Write)) - { - cs.Write(cipher, 0, cipher.Length); - } - - return Encoding.UTF8.GetString(plainText.ToArray()); - } - } - - private bool disposed = false; - - // Implement IDisposable. - // Do not make this method virtual. - // A derived class should not be able to override this method. - public void Dispose() - { - Dispose(true); - // This object will be cleaned up by the Dispose method. - // Therefore, you should call GC.SupressFinalize to - // take this object off the finalization queue - // and prevent finalization code for this object - // from executing a second time. - GC.SuppressFinalize(this); - } - - // Dispose(bool disposing) executes in two distinct scenarios. - // If disposing equals true, the method has been called directly - // or indirectly by a user's code. Managed and unmanaged resources - // can be disposed. - // If disposing equals false, the method has been called by the - // runtime from inside the finalizer and you should not reference - // other objects. Only unmanaged resources can be disposed. - protected virtual void Dispose(bool disposing) - { - // Check to see if Dispose has already been called. - if (!this.disposed) - { - // If disposing equals true, dispose all managed - // and unmanaged resources. - if (disposing) - { - // Dispose managed resources. - _algorithm.Dispose(); - } - - // Note disposing has been done. - disposed = true; - - } - } - - } - - public enum AlgorithmType - { - AES, - DES, - TripleDES, - Rjindal, - None - } -} diff --git a/SocketService.Framework/App.Config b/SocketService.Framework/App.Config deleted file mode 100644 index 4f78a04..0000000 --- a/SocketService.Framework/App.Config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/SocketService.Framework/Configuration/PluginInfoInstanceCollection.cs b/SocketService.Framework/Configuration/PluginInfoInstanceCollection.cs deleted file mode 100644 index f5156e2..0000000 --- a/SocketService.Framework/Configuration/PluginInfoInstanceCollection.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Configuration; - -namespace SocketService.Framework.Configuration -{ - public class PluginInfoInstanceCollection : ConfigurationElementCollection - { - protected override ConfigurationElement CreateNewElement() - { - return new PluginInfoInstanceElement(); - } - - protected override object GetElementKey(ConfigurationElement element) - { - return ((PluginInfoInstanceElement)element).Name; - } - } -} diff --git a/SocketService.Framework/Configuration/PluginInfoInstanceElement.cs b/SocketService.Framework/Configuration/PluginInfoInstanceElement.cs deleted file mode 100644 index 857c17b..0000000 --- a/SocketService.Framework/Configuration/PluginInfoInstanceElement.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Configuration; - -namespace SocketService.Framework.Configuration -{ - public class PluginInfoInstanceElement : ConfigurationElement - { - [ConfigurationProperty("name", IsKey = true, IsRequired = true)] - public string Name - { - get { return (string)base["name"]; } - set { base["name"] = value; } - } - - [ConfigurationProperty("path", IsRequired = true)] - public string Path - { - get { return (string)base["path"]; } - set { base["path"] = value; } - } - - } -} diff --git a/SocketService.Framework/Configuration/SocketServiceConfiguration.cs b/SocketService.Framework/Configuration/SocketServiceConfiguration.cs deleted file mode 100644 index 383fc97..0000000 --- a/SocketService.Framework/Configuration/SocketServiceConfiguration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Configuration; - -namespace SocketService.Framework.Configuration -{ - public class SocketServiceConfiguration : ConfigurationSection - { - [ConfigurationProperty("Plugins", IsRequired= true, IsDefaultCollection= true)] - public PluginInfoInstanceCollection Plugins - { - get { return (PluginInfoInstanceCollection)this["Plugins"]; } - set { this["Plugins"] = value; } - } - - [ConfigurationProperty("ListenPort", IsRequired = true)] - public int ListenPort - { - get { return (int)this["ListenPort"]; } - set { this["ListenPort"] = value; } - } - - } -} diff --git a/SocketService.Framework/Data/AutoIdElement.cs b/SocketService.Framework/Data/AutoIdElement.cs deleted file mode 100644 index 99fcc09..0000000 --- a/SocketService.Framework/Data/AutoIdElement.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Data -{ - public class AutoIdElement - { - private static object lockObject = new object(); - - private static long nextID = -1; - - public static long GetNextID() - { - lock (lockObject) - { - if (nextID == -1) nextID = DateTime.UtcNow.Ticks; else nextID++; - return nextID; - } - } - } -} diff --git a/SocketService.Framework/Data/DatabaseContextFactory.cs b/SocketService.Framework/Data/DatabaseContextFactory.cs deleted file mode 100644 index c940436..0000000 --- a/SocketService.Framework/Data/DatabaseContextFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Data -{ - public class DatabaseContextFactory - { - private static ServerDataEntities _context = null; - public static ServerDataEntities Context - { - get - { - if (_context == null) - { - _context = new ServerDataEntities(); - } - - return _context; - } - } - } -} diff --git a/SocketService.Framework/Data/IRepository.cs b/SocketService.Framework/Data/IRepository.cs deleted file mode 100644 index d467c01..0000000 --- a/SocketService.Framework/Data/IRepository.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Linq.Expressions; - -namespace SocketService.Framework.Data -{ - public interface IRepository - { - T Find(int id); - T[] GetAll(); - IQueryable Query(Expression> filter); - } -} diff --git a/SocketService.Framework/Data/Room.cs b/SocketService.Framework/Data/Room.cs deleted file mode 100644 index cc42e0a..0000000 --- a/SocketService.Framework/Data/Room.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Data -{ - public partial class Room - { - public Room() - { - Id = AutoIdElement.GetNextID(); - } - } -} diff --git a/SocketService.Framework/Data/ServerDataModel.Designer.cs b/SocketService.Framework/Data/ServerDataModel.Designer.cs deleted file mode 100644 index 1cbe231..0000000 --- a/SocketService.Framework/Data/ServerDataModel.Designer.cs +++ /dev/null @@ -1,1480 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated from a template. -// -// Manual changes to this file may cause unexpected behavior in your application. -// Manual changes to this file will be overwritten if the code is regenerated. -// -//------------------------------------------------------------------------------ - -using System; -using System.Data.Objects; -using System.Data.Objects.DataClasses; -using System.Data.EntityClient; -using System.ComponentModel; -using System.Xml.Serialization; -using System.Runtime.Serialization; - -[assembly: EdmSchemaAttribute()] -#region EDM Relationship Metadata - -[assembly: EdmRelationshipAttribute("ServerDataModel", "ZoneRoom", "Zone", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.Zone), "Room", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.Room), true)] -[assembly: EdmRelationshipAttribute("ServerDataModel", "RoomUser", "Room", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.Room), "User", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.User), true)] -[assembly: EdmRelationshipAttribute("ServerDataModel", "RoomRoomVariable", "Room", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.Room), "RoomVariable", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.RoomVariable), true)] -[assembly: EdmRelationshipAttribute("ServerDataModel", "UserUserVariable", "User", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.User), "UserVariable", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.UserVariable), true)] -[assembly: EdmRelationshipAttribute("ServerDataModel", "ExtensionPlugin", "Extension", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.Extension), "Plugin", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.Plugin), true)] -[assembly: EdmRelationshipAttribute("ServerDataModel", "RoomPlugin", "Room", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(SocketService.Framework.Data.Room), "Plugin", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(SocketService.Framework.Data.Plugin), true)] - -#endregion - -namespace SocketService.Framework.Data -{ - #region Contexts - - /// - /// No Metadata Documentation available. - /// - public partial class ServerDataEntities : ObjectContext - { - #region Constructors - - /// - /// Initializes a new ServerDataEntities object using the connection string found in the 'ServerDataEntities' section of the application configuration file. - /// - public ServerDataEntities() : base("name=ServerDataEntities", "ServerDataEntities") - { - this.ContextOptions.LazyLoadingEnabled = true; - OnContextCreated(); - } - - /// - /// Initialize a new ServerDataEntities object. - /// - public ServerDataEntities(string connectionString) : base(connectionString, "ServerDataEntities") - { - this.ContextOptions.LazyLoadingEnabled = true; - OnContextCreated(); - } - - /// - /// Initialize a new ServerDataEntities object. - /// - public ServerDataEntities(EntityConnection connection) : base(connection, "ServerDataEntities") - { - this.ContextOptions.LazyLoadingEnabled = true; - OnContextCreated(); - } - - #endregion - - #region Partial Methods - - partial void OnContextCreated(); - - #endregion - - #region ObjectSet Properties - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Zones - { - get - { - if ((_Zones == null)) - { - _Zones = base.CreateObjectSet("Zones"); - } - return _Zones; - } - } - private ObjectSet _Zones; - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Rooms - { - get - { - if ((_Rooms == null)) - { - _Rooms = base.CreateObjectSet("Rooms"); - } - return _Rooms; - } - } - private ObjectSet _Rooms; - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Users - { - get - { - if ((_Users == null)) - { - _Users = base.CreateObjectSet("Users"); - } - return _Users; - } - } - private ObjectSet _Users; - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Variables - { - get - { - if ((_Variables == null)) - { - _Variables = base.CreateObjectSet("Variables"); - } - return _Variables; - } - } - private ObjectSet _Variables; - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Extensions - { - get - { - if ((_Extensions == null)) - { - _Extensions = base.CreateObjectSet("Extensions"); - } - return _Extensions; - } - } - private ObjectSet _Extensions; - - /// - /// No Metadata Documentation available. - /// - public ObjectSet Plugins - { - get - { - if ((_Plugins == null)) - { - _Plugins = base.CreateObjectSet("Plugins"); - } - return _Plugins; - } - } - private ObjectSet _Plugins; - - #endregion - #region AddTo Methods - - /// - /// Deprecated Method for adding a new object to the Zones EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToZones(Zone zone) - { - base.AddObject("Zones", zone); - } - - /// - /// Deprecated Method for adding a new object to the Rooms EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToRooms(Room room) - { - base.AddObject("Rooms", room); - } - - /// - /// Deprecated Method for adding a new object to the Users EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToUsers(User user) - { - base.AddObject("Users", user); - } - - /// - /// Deprecated Method for adding a new object to the Variables EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToVariables(Variable variable) - { - base.AddObject("Variables", variable); - } - - /// - /// Deprecated Method for adding a new object to the Extensions EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToExtensions(Extension extension) - { - base.AddObject("Extensions", extension); - } - - /// - /// Deprecated Method for adding a new object to the Plugins EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. - /// - public void AddToPlugins(Plugin plugin) - { - base.AddObject("Plugins", plugin); - } - - #endregion - } - - - #endregion - - #region Entities - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="Extension")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class Extension : EntityObject - { - #region Factory Method - - /// - /// Create a new Extension object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - public static Extension CreateExtension(global::System.Int64 id, global::System.String name) - { - Extension extension = new Extension(); - extension.Id = id; - extension.Name = name; - return extension; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Name - { - get - { - return _Name; - } - set - { - OnNameChanging(value); - ReportPropertyChanging("Name"); - _Name = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Name"); - OnNameChanged(); - } - } - private global::System.String _Name; - partial void OnNameChanging(global::System.String value); - partial void OnNameChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "ExtensionPlugin", "Plugin")] - public EntityCollection Plugins - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.ExtensionPlugin", "Plugin"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.ExtensionPlugin", "Plugin", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="Plugin")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class Plugin : EntityObject - { - #region Factory Method - - /// - /// Create a new Plugin object. - /// - /// Initial value of the Id property. - /// Initial value of the Handle property. - /// Initial value of the ExtensionId property. - /// Initial value of the RoomId property. - public static Plugin CreatePlugin(global::System.Int64 id, global::System.String handle, global::System.Int64 extensionId, global::System.Int64 roomId) - { - Plugin plugin = new Plugin(); - plugin.Id = id; - plugin.Handle = handle; - plugin.ExtensionId = extensionId; - plugin.RoomId = roomId; - return plugin; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Handle - { - get - { - return _Handle; - } - set - { - OnHandleChanging(value); - ReportPropertyChanging("Handle"); - _Handle = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Handle"); - OnHandleChanged(); - } - } - private global::System.String _Handle; - partial void OnHandleChanging(global::System.String value); - partial void OnHandleChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 ExtensionId - { - get - { - return _ExtensionId; - } - set - { - OnExtensionIdChanging(value); - ReportPropertyChanging("ExtensionId"); - _ExtensionId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("ExtensionId"); - OnExtensionIdChanged(); - } - } - private global::System.Int64 _ExtensionId; - partial void OnExtensionIdChanging(global::System.Int64 value); - partial void OnExtensionIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 RoomId - { - get - { - return _RoomId; - } - set - { - OnRoomIdChanging(value); - ReportPropertyChanging("RoomId"); - _RoomId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("RoomId"); - OnRoomIdChanged(); - } - } - private global::System.Int64 _RoomId; - partial void OnRoomIdChanging(global::System.Int64 value); - partial void OnRoomIdChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "ExtensionPlugin", "Extension")] - public Extension Extension - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ExtensionPlugin", "Extension").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ExtensionPlugin", "Extension").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference ExtensionReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ExtensionPlugin", "Extension"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.ExtensionPlugin", "Extension", value); - } - } - } - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomPlugin", "Room")] - public Room Room - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomPlugin", "Room").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomPlugin", "Room").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference RoomReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomPlugin", "Room"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.RoomPlugin", "Room", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="Room")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class Room : EntityObject - { - #region Factory Method - - /// - /// Create a new Room object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - /// Initial value of the IsPersistable property. - /// Initial value of the Capacity property. - /// Initial value of the IsPrivate property. - /// Initial value of the Password property. - /// Initial value of the ZoneId property. - public static Room CreateRoom(global::System.Int64 id, global::System.String name, global::System.Boolean isPersistable, global::System.Int32 capacity, global::System.Boolean isPrivate, global::System.String password, global::System.Int64 zoneId) - { - Room room = new Room(); - room.Id = id; - room.Name = name; - room.IsPersistable = isPersistable; - room.Capacity = capacity; - room.IsPrivate = isPrivate; - room.Password = password; - room.ZoneId = zoneId; - return room; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Name - { - get - { - return _Name; - } - set - { - OnNameChanging(value); - ReportPropertyChanging("Name"); - _Name = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Name"); - OnNameChanged(); - } - } - private global::System.String _Name; - partial void OnNameChanging(global::System.String value); - partial void OnNameChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Boolean IsPersistable - { - get - { - return _IsPersistable; - } - set - { - OnIsPersistableChanging(value); - ReportPropertyChanging("IsPersistable"); - _IsPersistable = StructuralObject.SetValidValue(value); - ReportPropertyChanged("IsPersistable"); - OnIsPersistableChanged(); - } - } - private global::System.Boolean _IsPersistable; - partial void OnIsPersistableChanging(global::System.Boolean value); - partial void OnIsPersistableChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int32 Capacity - { - get - { - return _Capacity; - } - set - { - OnCapacityChanging(value); - ReportPropertyChanging("Capacity"); - _Capacity = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Capacity"); - OnCapacityChanged(); - } - } - private global::System.Int32 _Capacity; - partial void OnCapacityChanging(global::System.Int32 value); - partial void OnCapacityChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Boolean IsPrivate - { - get - { - return _IsPrivate; - } - set - { - OnIsPrivateChanging(value); - ReportPropertyChanging("IsPrivate"); - _IsPrivate = StructuralObject.SetValidValue(value); - ReportPropertyChanged("IsPrivate"); - OnIsPrivateChanged(); - } - } - private global::System.Boolean _IsPrivate; - partial void OnIsPrivateChanging(global::System.Boolean value); - partial void OnIsPrivateChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Password - { - get - { - return _Password; - } - set - { - OnPasswordChanging(value); - ReportPropertyChanging("Password"); - _Password = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Password"); - OnPasswordChanged(); - } - } - private global::System.String _Password; - partial void OnPasswordChanging(global::System.String value); - partial void OnPasswordChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 ZoneId - { - get - { - return _ZoneId; - } - set - { - OnZoneIdChanging(value); - ReportPropertyChanging("ZoneId"); - _ZoneId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("ZoneId"); - OnZoneIdChanged(); - } - } - private global::System.Int64 _ZoneId; - partial void OnZoneIdChanging(global::System.Int64 value); - partial void OnZoneIdChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "ZoneRoom", "Zone")] - public Zone Zone - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ZoneRoom", "Zone").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ZoneRoom", "Zone").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference ZoneReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.ZoneRoom", "Zone"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.ZoneRoom", "Zone", value); - } - } - } - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomUser", "User")] - public EntityCollection Users - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.RoomUser", "User"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.RoomUser", "User", value); - } - } - } - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomRoomVariable", "RoomVariable")] - public EntityCollection RoomVariables - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.RoomRoomVariable", "RoomVariable"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.RoomRoomVariable", "RoomVariable", value); - } - } - } - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomPlugin", "Plugin")] - public EntityCollection Plugins - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.RoomPlugin", "Plugin"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.RoomPlugin", "Plugin", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="RoomVariable")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class RoomVariable : Variable - { - #region Factory Method - - /// - /// Create a new RoomVariable object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - /// Initial value of the Value property. - /// Initial value of the RoomId property. - public static RoomVariable CreateRoomVariable(global::System.Int64 id, global::System.String name, global::System.Byte[] value, global::System.Int64 roomId) - { - RoomVariable roomVariable = new RoomVariable(); - roomVariable.Id = id; - roomVariable.Name = name; - roomVariable.Value = value; - roomVariable.RoomId = roomId; - return roomVariable; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 RoomId - { - get - { - return _RoomId; - } - set - { - OnRoomIdChanging(value); - ReportPropertyChanging("RoomId"); - _RoomId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("RoomId"); - OnRoomIdChanged(); - } - } - private global::System.Int64 _RoomId; - partial void OnRoomIdChanging(global::System.Int64 value); - partial void OnRoomIdChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomRoomVariable", "Room")] - public Room Room - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomRoomVariable", "Room").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomRoomVariable", "Room").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference RoomReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomRoomVariable", "Room"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.RoomRoomVariable", "Room", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="User")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class User : EntityObject - { - #region Factory Method - - /// - /// Create a new User object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - /// Initial value of the ClientKey property. - /// Initial value of the RoomId property. - public static User CreateUser(global::System.Int64 id, global::System.String name, global::System.Guid clientKey, global::System.Int64 roomId) - { - User user = new User(); - user.Id = id; - user.Name = name; - user.ClientKey = clientKey; - user.RoomId = roomId; - return user; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Name - { - get - { - return _Name; - } - set - { - OnNameChanging(value); - ReportPropertyChanging("Name"); - _Name = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Name"); - OnNameChanged(); - } - } - private global::System.String _Name; - partial void OnNameChanging(global::System.String value); - partial void OnNameChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Guid ClientKey - { - get - { - return _ClientKey; - } - set - { - OnClientKeyChanging(value); - ReportPropertyChanging("ClientKey"); - _ClientKey = StructuralObject.SetValidValue(value); - ReportPropertyChanged("ClientKey"); - OnClientKeyChanged(); - } - } - private global::System.Guid _ClientKey; - partial void OnClientKeyChanging(global::System.Guid value); - partial void OnClientKeyChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 RoomId - { - get - { - return _RoomId; - } - set - { - OnRoomIdChanging(value); - ReportPropertyChanging("RoomId"); - _RoomId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("RoomId"); - OnRoomIdChanged(); - } - } - private global::System.Int64 _RoomId; - partial void OnRoomIdChanging(global::System.Int64 value); - partial void OnRoomIdChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "RoomUser", "Room")] - public Room Room - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomUser", "Room").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomUser", "Room").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference RoomReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.RoomUser", "Room"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.RoomUser", "Room", value); - } - } - } - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "UserUserVariable", "UserVariable")] - public EntityCollection UserVariables - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.UserUserVariable", "UserVariable"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.UserUserVariable", "UserVariable", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="UserVariable")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class UserVariable : Variable - { - #region Factory Method - - /// - /// Create a new UserVariable object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - /// Initial value of the Value property. - /// Initial value of the UserId property. - public static UserVariable CreateUserVariable(global::System.Int64 id, global::System.String name, global::System.Byte[] value, global::System.Int64 userId) - { - UserVariable userVariable = new UserVariable(); - userVariable.Id = id; - userVariable.Name = name; - userVariable.Value = value; - userVariable.UserId = userId; - return userVariable; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 UserId - { - get - { - return _UserId; - } - set - { - OnUserIdChanging(value); - ReportPropertyChanging("UserId"); - _UserId = StructuralObject.SetValidValue(value); - ReportPropertyChanged("UserId"); - OnUserIdChanged(); - } - } - private global::System.Int64 _UserId; - partial void OnUserIdChanging(global::System.Int64 value); - partial void OnUserIdChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "UserUserVariable", "User")] - public User User - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.UserUserVariable", "User").Value; - } - set - { - ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.UserUserVariable", "User").Value = value; - } - } - /// - /// No Metadata Documentation available. - /// - [BrowsableAttribute(false)] - [DataMemberAttribute()] - public EntityReference UserReference - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("ServerDataModel.UserUserVariable", "User"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("ServerDataModel.UserUserVariable", "User", value); - } - } - } - - #endregion - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="Variable")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - [KnownTypeAttribute(typeof(RoomVariable))] - [KnownTypeAttribute(typeof(UserVariable))] - public partial class Variable : EntityObject - { - #region Factory Method - - /// - /// Create a new Variable object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - /// Initial value of the Value property. - public static Variable CreateVariable(global::System.Int64 id, global::System.String name, global::System.Byte[] value) - { - Variable variable = new Variable(); - variable.Id = id; - variable.Name = name; - variable.Value = value; - return variable; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Name - { - get - { - return _Name; - } - set - { - OnNameChanging(value); - ReportPropertyChanging("Name"); - _Name = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Name"); - OnNameChanged(); - } - } - private global::System.String _Name; - partial void OnNameChanging(global::System.String value); - partial void OnNameChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Byte[] Value - { - get - { - return StructuralObject.GetValidValue(_Value); - } - set - { - OnValueChanging(value); - ReportPropertyChanging("Value"); - _Value = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Value"); - OnValueChanged(); - } - } - private global::System.Byte[] _Value; - partial void OnValueChanging(global::System.Byte[] value); - partial void OnValueChanged(); - - #endregion - - } - - /// - /// No Metadata Documentation available. - /// - [EdmEntityTypeAttribute(NamespaceName="ServerDataModel", Name="Zone")] - [Serializable()] - [DataContractAttribute(IsReference=true)] - public partial class Zone : EntityObject - { - #region Factory Method - - /// - /// Create a new Zone object. - /// - /// Initial value of the Id property. - /// Initial value of the Name property. - public static Zone CreateZone(global::System.Int64 id, global::System.String name) - { - Zone zone = new Zone(); - zone.Id = id; - zone.Name = name; - return zone; - } - - #endregion - #region Primitive Properties - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] - [DataMemberAttribute()] - public global::System.Int64 Id - { - get - { - return _Id; - } - set - { - if (_Id != value) - { - OnIdChanging(value); - ReportPropertyChanging("Id"); - _Id = StructuralObject.SetValidValue(value); - ReportPropertyChanged("Id"); - OnIdChanged(); - } - } - } - private global::System.Int64 _Id; - partial void OnIdChanging(global::System.Int64 value); - partial void OnIdChanged(); - - /// - /// No Metadata Documentation available. - /// - [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] - [DataMemberAttribute()] - public global::System.String Name - { - get - { - return _Name; - } - set - { - OnNameChanging(value); - ReportPropertyChanging("Name"); - _Name = StructuralObject.SetValidValue(value, false); - ReportPropertyChanged("Name"); - OnNameChanged(); - } - } - private global::System.String _Name; - partial void OnNameChanging(global::System.String value); - partial void OnNameChanged(); - - #endregion - - #region Navigation Properties - - /// - /// No Metadata Documentation available. - /// - [XmlIgnoreAttribute()] - [SoapIgnoreAttribute()] - [DataMemberAttribute()] - [EdmRelationshipNavigationPropertyAttribute("ServerDataModel", "ZoneRoom", "Room")] - public EntityCollection Rooms - { - get - { - return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("ServerDataModel.ZoneRoom", "Room"); - } - set - { - if ((value != null)) - { - ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("ServerDataModel.ZoneRoom", "Room", value); - } - } - } - - #endregion - } - - #endregion - -} diff --git a/SocketService.Framework/Data/ServerDataModel.edmx b/SocketService.Framework/Data/ServerDataModel.edmx deleted file mode 100644 index 746e3ff..0000000 --- a/SocketService.Framework/Data/ServerDataModel.edmx +++ /dev/null @@ -1,534 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SocketService.Framework/Data/ServerDataModel.edmx.sqlce b/SocketService.Framework/Data/ServerDataModel.edmx.sqlce deleted file mode 100644 index 8c6adc3..0000000 --- a/SocketService.Framework/Data/ServerDataModel.edmx.sqlce +++ /dev/null @@ -1,284 +0,0 @@ - --- -------------------------------------------------- --- Entity Designer DDL Script for SQL Server Compact Edition --- -------------------------------------------------- --- Date Created: 09/26/2011 18:46:02 --- Generated from EDMX file: C:\Users\MonkeyBreath\Desktop\SocketServer\SocketService.Framework\Data\ServerDataModel.edmx --- -------------------------------------------------- - - --- -------------------------------------------------- --- Dropping existing FOREIGN KEY constraints --- NOTE: if the constraint does not exist, an ignorable error will be reported. --- -------------------------------------------------- - - ALTER TABLE [Rooms] DROP CONSTRAINT [FK_ZoneRoom]; -GO - ALTER TABLE [Users] DROP CONSTRAINT [FK_RoomUser]; -GO - ALTER TABLE [Variables_RoomVariable] DROP CONSTRAINT [FK_RoomRoomVariable]; -GO - ALTER TABLE [Variables_UserVariable] DROP CONSTRAINT [FK_UserUserVariable]; -GO - ALTER TABLE [Plugins] DROP CONSTRAINT [FK_ExtensionPlugin]; -GO - ALTER TABLE [Plugins] DROP CONSTRAINT [FK_RoomPlugin]; -GO - ALTER TABLE [Variables_RoomVariable] DROP CONSTRAINT [FK_RoomVariable_inherits_Variable]; -GO - ALTER TABLE [Variables_UserVariable] DROP CONSTRAINT [FK_UserVariable_inherits_Variable]; -GO - --- -------------------------------------------------- --- Dropping existing tables --- NOTE: if the table does not exist, an ignorable error will be reported. --- -------------------------------------------------- - - DROP TABLE [Zones]; -GO - DROP TABLE [Rooms]; -GO - DROP TABLE [Users]; -GO - DROP TABLE [Variables]; -GO - DROP TABLE [Extensions]; -GO - DROP TABLE [Plugins]; -GO - DROP TABLE [Variables_RoomVariable]; -GO - DROP TABLE [Variables_UserVariable]; -GO - --- -------------------------------------------------- --- Creating all tables --- -------------------------------------------------- - --- Creating table 'Zones' -CREATE TABLE [Zones] ( - [Id] bigint NOT NULL, - [Name] nvarchar(4000) NOT NULL -); -GO - --- Creating table 'Rooms' -CREATE TABLE [Rooms] ( - [Id] bigint NOT NULL, - [Name] nvarchar(4000) NOT NULL, - [IsPersistable] bit NOT NULL, - [Capacity] int NOT NULL, - [IsPrivate] bit NOT NULL, - [Password] nvarchar(4000) NOT NULL, - [ZoneId] bigint NOT NULL -); -GO - --- Creating table 'Users' -CREATE TABLE [Users] ( - [Id] bigint NOT NULL, - [Name] nvarchar(4000) NOT NULL, - [ClientKey] uniqueidentifier NOT NULL, - [RoomId] bigint NOT NULL -); -GO - --- Creating table 'Variables' -CREATE TABLE [Variables] ( - [Id] bigint NOT NULL, - [Name] nvarchar(4000) NOT NULL, - [Value] varbinary(8000) NOT NULL -); -GO - --- Creating table 'Extensions' -CREATE TABLE [Extensions] ( - [Id] bigint NOT NULL, - [Name] nvarchar(4000) NOT NULL -); -GO - --- Creating table 'Plugins' -CREATE TABLE [Plugins] ( - [Id] bigint IDENTITY(1,1) NOT NULL, - [Handle] nvarchar(4000) NOT NULL, - [ExtensionId] bigint NOT NULL, - [RoomId] bigint NOT NULL -); -GO - --- Creating table 'Variables_RoomVariable' -CREATE TABLE [Variables_RoomVariable] ( - [RoomId] bigint NOT NULL, - [Id] bigint NOT NULL -); -GO - --- Creating table 'Variables_UserVariable' -CREATE TABLE [Variables_UserVariable] ( - [UserId] bigint NOT NULL, - [Id] bigint NOT NULL -); -GO - --- -------------------------------------------------- --- Creating all PRIMARY KEY constraints --- -------------------------------------------------- - --- Creating primary key on [Id] in table 'Zones' -ALTER TABLE [Zones] -ADD CONSTRAINT [PK_Zones] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Rooms' -ALTER TABLE [Rooms] -ADD CONSTRAINT [PK_Rooms] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Users' -ALTER TABLE [Users] -ADD CONSTRAINT [PK_Users] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Variables' -ALTER TABLE [Variables] -ADD CONSTRAINT [PK_Variables] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Extensions' -ALTER TABLE [Extensions] -ADD CONSTRAINT [PK_Extensions] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Plugins' -ALTER TABLE [Plugins] -ADD CONSTRAINT [PK_Plugins] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Variables_RoomVariable' -ALTER TABLE [Variables_RoomVariable] -ADD CONSTRAINT [PK_Variables_RoomVariable] - PRIMARY KEY ([Id] ); -GO - --- Creating primary key on [Id] in table 'Variables_UserVariable' -ALTER TABLE [Variables_UserVariable] -ADD CONSTRAINT [PK_Variables_UserVariable] - PRIMARY KEY ([Id] ); -GO - --- -------------------------------------------------- --- Creating all FOREIGN KEY constraints --- -------------------------------------------------- - --- Creating foreign key on [ZoneId] in table 'Rooms' -ALTER TABLE [Rooms] -ADD CONSTRAINT [FK_ZoneRoom] - FOREIGN KEY ([ZoneId]) - REFERENCES [Zones] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_ZoneRoom' -CREATE INDEX [IX_FK_ZoneRoom] -ON [Rooms] - ([ZoneId]); -GO - --- Creating foreign key on [RoomId] in table 'Users' -ALTER TABLE [Users] -ADD CONSTRAINT [FK_RoomUser] - FOREIGN KEY ([RoomId]) - REFERENCES [Rooms] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_RoomUser' -CREATE INDEX [IX_FK_RoomUser] -ON [Users] - ([RoomId]); -GO - --- Creating foreign key on [RoomId] in table 'Variables_RoomVariable' -ALTER TABLE [Variables_RoomVariable] -ADD CONSTRAINT [FK_RoomRoomVariable] - FOREIGN KEY ([RoomId]) - REFERENCES [Rooms] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_RoomRoomVariable' -CREATE INDEX [IX_FK_RoomRoomVariable] -ON [Variables_RoomVariable] - ([RoomId]); -GO - --- Creating foreign key on [UserId] in table 'Variables_UserVariable' -ALTER TABLE [Variables_UserVariable] -ADD CONSTRAINT [FK_UserUserVariable] - FOREIGN KEY ([UserId]) - REFERENCES [Users] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_UserUserVariable' -CREATE INDEX [IX_FK_UserUserVariable] -ON [Variables_UserVariable] - ([UserId]); -GO - --- Creating foreign key on [ExtensionId] in table 'Plugins' -ALTER TABLE [Plugins] -ADD CONSTRAINT [FK_ExtensionPlugin] - FOREIGN KEY ([ExtensionId]) - REFERENCES [Extensions] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_ExtensionPlugin' -CREATE INDEX [IX_FK_ExtensionPlugin] -ON [Plugins] - ([ExtensionId]); -GO - --- Creating foreign key on [RoomId] in table 'Plugins' -ALTER TABLE [Plugins] -ADD CONSTRAINT [FK_RoomPlugin] - FOREIGN KEY ([RoomId]) - REFERENCES [Rooms] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; - --- Creating non-clustered index for FOREIGN KEY 'FK_RoomPlugin' -CREATE INDEX [IX_FK_RoomPlugin] -ON [Plugins] - ([RoomId]); -GO - --- Creating foreign key on [Id] in table 'Variables_RoomVariable' -ALTER TABLE [Variables_RoomVariable] -ADD CONSTRAINT [FK_RoomVariable_inherits_Variable] - FOREIGN KEY ([Id]) - REFERENCES [Variables] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; -GO - --- Creating foreign key on [Id] in table 'Variables_UserVariable' -ALTER TABLE [Variables_UserVariable] -ADD CONSTRAINT [FK_UserVariable_inherits_Variable] - FOREIGN KEY ([Id]) - REFERENCES [Variables] - ([Id]) - ON DELETE NO ACTION ON UPDATE NO ACTION; -GO - --- -------------------------------------------------- --- Script has ended --- -------------------------------------------------- \ No newline at end of file diff --git a/SocketService.Framework/Data/User.cs b/SocketService.Framework/Data/User.cs deleted file mode 100644 index 2fbf217..0000000 --- a/SocketService.Framework/Data/User.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Data -{ - public partial class User - { - public User() - { - Id = AutoIdElement.GetNextID(); - } - - } -} diff --git a/SocketService.Framework/Data/Zone.cs b/SocketService.Framework/Data/Zone.cs deleted file mode 100644 index adef25b..0000000 --- a/SocketService.Framework/Data/Zone.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Data -{ - public partial class Zone - { - public Zone() - { - Id = AutoIdElement.GetNextID(); - } - } -} diff --git a/SocketService.Framework/Messaging/BaseMessageHandler.cs b/SocketService.Framework/Messaging/BaseMessageHandler.cs deleted file mode 100644 index ec8f35a..0000000 --- a/SocketService.Framework/Messaging/BaseMessageHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Messaging -{ - [Serializable] - public abstract class BaseMessageHandler : ICommand - { - public abstract void Execute(); - } -} diff --git a/SocketService.Framework/Messaging/ICommand.cs b/SocketService.Framework/Messaging/ICommand.cs deleted file mode 100644 index 4ba28f7..0000000 --- a/SocketService.Framework/Messaging/ICommand.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Messaging -{ - public interface ICommand - { - void Execute(); - } -} diff --git a/SocketService.Framework/Messaging/MSMQQueueWatcher.cs b/SocketService.Framework/Messaging/MSMQQueueWatcher.cs deleted file mode 100644 index 1659dc1..0000000 --- a/SocketService.Framework/Messaging/MSMQQueueWatcher.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Messaging; -using System.Diagnostics; -using log4net; -using System.Reflection; - -namespace SocketService.Framework.Messaging -{ - public class MSMQQueueWatcher : IDisposable - { - private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private readonly MessageQueue _receiveQueue; - - /// - /// Initializes a new instance of the class. - /// - /// Name of the queue. - public MSMQQueueWatcher(string queueName) - { - // open the queue - _receiveQueue = new MessageQueue(queueName); - _receiveQueue.Formatter = new BinaryMessageFormatter(); - } - - /// - /// Closes the queue. - /// - public void CloseQueue() - { - _receiveQueue.Close(); - } - - /// - /// Recieves the message. - /// - /// - /// The milliseconds. - /// - public T RecieveMessage(int milliseconds) where T : class - { - T t = default(T); - try - { - Message myMessage = _receiveQueue.Receive(TimeSpan.FromMilliseconds(milliseconds)); - t = myMessage.Body as T; - } - catch (MessageQueueException e) - { - // if MessageQueue.Receive times out, we'll ignore the exception - // otherwise, do something useful with the error (log, display, etc.) - if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout) - { - Log.ErrorFormat("Error: ({0}) {1}", e.ErrorCode, e.Message); - } - } - return t; - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - CloseQueue(); - } - } -} diff --git a/SocketService.Framework/Messaging/MSMQQueueWrapper.cs b/SocketService.Framework/Messaging/MSMQQueueWrapper.cs deleted file mode 100644 index 3dae7f5..0000000 --- a/SocketService.Framework/Messaging/MSMQQueueWrapper.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Messaging; -using System.Configuration; -using log4net; -using System.Reflection; - -namespace SocketService.Framework.Messaging -{ - public class MSMQQueueWrapper - { - private static string _queuePath; - private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - static MSMQQueueWrapper() - { - _queuePath = ConfigurationManager.AppSettings["ServerMessageQueue"]; - } - - /// - /// Queues the command. - /// - /// The c. - public static void QueueCommand(ICommand c) - { - try - { - // open the queue - MessageQueue mq = new MessageQueue(_queuePath); - - // set the message to durable. - mq.DefaultPropertiesToSend.Recoverable = true; - - // set the formatter to Binary, default is XML - mq.Formatter = new BinaryMessageFormatter(); - - // send the command object - mq.Send(c, "Command Message"); - mq.Close(); - } - catch (Exception e) - { - Log.ErrorFormat("Error: {0}", e.Message); - } - } - - } -} diff --git a/SocketService.Framework/Messaging/MessageServer.cs b/SocketService.Framework/Messaging/MessageServer.cs deleted file mode 100644 index 537cba5..0000000 --- a/SocketService.Framework/Messaging/MessageServer.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Messaging; -using System.Threading; -using System.Configuration; -using System.Reflection; -using log4net; - -namespace SocketService.Framework.Messaging -{ - public class MessageServer : MSMQQueueWatcher - { - private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false); - private readonly ManualResetEvent _pauseEvent = new ManualResetEvent(false); - - private bool _running = false; - - private readonly string _queuePath; - /// - /// Initializes a new instance of the class. - /// - public MessageServer() : base(ConfigurationManager.AppSettings["ServerMessageQueue"]) - { - _queuePath = ConfigurationManager.AppSettings["ServerMessageQueue"]; - - // create queue, if it doesn't exist - if (!MessageQueue.Exists(_queuePath)) - MessageQueue.Create(_queuePath); - } - - /// - /// Starts this instance. - /// - public void Start() - { - if (!_running) - { - _stopEvent.Reset(); - _running = true; - - int numProcessors = System.Environment.ProcessorCount; - double numThreadsPerProcessor = 1.5; - int numThreads = (int)((double)numProcessors * numThreadsPerProcessor) + 1; - - for (int i = 0; i < numThreads; i++) - { - Thread serverThread = new Thread(new ThreadStart(Serve)); - serverThread.Start(); - } - } - } - - /// - /// Stops this instance. - /// - public void Stop() - { - _stopEvent.Set(); - _running = false; - } - - /// - /// Pauses this instance. - /// - public void Pause() - { - // TODO: Implement Pause - } - - /// - /// Resumes this instance. - /// - public void Resume() - { - // TODO: Implement Resume - } - - protected void Serve() - { - while (!_stopEvent.WaitOne(50)) - { - ICommand command = RecieveMessage(500); - if (command != null) - { - try - { - command.Execute(); - } - catch (Exception e) - { - Log.ErrorFormat("Error: {0}", e.Message); - } - - } - } - } - } -} diff --git a/SocketService.Framework/Properties/AssemblyInfo.cs b/SocketService.Framework/Properties/AssemblyInfo.cs deleted file mode 100644 index 0a088dd..0000000 --- a/SocketService.Framework/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("SocketService.Framework")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("SocketService.Framework")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9c7d6078-99b8-4145-b9b7-8744625cb764")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketService.Framework/ServiceHandlerLib/BaseHandler.cs b/SocketService.Framework/ServiceHandlerLib/BaseHandler.cs deleted file mode 100644 index f9043a0..0000000 --- a/SocketService.Framework/ServiceHandlerLib/BaseHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; - -namespace SocketService.Framework.ServiceHandlerLib -{ - [Serializable] - public abstract class BaseHandler : IServiceHandler where T : class - { - public bool HandleRequest(object request, object state) - { - return HandleRequest(request as T, (P)state); - } - - public abstract bool HandleRequest(T request, P state); - } -} diff --git a/SocketService.Framework/ServiceHandlerLib/IServiceHandler.cs b/SocketService.Framework/ServiceHandlerLib/IServiceHandler.cs deleted file mode 100644 index abcc15a..0000000 --- a/SocketService.Framework/ServiceHandlerLib/IServiceHandler.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; - -namespace SocketService.Framework.ServiceHandlerLib -{ - public interface IServiceHandler - { - bool HandleRequest(object request, object state); - } -} diff --git a/SocketService.Framework/ServiceHandlerLib/IServiceHandlerMetaData.cs b/SocketService.Framework/ServiceHandlerLib/IServiceHandlerMetaData.cs deleted file mode 100644 index dd20a29..0000000 --- a/SocketService.Framework/ServiceHandlerLib/IServiceHandlerMetaData.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.ServiceHandlerLib -{ - public interface IServiceHandlerMetaData - { - Type HandlerType - { - get; - } - } -} diff --git a/SocketService.Framework/ServiceHandlerLib/IServiceHandlerRepository.cs b/SocketService.Framework/ServiceHandlerLib/IServiceHandlerRepository.cs deleted file mode 100644 index f0f3bdc..0000000 --- a/SocketService.Framework/ServiceHandlerLib/IServiceHandlerRepository.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.ServiceHandlerLib -{ - public interface IServiceHandlerRepository - { - /// - /// Gets the handler list by type. - /// - /// The type. - /// - List GetHandlerListByType(Type type); - - /// - /// Loads the handlers. - /// - /// The handler path. - void LoadHandlers(); - - } -} diff --git a/SocketService.Framework/ServiceHandlerLib/ServiceHandlerRepository.cs b/SocketService.Framework/ServiceHandlerLib/ServiceHandlerRepository.cs deleted file mode 100644 index f378f88..0000000 --- a/SocketService.Framework/ServiceHandlerLib/ServiceHandlerRepository.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; -using System.ComponentModel.Composition.Hosting; -using System.Reflection; -using System.IO; -using System.Configuration; -using SocketService.Framework.Configuration; -using SocketService.Framework.ServiceHandlerLib; - -namespace SocketService.Framework.ServiceHandlerLib -{ - public class ServiceHandlerRepository : IServiceHandlerRepository - { - [ImportMany] - protected IEnumerable> _handlerList; - - private static ServiceHandlerRepository _instance = null; - - /// - /// Initializes the class. - /// - static ServiceHandlerRepository() - { - Instance.LoadHandlers(); - } - - /// - /// Gets the instance. - /// - public static ServiceHandlerRepository Instance - { - get - { - if (_instance == null) - { - _instance = new ServiceHandlerRepository(); - } - - return _instance; - } - } - - protected ServiceHandlerRepository() - { - //string handlerPath - } - - /// - /// Gets the handler list by type. - /// - /// The type. - /// - public List GetHandlerListByType(Type type) - { - List serviceHandlers = new List(); - - serviceHandlers = _handlerList - .Where((h) => h.Metadata.HandlerType == type) - .Select((lz) => lz.Value) - .ToList(); - - return serviceHandlers; - } - - /// - /// Loads the handlers. - /// - /// The handler path. - public void LoadHandlers() - { - SocketServiceConfiguration config = null; - - try - { config = (SocketServiceConfiguration)ConfigurationManager.GetSection("SocketServerConfiguration"); } - catch (Exception ex) - { } - - var aggregateCatalog = new AggregateCatalog(); - - Assembly callingAssembly = Assembly.GetExecutingAssembly(); - - // an assembly catalog to load information about parts from this assembly - var assemblyCatalog = new AssemblyCatalog(callingAssembly); - var directoryCatalog = new DirectoryCatalog(Path.GetDirectoryName(callingAssembly.Location), "*.dll"); - - aggregateCatalog.Catalogs.Add(assemblyCatalog); - aggregateCatalog.Catalogs.Add(directoryCatalog); - - // create a container for our catalogs - var container = new CompositionContainer(aggregateCatalog); - - // finally, compose the parts - container.ComposeParts(this); - } - } -} diff --git a/SocketService.Framework/ServiceHandlerLib/ServiceHandlerTypeAttribute.cs b/SocketService.Framework/ServiceHandlerLib/ServiceHandlerTypeAttribute.cs deleted file mode 100644 index 95ea534..0000000 --- a/SocketService.Framework/ServiceHandlerLib/ServiceHandlerTypeAttribute.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; - -namespace SocketService.Framework.ServiceHandlerLib -{ - [MetadataAttribute] - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] - public class ServiceHandlerTypeAttribute : ExportAttribute, IServiceHandlerMetaData - { - /// - /// Initializes a new instance of the class. - /// - public ServiceHandlerTypeAttribute() - : this(null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Type of the handler. - public ServiceHandlerTypeAttribute(Type handlerType) - : base(typeof(IServiceHandler)) - { - HandlerType = handlerType; - } - - #region IHandlerType Members - - public Type HandlerType - { - get; - set; - } - - #endregion - } -} diff --git a/SocketService.Framework/SocketService.Framework.csproj b/SocketService.Framework/SocketService.Framework.csproj deleted file mode 100644 index 01584e5..0000000 --- a/SocketService.Framework/SocketService.Framework.csproj +++ /dev/null @@ -1,145 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B} - Library - Properties - SocketService.Framework - SocketService.Framework - v4.0 - 512 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\References\log4net.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - ServerDataModel.edmx - - - - - - - - - - - {93FD4F32-5214-40E3-8E36-5B4E354F10C4} - SocketService.Framework.Client - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - SQL Server Compact 3.5 SP2 - true - - - False - Windows Installer 3.1 - true - - - - - EntityModelCodeGenerator - ServerDataModel.Designer.cs - - - - - - - - - \ No newline at end of file diff --git a/SocketService.Framework/Util/SingletonBase.cs b/SocketService.Framework/Util/SingletonBase.cs deleted file mode 100644 index 16898f6..0000000 --- a/SocketService.Framework/Util/SingletonBase.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace SocketService.Framework.Util -{ - public class SingletonBase where T : new() - { - private static T _instance = default(T); - - /// - /// Gets the instance. - /// - public static T Instance - { - get - { - if( _instance == null ) - { - _instance = new T(); - } - - return _instance; - } - } - } -} diff --git a/SocketService/Actions/RoomActionEngine.cs b/SocketService/Actions/RoomActionEngine.cs index e46607e..078fbda 100644 --- a/SocketService/Actions/RoomActionEngine.cs +++ b/SocketService/Actions/RoomActionEngine.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Util; -using SocketService.Framework.SharedObjects; -using SocketService.Framework.Data; +using System.Linq; +using SocketService.Core.Data; +using SocketService.Core.Util; using SocketService.Repository; +using RoomVariable = SocketService.Core.Data.RoomVariable; +using Zone = SocketService.Core.Data.Zone; namespace SocketService.Actions { @@ -15,10 +13,10 @@ class RoomActionEngine : SingletonBase public Room CreateRoom(string roomName, Zone zone) { - Room room = RoomRepository.Instance.Query( r => r.Name.Equals(roomName) ).FirstOrDefault(); + var room = RoomRepository.Instance.Query( r => r.Name.Equals(roomName) ).FirstOrDefault(); if (room == null) { - room = new Room() { Name = roomName, Password = string.Empty, Capacity = -1, IsPersistable = false, IsPrivate = false, Zone = zone }; + room = new Room { Name = roomName, Password = string.Empty, Capacity = -1, IsPersistable = false, IsPrivate = false, Zone = zone }; RoomRepository.Instance.Add(room); zone.Rooms.Add(room); @@ -99,13 +97,23 @@ public Room CreateRoom(string roomName, Zone zone) //{ // throw new NotImplementedException(); //} + + public void CreateRoomVariable(Room room, string variableName, byte [] value) + { + var variable = new RoomVariable(); + variable.Name = variableName; + variable.Value = value; + + room.RoomVariables.Add(variable); + RoomRepository.Instance.Update(room); + } public void RemoveNonPersistentRooms() { - List rooms = RoomRepository.Instance.Query(r => !r.IsPersistable).ToList(); - foreach (Room room in rooms) + var rooms = RoomRepository.Instance.Query(r => !r.IsPersistable).ToList(); + foreach (var room in rooms) { - Zone zone = room.Zone; + var zone = room.Zone; if (zone != null) { zone.Rooms.Remove(room); diff --git a/SocketService/Actions/UserActionEngine.cs b/SocketService/Actions/UserActionEngine.cs index 9d24421..ad00ab0 100644 --- a/SocketService/Actions/UserActionEngine.cs +++ b/SocketService/Actions/UserActionEngine.cs @@ -1,13 +1,9 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Net; -using SocketService.Command; -using SocketService.Framework.Util; -using SocketService.Framework.Data; -using SocketService.Framework.SharedObjects; +using SocketService.Core.Data; +using SocketService.Core.Util; using SocketService.Repository; +using User = SocketService.Core.Data.User; namespace SocketService.Actions { @@ -15,63 +11,58 @@ class UserActionEngine : SingletonBase { public void LogoutUser(Guid clientId) { - User user = UserRepository.Instance.Query(u => u.ClientKey.Equals(clientId)).FirstOrDefault(); - if (user != null) + var user = UserRepository.Instance.Query(u => u.ClientKey.Equals(clientId)).FirstOrDefault(); + if (user == null) return; + if (user.Room != null) { - if (user.Room != null) - { - user.Room.Users.Remove(user); - } - - UserRepository.Instance.Delete(user); + user.Room.Users.Remove(user); } + + UserRepository.Instance.Delete(user); } public bool LoginUser(Guid clientId, string loginName, Room entryRoom) { // check for duplicates - User duplicateUser = UserRepository.Instance.Query(u => u.Name.Equals(loginName)).FirstOrDefault(); + var duplicateUser = UserRepository.Instance.Query(u => u.Name.Equals(loginName)).FirstOrDefault(); if (duplicateUser != null) { return false; } - else - { - User user = new User() { ClientKey = clientId, Name = loginName, Room = entryRoom }; - UserRepository.Instance.Add(user); - entryRoom.Users.Add(user); + var user = new User { ClientKey = clientId, Name = loginName, Room = entryRoom }; + UserRepository.Instance.Add(user); - RoomRepository.Instance.Update(entryRoom); - UserRepository.Instance.Update(user); + entryRoom.Users.Add(user); - return true; - } + RoomRepository.Instance.Update(entryRoom); + UserRepository.Instance.Update(user); + + return true; } public void ClientChangeRoom(Guid clientId, string roomName) { - User user = UserRepository.Instance.Query(u => u.ClientKey.Equals(clientId)).FirstOrDefault(); - Room room = RoomRepository.Instance.Query(r => r.Name.Equals(roomName)).FirstOrDefault(); + var user = UserRepository.Instance.Query(u => u.ClientKey.Equals(clientId)).FirstOrDefault(); + var room = RoomRepository.Instance.Query(r => r.Name.Equals(roomName)).FirstOrDefault(); - if (user != null && room != null) - { - // remove from old room - if (user.Room != null) - { - room.Users.Remove(user); - } + if (user == null || room == null) return; - room.Users.Add(user); - RoomRepository.Instance.Update(room); - UserRepository.Instance.Update(user); + // remove from old room + if (user.Room != null) + { + room.Users.Remove(user); } + + room.Users.Add(user); + RoomRepository.Instance.Update(room); + UserRepository.Instance.Update(user); } public void RemoveAllUsers() { - User [] users = UserRepository.Instance.GetAll(); - foreach (User user in users) + var users = UserRepository.Instance.GetAll(); + foreach (var user in users) { user.Room.Users.Remove(user); diff --git a/SocketService/Actions/ZoneActionEngine.cs b/SocketService/Actions/ZoneActionEngine.cs index 0365ffb..253b344 100644 --- a/SocketService/Actions/ZoneActionEngine.cs +++ b/SocketService/Actions/ZoneActionEngine.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Util; +using System.Linq; +using SocketService.Core.Data; +using SocketService.Core.Util; using SocketService.Framework.Data; using SocketService.Repository; @@ -14,10 +12,10 @@ class ZoneActionEngine : SingletonBase public Zone CreateZone(string zoneName) { - Zone zone = ZoneRepository.Instance.Query( z => z.Name.Equals(zoneName) ).FirstOrDefault(); + var zone = ZoneRepository.Instance.Query( z => z.Name.Equals(zoneName) ).FirstOrDefault(); if (zone == null) { - zone = new Zone() { Name = zoneName }; + zone = new Zone { Name = zoneName }; ZoneRepository.Instance.Add(zone); } diff --git a/SocketService/Command/BroadcastObjectCommand.cs b/SocketService/Command/BroadcastObjectCommand.cs index 575ac83..32fbd36 100644 --- a/SocketService/Command/BroadcastObjectCommand.cs +++ b/SocketService/Command/BroadcastObjectCommand.cs @@ -1,11 +1,10 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.Client.Serialize; -using SocketService.Framework.Client.Sockets; +using System.Reflection; +using SocketService.Core.Messaging; using SocketService.Net; +using SocketService.Shared; +using log4net; namespace SocketService.Command { @@ -15,6 +14,8 @@ class BroadcastObjectCommand : BaseMessageHandler private readonly Guid [] _clientList; private readonly byte[] _data; + private readonly static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + public BroadcastObjectCommand(Guid [] clientList, object graph) { _clientList = clientList; @@ -23,19 +24,15 @@ public BroadcastObjectCommand(Guid [] clientList, object graph) public override void Execute() { - foreach (Guid clientId in _clientList) + foreach (var connection in _clientList.Select(clientId => SocketRepository.Instance.FindByClientId(clientId)).Where(connection => connection != null)) { - ZipSocket connection = SocketRepository.Instance.FindByClientId(clientId); - if (connection != null) + try + { + connection.SendData(_data); + } + catch (Exception ex) { - try - { - connection.SendData(_data); - } - catch (Exception) - { - // TODO: Log exception here - } + Log.Error(ex); } } } diff --git a/SocketService/Command/CreateRoomCommand.cs b/SocketService/Command/CreateRoomCommand.cs index fa7fc33..6d5aa35 100644 --- a/SocketService/Command/CreateRoomCommand.cs +++ b/SocketService/Command/CreateRoomCommand.cs @@ -1,13 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; +using SocketService.Core.Messaging; using SocketService.Actions; -using SocketService.Framework.Data; -using SocketService.Framework.Client.Response; -using SocketService.Framework.Client.Event; -using SocketService.Framework.SharedObjects; +using SocketService.Repository; namespace SocketService.Command { @@ -21,13 +16,25 @@ public CreateRoomCommand(Guid clientId, string zoneName, string roomName) { _clientId = clientId; _roomName = roomName; + _zoneName = zoneName; } public override void Execute() { + var newZone = ZoneActionEngine.Instance.CreateZone(_zoneName); + + if( newZone != null) + { + var newRoom = RoomActionEngine.Instance.CreateRoom(_roomName, newZone); + var user = UserRepository.Instance.Query(u => u.ClientKey.Equals(_clientId)).FirstOrDefault(); + + if( user != null && newRoom != null) + { + + } + } + //Zone newZone = ZoneActionEngine.Instance.CreateZone(_zoneName); - //Room newRoom = RoomActionEngine.Instance.CreateRoom(_roomName); - //User user = UserRepository.Instance.FindUserByClientKey(_clientId); //if (user != null && user.Room.Name != _roomName) //{ diff --git a/SocketService/Command/CreateRoomVariableCommand.cs b/SocketService/Command/CreateRoomVariableCommand.cs index 2761ecf..a64484f 100644 --- a/SocketService/Command/CreateRoomVariableCommand.cs +++ b/SocketService/Command/CreateRoomVariableCommand.cs @@ -1,22 +1,23 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework; -using SocketService.Framework.SharedObjects; +using SocketService.Core.Messaging; +using SocketService.Event; +using SocketService.Actions; +using SocketService.Repository; +using SocketService.Shared; namespace SocketService.Command { [Serializable] - class CreateRoomVariableCommand : BaseMessageHandler + internal class CreateRoomVariableCommand : BaseMessageHandler { private readonly Guid _clientId; - private readonly int _zoneId; - private readonly int _roomId; private readonly string _name; - private readonly SharedObject _so; - public CreateRoomVariableCommand(Guid clientId, int zoneId, int roomId, string name, SharedObject so) + private readonly long _roomId; + private readonly object _so; + private readonly int _zoneId; + + public CreateRoomVariableCommand(Guid clientId, int zoneId, long roomId, string name, object so) { _clientId = clientId; _zoneId = zoneId; @@ -27,9 +28,18 @@ public CreateRoomVariableCommand(Guid clientId, int zoneId, int roomId, string n public override void Execute() { - //RoomActionEngine.Instance.CreateRoomVariable(_room, _name, _so); + var room = RoomRepository.Instance.Find(_roomId); + if (room == null) return; + + RoomActionEngine.Instance.CreateRoomVariable(room, _name, ObjectSerialize.Serialize(_so)); + + MSMQQueueWrapper.QueueCommand( + new BroadcastObjectCommand( + room.Users.Select( u => u.ClientKey ).ToArray(), + new RoomVariableUpdateEvent() { Action = RoomVariableUpdateAction.Add, Name = _name, RoomId = _roomId, Value = _so, ZoneId = _zoneId } + ) + ); - // TODO: Send RoomVariableUpdateEvent to all users in room } } -} +} \ No newline at end of file diff --git a/SocketService/Command/DeleteRoomVariableCommand.cs b/SocketService/Command/DeleteRoomVariableCommand.cs index d3e3d3f..c7b97a3 100644 --- a/SocketService/Command/DeleteRoomVariableCommand.cs +++ b/SocketService/Command/DeleteRoomVariableCommand.cs @@ -1,12 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.Data; -using SocketService.Actions; -using SocketService.Framework.Client.Event; -using SocketService.Framework.Client.Response; +using SocketService.Core.Messaging; namespace SocketService.Command { @@ -17,12 +10,12 @@ public class DeleteRoomVariableCommand : BaseMessageHandler private readonly int _zoneId; private readonly int _roomId; private readonly string _name; - public DeleteRoomVariableCommand(Guid ClientId, int ZoneId, int RoomId, string Name) + public DeleteRoomVariableCommand(Guid clientId, int zoneId, int roomId, string name) { - _zoneId = ZoneId; - _clientId = ClientId; - _roomId = RoomId; - _name = Name; + _zoneId = zoneId; + _clientId = clientId; + _roomId = roomId; + _name = name; } public override void Execute() diff --git a/SocketService/Command/GetCentralAuthorityCommand.cs b/SocketService/Command/GetCentralAuthorityCommand.cs index 6b5c4d6..d68f05e 100644 --- a/SocketService/Command/GetCentralAuthorityCommand.cs +++ b/SocketService/Command/GetCentralAuthorityCommand.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Crypto; +using SocketService.Core.Crypto; +using SocketService.Core.Messaging; using SocketService.Net.Client; namespace SocketService.Command @@ -19,14 +17,14 @@ public GetCentralAuthorityCommand(Guid clientId) public override void Execute() { - CentralAuthority ca = new CentralAuthority(CAKeyProtocol.DH64); + var ca = new CentralAuthority(CAKeyProtocol.DH64); - Connection connection = ConnectionRepository.Instance.FindConnectionByClientId(_clientId); - if (connection != null) - { - connection.Provider = ca.GetProvider(); - MSMQQueueWrapper.QueueCommand(new SendObjectCommand(_clientId, ca)); - } + ClientConnection connection = + ConnectionRepository.Instance.Query(c => c.ClientId == _clientId).FirstOrDefault(); + if (connection == null) return; + + connection.SecureKeyProvider = ca.GetProvider(); + MSMQQueueWrapper.QueueCommand(new SendObjectCommand(_clientId, ca)); } } } diff --git a/SocketService/Command/GetRoomVariableCommand.cs b/SocketService/Command/GetRoomVariableCommand.cs index 7f191e6..f81bee6 100644 --- a/SocketService/Command/GetRoomVariableCommand.cs +++ b/SocketService/Command/GetRoomVariableCommand.cs @@ -1,15 +1,10 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.SharedObjects; -using SocketService.Actions; -using SocketService.Framework.Client.Response; -using SocketService.Framework; -using SocketService.Framework.Data; -using SocketService.Framework.Client.Serialize; +using SocketService.Core.Data; +using SocketService.Core.Messaging; using SocketService.Repository; +using SocketService.Shared; +using SocketService.Shared.Response; namespace SocketService.Command { @@ -34,21 +29,16 @@ public override void Execute() Room room = RoomRepository.Instance.Find(_roomId); if (room != null) { - RoomVariable var = room.RoomVariables.FirstOrDefault( - new Func( - (target) => - { - return target.Id == _roomId; - } - ) - ); + var var = room.RoomVariables.FirstOrDefault( + target => target.Id == _roomId); - SharedObject so = new SharedObject(); - so.SetElementValue("", ObjectSerialize.Deserialize(var.Value), SharedObjectDataType.BzObject); + object so = null; + if( var != null) + so = var.Value; MSMQQueueWrapper.QueueCommand( new SendObjectCommand(_clientId, - new GetRoomVariableResponse() { ZoneId = _zoneId, RoomId = room.Id, Name = _name, Value = so }) + new GetRoomVariableResponse { ZoneId = _zoneId, RoomId = room.Id, Name = _name, Value = so }) ); } } diff --git a/SocketService/Command/HandleClientRequestCommand.cs b/SocketService/Command/HandleClientRequestCommand.cs index 00eae01..71aa009 100644 --- a/SocketService/Command/HandleClientRequestCommand.cs +++ b/SocketService/Command/HandleClientRequestCommand.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; namespace SocketService.Command { - [Serializable()] + [Serializable] public class HandleClientRequestCommand : BaseMessageHandler { private readonly List _handlerList; diff --git a/SocketService/Command/LoginUserCommand.cs b/SocketService/Command/LoginUserCommand.cs index 1e72129..89b6345 100644 --- a/SocketService/Command/LoginUserCommand.cs +++ b/SocketService/Command/LoginUserCommand.cs @@ -1,23 +1,21 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; using SocketService.Actions; -using SocketService.Framework.Data; -using SocketService.Framework.Client.Response; -using SocketService.Framework.SharedObjects; -using SocketService.Framework.Client.Event; +using SocketService.Core.Data; +using SocketService.Core.Messaging; +using SocketService.Event; using SocketService.Repository; -using SocketService.Framework.Client.Serialize; +using SocketService.Shared; +using SocketService.Shared.Response; namespace SocketService.Command { [Serializable] public class LoginUserCommand : BaseMessageHandler { - private readonly string _username; private readonly Guid _clientId; + private readonly string _username; + public LoginUserCommand(Guid clientId, string username) { _clientId = clientId; @@ -26,19 +24,21 @@ public LoginUserCommand(Guid clientId, string username) public override void Execute() { + Logger.InfoFormat("Client {0} logging in.", _clientId); + // get/create default zone - Zone zone = ZoneActionEngine.Instance.CreateZone(ZoneActionEngine.DefaultZone); + var zone = ZoneActionEngine.Instance.CreateZone(ZoneActionEngine.DefaultZone); // get/create default room - Room room = RoomActionEngine.Instance.CreateRoom(RoomActionEngine.DefaultRoom, zone); + var room = RoomActionEngine.Instance.CreateRoom(RoomActionEngine.DefaultRoom, zone); // authenticate if (!UserActionEngine.Instance.LoginUser(_clientId, _username, room)) { MSMQQueueWrapper.QueueCommand( new SendObjectCommand(_clientId, - new LoginResponse() { Success = false }) - ); + new LoginResponse {Success = false}) + ); return; } @@ -50,57 +50,55 @@ public override void Execute() UserActionEngine.Instance.ClientChangeRoom(_clientId, RoomActionEngine.DefaultRoom); // tell clients about new user - MSMQQueueWrapper.QueueCommand( - new BroadcastObjectCommand( - room.Users. - Where((u) => { return u.ClientKey != _clientId; }). - Select((u) => { return u.ClientKey; }). - ToArray(), - new RoomUserUpdateEvent() - { - Action = RoomUserUpdateAction.AddUser, - RoomId = room.Id, - RoomName = room.Name, - UserName = user.Name - } - ) - ); + if (room != null) + MSMQQueueWrapper.QueueCommand( + new BroadcastObjectCommand( + room.Users.Where(u => + { + if (u == null) throw new ArgumentNullException("u"); + return u.ClientKey != _clientId; + }). + Select(u => u != null ? u.ClientKey : new Guid()). + ToArray(), + new RoomUserUpdateEvent + { + Action = RoomUserUpdateAction.AddUser, + RoomId = room.Id, + RoomName = room.Name, + UserName = user.Name + } + ) + ); } // send login response MSMQQueueWrapper.QueueCommand( new SendObjectCommand(_clientId, - new LoginResponse() { UserName = _username, Success = true }) - ); + new LoginResponse {UserName = _username, Success = true}) + ); // finally send a join room event to user - MSMQQueueWrapper.QueueCommand( - new SendObjectCommand(_clientId, - new JoinRoomEvent() - { - RoomName = room.Name, - RoomId = room.Id, - Protected = false, - Hidden = false, - Capacity = -1, - RoomDescription = "", - RoomVariables = room.RoomVariables.Select( - (rv) => - { - return ObjectSerialize.Deserialize(rv.Value); - }).ToArray(), - Users = room.Users.Select( - (u) => - { - return new UserListEntry() - { - UserName = u.Name - }; - }).ToArray() - } - ) - ); + if (room != null) + MSMQQueueWrapper.QueueCommand( + new SendObjectCommand(_clientId, + new JoinRoomEvent + { + RoomName = room.Name, + RoomId = room.Id, + Protected = false, + Hidden = false, + Capacity = -1, + RoomDescription = "", + RoomVariables = room.RoomVariables.Select( + rv => + ObjectSerialize.Deserialize(rv.Value)). + ToArray(), + Users = room.Users.Select( + u => u.Name + ).ToArray() + } + ) + ); } } - } diff --git a/SocketService/Command/LogoutUserCommand.cs b/SocketService/Command/LogoutUserCommand.cs index 5cbb726..7e78c5e 100644 --- a/SocketService/Command/LogoutUserCommand.cs +++ b/SocketService/Command/LogoutUserCommand.cs @@ -1,20 +1,19 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Net.Client; -using SocketService.Framework.Data; -using SocketService.Framework.Client.Response; using SocketService.Actions; +using SocketService.Core.Messaging; +using SocketService.Event; +using SocketService.Net; +using SocketService.Net.Client; using SocketService.Repository; namespace SocketService.Command { [Serializable] - class LogoutUserCommand : BaseMessageHandler + internal class LogoutUserCommand : BaseMessageHandler { private readonly Guid _clientId; + public LogoutUserCommand(Guid clientId) { _clientId = clientId; @@ -22,30 +21,42 @@ public LogoutUserCommand(Guid clientId) public override void Execute() { - Connection connection = ConnectionRepository.Instance.FindConnectionByClientId(_clientId); + Logger.InfoFormat("Client {0} logging out.", _clientId); + + var connection = ConnectionRepository.Instance.Query( c => c.ClientId == _clientId).FirstOrDefault(); if (connection != null) ConnectionRepository.Instance.RemoveConnection(connection); - //User user = UserRepository.Instance.Query(u => u.ClientKey.Equals(_clientId)).FirstOrDefault(); + var clientSocket = SocketRepository.Instance.FindByClientId(_clientId); + if (clientSocket != null) + { + try + { + clientSocket.Close(); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } + } + + var user = UserRepository.Instance.Query(u => u.ClientKey == _clientId).FirstOrDefault(); + if (user != null && user.Room != null) + { + var userList = user.Room.Users.Select(u => u.ClientKey); + MSMQQueueWrapper.QueueCommand( + new BroadcastObjectCommand(userList.ToArray(), + new PublicMessageEvent + { + RoomId = (int) user.RoomId, + UserName = string.Empty, + Message = string.Format("{0} has logged out.", user.Name), + ZoneId = (int) user.Room.ZoneId + }) + ); + } UserActionEngine.Instance.LogoutUser(_clientId); - - //if( user.Room != null ) - //{ - // List userList = user.Room.Users.ToList(); - //} - - //// broadcast to all but this user - //var query = from u in userList - // where u.ClientId != _clientId - // select u.ClientId; - - // TODO: Replace with PublicMessageEvent - //MSMQQueueWrapper.QueueCommand( - // new BroadcastObjectCommand(query.ToArray(), - // new ServerMessage("{0} has logged out.", user.UserName)) - //); - } } -} +} \ No newline at end of file diff --git a/SocketService/Command/NegotiateKeysCommand.cs b/SocketService/Command/NegotiateKeysCommand.cs index 99ce85a..0b63c69 100644 --- a/SocketService/Command/NegotiateKeysCommand.cs +++ b/SocketService/Command/NegotiateKeysCommand.cs @@ -1,22 +1,16 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Net.Sockets; -using SocketService.Framework.Client.Sockets; +using SocketService.Core.Messaging; using SocketService.Net.Client; -using SocketService.Net; -using SocketService.Framework.Messaging; -using SocketService.Framework.Request; -using SocketService.Framework.Client.Response; +using SocketService.Shared.Response; namespace SocketService.Command { - [Serializable()] + [Serializable] public class NegotiateKeysCommand : BaseMessageHandler { - Guid _clientId; - byte[] _publicKey; + private readonly Guid _clientId; + private readonly byte[] _publicKey; public NegotiateKeysCommand(Guid clientId, byte[] publicKey) { @@ -26,8 +20,9 @@ public NegotiateKeysCommand(Guid clientId, byte[] publicKey) public override void Execute() { - Connection connection = ConnectionRepository.Instance.FindConnectionByClientId(_clientId); - if (connection != null) + var connection = + ConnectionRepository.Instance.Query(c => c.ClientId == _clientId).FirstOrDefault(); + { //connection.RemotePublicKey = connection.Provider.Import(_data); @@ -47,11 +42,10 @@ public override void Execute() //if (connection != null) //{ // import clients public key - connection.RemotePublicKey = connection.Provider.Import(_publicKey); + connection.RemotePublicKey = connection.SecureKeyProvider.Import(_publicKey); // send our public key back - NegotiateKeysResponse response = new NegotiateKeysResponse(); - response.RemotePublicKey = connection.Provider.PublicKey.ToByteArray(); + var response = new NegotiateKeysResponse {RemotePublicKey = connection.SecureKeyProvider.PublicKey.ToByteArray()}; // now we send a response back MSMQQueueWrapper.QueueCommand(new SendObjectCommand(_clientId, response)); @@ -59,4 +53,4 @@ public override void Execute() } } } -} +} \ No newline at end of file diff --git a/SocketService/Command/ParseRequestCommand.cs b/SocketService/Command/ParseRequestCommand.cs index 5d6b611..a596923 100644 --- a/SocketService/Command/ParseRequestCommand.cs +++ b/SocketService/Command/ParseRequestCommand.cs @@ -1,13 +1,11 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.Request; -using SocketService.Framework.Client.Serialize; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Crypto; +using SocketService.Client.Core.Request; +using SocketService.Core.Crypto; +using SocketService.Core.Messaging; using SocketService.Net.Client; +using SocketService.Repository; +using SocketService.Shared; namespace SocketService.Command { @@ -25,10 +23,10 @@ public ParseRequestCommand(Guid clientId, byte[] serialized) public override void Execute() { - ClientRequest request = (ClientRequest)ObjectSerialize.Deserialize(_serialized); - object payload = DecryptRequest(request); + var requestWrapper = ObjectSerialize.Deserialize(_serialized); + var payload = DecryptRequest(requestWrapper); - Type handlerType = payload.GetType(); + var handlerType = payload.GetType(); var handlerList = ServiceHandlerLookup.Instance.GetHandlerListByType(handlerType); MSMQQueueWrapper.QueueCommand( @@ -36,13 +34,13 @@ public override void Execute() ); } - private object DecryptRequest(ClientRequest request) + private object DecryptRequest(ClientRequestWrapper requestWrapper) { // switch on encryption type, and create a decryptor for that type // with the remote private key and iv as salt - AlgorithmType algorithm = AlgorithmType.AES; + var algorithm = AlgorithmType.AES; - switch (request.Encryption) + switch (requestWrapper.Encryption) { case EncryptionType.DES: algorithm = AlgorithmType.DES; @@ -58,27 +56,23 @@ private object DecryptRequest(ClientRequest request) } - if (algorithm != AlgorithmType.None) + if (algorithm == AlgorithmType.None) { - Connection connection = ConnectionRepository.Instance.FindConnectionByClientId(_clientId); - if (connection != null) - { - DiffieHellmanKey privateKey = connection.Provider.CreatePrivateKey(connection.RemotePublicKey); - using (Wrapper cryptoWrapper = Wrapper.CreateDecryptor(algorithm, - privateKey.ToByteArray(), - request.EncryptionPublicKey)) - { - return ObjectSerialize.Deserialize(cryptoWrapper.Decrypt(request.RequestData)); - } - } - else - { - return null; - } + return ObjectSerialize.Deserialize(requestWrapper.RequestData); } - else + + var connection = ConnectionRepository.Instance.Query( c => c.ClientId == _clientId).FirstOrDefault(); + if (connection == null) { - return ObjectSerialize.Deserialize(request.RequestData); + return null; + } + + var privateKey = connection.SecureKeyProvider.CreatePrivateKey(connection.RemotePublicKey); + using (var cryptoWrapper = Wrapper.CreateDecryptor(algorithm, + privateKey.ToByteArray(), + requestWrapper.EncryptionPublicKey)) + { + return ObjectSerialize.Deserialize(cryptoWrapper.Decrypt(requestWrapper.RequestData)); } } } diff --git a/SocketService/Command/PublicMessageCommand.cs b/SocketService/Command/PublicMessageCommand.cs index 7be4585..f46bd01 100644 --- a/SocketService/Command/PublicMessageCommand.cs +++ b/SocketService/Command/PublicMessageCommand.cs @@ -1,27 +1,22 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.Client.Event; -using SocketService.Framework.Data; -using SocketService.Framework.Client.API; +using SocketService.Core.Messaging; namespace SocketService.Command { [Serializable] public class PublicMessageCommand : BaseMessageHandler { - private readonly int _zoneId; + private readonly string _message; private readonly int _roomId; private readonly string _user; - private readonly string _message; - public PublicMessageCommand(int ZoneId, int RoomId, string User, string Message) + private readonly int _zoneId; + + public PublicMessageCommand(int zoneId, int roomId, string user, string message) { - _zoneId = ZoneId; - _roomId = RoomId; - _user = User; - _message = Message; + _zoneId = zoneId; + _roomId = roomId; + _user = user; + _message = message; } public override void Execute() @@ -54,7 +49,6 @@ public override void Execute() // // we had a fail action, handle it somehow? // } //} - } } -} +} \ No newline at end of file diff --git a/SocketService/Command/SendObjectCommand.cs b/SocketService/Command/SendObjectCommand.cs index c9ffe95..b165330 100644 --- a/SocketService/Command/SendObjectCommand.cs +++ b/SocketService/Command/SendObjectCommand.cs @@ -1,17 +1,13 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Net.Sockets; -using SocketService.Framework.Messaging; -using SocketService.Framework.Client.Sockets; +using SocketService.Client.Core.Sockets; +using SocketService.Core.Messaging; using SocketService.Net; -using SocketService.Framework.Client.Serialize; +using SocketService.Shared; namespace SocketService.Command { [Serializable] - class SendObjectCommand : BaseMessageHandler + internal class SendObjectCommand : BaseMessageHandler { private readonly Guid _clientId; private readonly byte[] _data; @@ -27,9 +23,8 @@ public override void Execute() ZipSocket connection = SocketRepository.Instance.FindByClientId(_clientId); if (connection != null) { - connection.SendData(_data); } } } -} +} \ No newline at end of file diff --git a/SocketService/Command/ServerStartingCommand.cs b/SocketService/Command/ServerStartingCommand.cs index 257d8e5..ed7faec 100644 --- a/SocketService/Command/ServerStartingCommand.cs +++ b/SocketService/Command/ServerStartingCommand.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; using SocketService.Actions; -using SocketService.Net; +using SocketService.Core.Messaging; namespace SocketService.Command { @@ -18,7 +14,6 @@ public override void Execute() // remove all non-persistent rooms RoomActionEngine.Instance.RemoveNonPersistentRooms(); - } } -} +} \ No newline at end of file diff --git a/SocketService/Command/UpdateRoomVariableCommand.cs b/SocketService/Command/UpdateRoomVariableCommand.cs index 6a0669e..4faab7d 100644 --- a/SocketService/Command/UpdateRoomVariableCommand.cs +++ b/SocketService/Command/UpdateRoomVariableCommand.cs @@ -1,13 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Messaging; -using SocketService.Framework.SharedObjects; -using SocketService.Actions; -using SocketService.Framework.Client.Event; -using SocketService.Framework.Data; -using SocketService.Framework.Client.Response; +using SocketService.Core.Data; +using SocketService.Core.Messaging; +using SocketService.Event; using SocketService.Repository; namespace SocketService.Command @@ -15,18 +10,18 @@ namespace SocketService.Command [Serializable] public class UpdateRoomVariableCommand : BaseMessageHandler { - private readonly int _zoneId; - private readonly int _roomId; - private readonly string _name; - private readonly SharedObject _so; private readonly Guid _clientId; + private readonly string _name; + private readonly int _roomId; + private readonly object _so; + private readonly int _zoneId; - public UpdateRoomVariableCommand(Guid clientId, int ZoneId, int RoomId, string Name, SharedObject Value) + public UpdateRoomVariableCommand(Guid clientId, int zoneId, int roomId, string name, object value) { - _zoneId = ZoneId; - _roomId = RoomId; - _name = Name; - _so = Value; + _zoneId = zoneId; + _roomId = roomId; + _name = name; + _so = value; _clientId = clientId; } @@ -39,16 +34,17 @@ public override void Execute() MSMQQueueWrapper.QueueCommand( new BroadcastObjectCommand( - room.Users.Select((u) => { return u.ClientKey; }).ToArray(), - new RoomVariableUpdateEvent() - { - RoomId = room.Id, - Name = _name, - Value = _so, - Action = RoomVariableUpdateAction.Update - } - ) - ); + room.Users.Select(u => u == null ? new Guid() : u.ClientKey).ToArray(), + new RoomVariableUpdateEvent + { + ZoneId = _zoneId, + RoomId = room.Id, + Name = _name, + Value = _so, + Action = RoomVariableUpdateAction.Update + } + ) + ); //MSMQQueueWrapper.QueueCommand( // new SendObjectCommand( @@ -61,7 +57,6 @@ public override void Execute() // } // ) //); - } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/ChangeRoomRequestHandler.cs b/SocketService/Handler/ChangeRoomRequestHandler.cs index 19b542e..38c7044 100644 --- a/SocketService/Handler/ChangeRoomRequestHandler.cs +++ b/SocketService/Handler/ChangeRoomRequestHandler.cs @@ -1,18 +1,14 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] - [ServiceHandlerType(typeof(CreateRoomRequest))] - class ChangeRoomRequestHandler : BaseHandler + [Serializable] + [ServiceHandlerType(typeof (CreateRoomRequest))] + internal class ChangeRoomRequestHandler : BaseHandler { public override bool HandleRequest(CreateRoomRequest request, Guid state) { @@ -22,13 +18,12 @@ public override bool HandleRequest(CreateRoomRequest request, Guid state) MSMQQueueWrapper.QueueCommand( new CreateRoomCommand(state, request.ZoneName, roomName) - ); + ); return true; - } return false; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/CreateRoomVariableRequestHandler.cs b/SocketService/Handler/CreateRoomVariableRequestHandler.cs index db04393..b546e02 100644 --- a/SocketService/Handler/CreateRoomVariableRequestHandler.cs +++ b/SocketService/Handler/CreateRoomVariableRequestHandler.cs @@ -1,26 +1,22 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] - [ServiceHandlerType(typeof(CreateRoomVariableRequest))] + [Serializable] + [ServiceHandlerType(typeof (CreateRoomVariableRequest))] public class CreateRoomVariableRequestHandler : BaseHandler { public override bool HandleRequest(CreateRoomVariableRequest request, Guid state) { MSMQQueueWrapper.QueueCommand( new CreateRoomVariableCommand(state, request.ZoneId, request.RoomId, request.Name, request.Value) - ); + ); return true; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/DeleteRoomVariableRequestHandler.cs b/SocketService/Handler/DeleteRoomVariableRequestHandler.cs index 7c992f1..164c0e9 100644 --- a/SocketService/Handler/DeleteRoomVariableRequestHandler.cs +++ b/SocketService/Handler/DeleteRoomVariableRequestHandler.cs @@ -1,16 +1,13 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; -using SocketService.Framework.Messaging; +using SocketService.Client.Core.Request; using SocketService.Command; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; namespace SocketService.Handler { [Serializable] - [ServiceHandlerType(typeof(DeleteRoomVariableRequest))] + [ServiceHandlerType(typeof (DeleteRoomVariableRequest))] public class DeleteRoomVariableRequestHandler : BaseHandler { public override bool HandleRequest(DeleteRoomVariableRequest request, Guid state) @@ -19,15 +16,12 @@ public override bool HandleRequest(DeleteRoomVariableRequest request, Guid state { MSMQQueueWrapper.QueueCommand( new DeleteRoomVariableCommand(state, request.ZoneId, request.RoomId, request.Name) - ); + ); return true; - } return false; } - - } -} +} \ No newline at end of file diff --git a/SocketService/Handler/GetCARequestHandler.cs b/SocketService/Handler/GetCARequestHandler.cs index ddf7636..f70b5c4 100644 --- a/SocketService/Handler/GetCARequestHandler.cs +++ b/SocketService/Handler/GetCARequestHandler.cs @@ -1,27 +1,23 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] - [ServiceHandlerType(typeof(GetCentralAuthorityRequest))] - public class GetCARequestHandler : + [Serializable] + [ServiceHandlerType(typeof (GetCentralAuthorityRequest))] + public class GetCARequestHandler : BaseHandler { public override bool HandleRequest(GetCentralAuthorityRequest request, Guid state) { MSMQQueueWrapper.QueueCommand( new GetCentralAuthorityCommand(state) - ); - + ); + return true; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/GetRoomVariableRequestHandler.cs b/SocketService/Handler/GetRoomVariableRequestHandler.cs index a84fc6d..02234a1 100644 --- a/SocketService/Handler/GetRoomVariableRequestHandler.cs +++ b/SocketService/Handler/GetRoomVariableRequestHandler.cs @@ -1,17 +1,11 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; -using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Client.Core.Request; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] - [ServiceHandlerType(typeof(GetRoomVariableRequest))] + [Serializable] + [ServiceHandlerType(typeof (GetRoomVariableRequest))] public class GetRoomVariableRequestHandler : BaseHandler { public override bool HandleRequest(GetRoomVariableRequest request, Guid state) @@ -30,4 +24,4 @@ public override bool HandleRequest(GetRoomVariableRequest request, Guid state) return false; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/LoginRequestHandler.cs b/SocketService/Handler/LoginRequestHandler.cs index 1395db9..130a0f2 100644 --- a/SocketService/Handler/LoginRequestHandler.cs +++ b/SocketService/Handler/LoginRequestHandler.cs @@ -1,23 +1,15 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] + [Serializable] [ServiceHandlerType(typeof(LoginRequest))] public class LoginRequestHandler : BaseHandler { - public LoginRequestHandler() - { - } - public override bool HandleRequest(LoginRequest request, Guid connectionId) { if (request != null) diff --git a/SocketService/Handler/NegotiateKeysRequestHandler.cs b/SocketService/Handler/NegotiateKeysRequestHandler.cs index 5642e3f..46c4108 100644 --- a/SocketService/Handler/NegotiateKeysRequestHandler.cs +++ b/SocketService/Handler/NegotiateKeysRequestHandler.cs @@ -1,27 +1,23 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.ComponentModel.Composition; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Messaging; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Handler { - [Serializable()] - [ServiceHandlerType(typeof(NegotiateKeysRequest))] - public class NegotiateKeysRequestHandler : + [Serializable] + [ServiceHandlerType(typeof (NegotiateKeysRequest))] + public class NegotiateKeysRequestHandler : BaseHandler { public override bool HandleRequest(NegotiateKeysRequest request, Guid state) { MSMQQueueWrapper.QueueCommand( new NegotiateKeysCommand(state, request.PublicKey) - ); + ); return true; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/PublicMessageRequestHandler.cs b/SocketService/Handler/PublicMessageRequestHandler.cs index 2219b80..30a9509 100644 --- a/SocketService/Handler/PublicMessageRequestHandler.cs +++ b/SocketService/Handler/PublicMessageRequestHandler.cs @@ -1,30 +1,27 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; -using SocketService.Framework.Messaging; +using SocketService.Client.Core.Request; using SocketService.Command; -using SocketService.Framework.Data; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; using SocketService.Repository; namespace SocketService.Handler { - [ServiceHandlerType(typeof(PublicMessageRequest))] + [ServiceHandlerType(typeof (PublicMessageRequest))] public class PublicMessageRequestHandler : BaseHandler { public override bool HandleRequest(PublicMessageRequest request, Guid state) { - User user = UserRepository.Instance.Query( u => u.ClientKey.Equals(state) ).FirstOrDefault(); + var user = UserRepository.Instance.Query(u => u.ClientKey.Equals(state)).FirstOrDefault(); if (user != null) { MSMQQueueWrapper.QueueCommand( new PublicMessageCommand(request.ZoneId, request.RoomId, user.Name, request.Message) - ); + ); } return true; } } -} +} \ No newline at end of file diff --git a/SocketService/Handler/UpdateRoomVariableRequestHandler.cs b/SocketService/Handler/UpdateRoomVariableRequestHandler.cs index ecdf85b..d3648b8 100644 --- a/SocketService/Handler/UpdateRoomVariableRequestHandler.cs +++ b/SocketService/Handler/UpdateRoomVariableRequestHandler.cs @@ -1,25 +1,22 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Framework.ServiceHandlerLib; -using SocketService.Framework.Request; -using SocketService.Framework.Messaging; +using SocketService.Client.Core.Request; using SocketService.Command; +using SocketService.Core.Messaging; +using SocketService.Core.ServiceHandlerLib; namespace SocketService.Handler { [Serializable] - [ServiceHandlerType(typeof(UpdateRoomVariableRequest))] + [ServiceHandlerType(typeof (UpdateRoomVariableRequest))] public class UpdateRoomVariableRequestHandler : BaseHandler { public override bool HandleRequest(UpdateRoomVariableRequest request, Guid state) { MSMQQueueWrapper.QueueCommand( new UpdateRoomVariableCommand(state, request.ZoneId, request.RoomId, request.Name, request.Value) - ); + ); return true; } } -} +} \ No newline at end of file diff --git a/SocketService/Net/Client/ConnectArgs.cs b/SocketService/Net/Client/ConnectArgs.cs index 1fc9426..2bf5e88 100644 --- a/SocketService/Net/Client/ConnectArgs.cs +++ b/SocketService/Net/Client/ConnectArgs.cs @@ -1,68 +1,52 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Net.Sockets; namespace SocketService.Net.Client { - public class ConnectArgs : EventArgs - { - /// - /// Initializes a new instance of the class. - /// - public ConnectArgs() - { - } + public class ConnectArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + public ConnectArgs() + { + } - /// - /// Initializes a new instance of the class. - /// - /// The client id. - /// The raw socket. - /// The remote address. - public ConnectArgs(Guid clientId, Socket rawSocket, string remoteAddress) - { - ClientId = clientId; - RemoteAddress = remoteAddress; - RawSocket = rawSocket; - } + /// + /// Initializes a new instance of the class. + /// + /// The client id. + /// The raw socket. + /// The remote address. + public ConnectArgs(Guid clientId, Socket rawSocket, string remoteAddress) + { + ClientId = clientId; + RemoteAddress = remoteAddress; + RawSocket = rawSocket; + } - /// - /// Gets or sets the client id. - /// - /// - /// The client id. - /// - public Guid ClientId - { - get; - set; - } + /// + /// Gets or sets the client id. + /// + /// + /// The client id. + /// + public Guid ClientId { get; set; } - /// - /// Gets or sets the raw socket. - /// - /// - /// The raw socket. - /// - public Socket RawSocket - { - get; - set; - } + /// + /// Gets or sets the raw socket. + /// + /// + /// The raw socket. + /// + public Socket RawSocket { get; set; } - /// - /// Gets or sets the remote address. - /// - /// - /// The remote address. - /// - public string RemoteAddress - { - get; - set; - } - - } -} + /// + /// Gets or sets the remote address. + /// + /// + /// The remote address. + /// + public string RemoteAddress { get; set; } + } +} \ No newline at end of file diff --git a/SocketService/Net/Client/Connection.cs b/SocketService/Net/Client/Connection.cs index c145d2f..eca6861 100644 --- a/SocketService/Net/Client/Connection.cs +++ b/SocketService/Net/Client/Connection.cs @@ -1,74 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SocketService.Crypto; +using System; namespace SocketService.Net.Client { public class Connection { - /// - /// Initializes a new instance of the class. - /// - /// The client id. public Connection(Guid clientId) { ClientId = clientId; } - /// /// Gets or sets the client id. /// /// /// The client id. /// - public Guid ClientId - { - get; - set; - } - - /// - /// Gets or sets the remote public key. - /// - /// - /// The remote public key. - /// - public DiffieHellmanKey RemotePublicKey - { - get; - set; - } - - /// - /// Gets or sets the provider. - /// - /// - /// The provider. - /// - public DiffieHellmanProvider Provider - { - get; - set; - } - - /// - /// Gets or sets the state of the connection. - /// - /// - /// The state of the connection. - /// - public ConnectionState ConnectionState - { - get; - set; - } - } + public Guid ClientId { get; set; } - public enum ConnectionState - { - NegotiateKeyPair, - Connected } -} +} \ No newline at end of file diff --git a/SocketService/Net/Client/ConnectionRepository.cs b/SocketService/Net/Client/ConnectionRepository.cs index b635472..521bd65 100644 --- a/SocketService/Net/Client/ConnectionRepository.cs +++ b/SocketService/Net/Client/ConnectionRepository.cs @@ -1,66 +1,81 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading; namespace SocketService.Net.Client { public class ConnectionRepository { - private readonly List _connectionList = new List(); + private static ConnectionRepository _instance; + private readonly List _connectionList = new List(); private readonly Mutex _connectionMutex = new Mutex(); protected ConnectionRepository() { } - private static ConnectionRepository _instance = null; - /// /// Gets the instance. /// public static ConnectionRepository Instance + { + get { return _instance ?? (_instance = new ConnectionRepository()); } + } + + /// + /// Gets the connection list. + /// + public List ConnectionList { get { - if (_instance == null) + _connectionMutex.WaitOne(); + try + { + return _connectionList.ToList(); + } + finally { - _instance = new ConnectionRepository(); + _connectionMutex.ReleaseMutex(); } - return _instance; } } + public IEnumerable Query(Func filter) + { + return _connectionList.Where(filter); + + } + /// /// Finds the connection by client id. /// /// The client id. /// - public Connection FindConnectionByClientId(Guid clientId) - { - _connectionMutex.WaitOne(); - try - { + //public ClientConnection FindConnectionByClientId(Guid clientId) + //{ + // _connectionMutex.WaitOne(); + // try + // { + // IEnumerable q = from c in _connectionList + // where c.ClientId == clientId + // select c; - var q = from c in _connectionList - where c.ClientId == clientId - select c; - - return q.FirstOrDefault(); - } - finally - { - _connectionMutex.ReleaseMutex(); - } - } + // return q.FirstOrDefault(); + // } + // finally + // { + // _connectionMutex.ReleaseMutex(); + // } + //} /// /// Removes the connection. /// /// The connection. - public void RemoveConnection(Connection connection) + public void RemoveConnection(ClientConnection connection) { _connectionMutex.WaitOne(); try @@ -77,8 +92,10 @@ public void RemoveConnection(Connection connection) /// Adds the connection. /// /// The connection. - public void AddConnection(Connection connection) + public ClientConnection NewConnection() { + var connection = new ClientConnection(); + _connectionMutex.WaitOne(); try { @@ -88,28 +105,8 @@ public void AddConnection(Connection connection) { _connectionMutex.ReleaseMutex(); } - } - - - /// - /// Gets the connection list. - /// - public List ConnectionList - { - get - { - _connectionMutex.WaitOne(); - try - { - } - finally - { - _connectionMutex.ReleaseMutex(); - } - return _connectionList.ToList(); - } + return connection; } - } -} +} \ No newline at end of file diff --git a/SocketService/Net/Client/DisconnectedArgs.cs b/SocketService/Net/Client/DisconnectedArgs.cs index 4647804..4ca3942 100644 --- a/SocketService/Net/Client/DisconnectedArgs.cs +++ b/SocketService/Net/Client/DisconnectedArgs.cs @@ -1,38 +1,29 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Net.Sockets; namespace SocketService.Net.Client { - public class DisconnectedArgs : EventArgs - { - public DisconnectedArgs() - { - } + public class DisconnectedArgs : EventArgs + { + public DisconnectedArgs() + { + } - /// - /// Initializes a new instance of the class. - /// - /// The client id. - public DisconnectedArgs(Guid clientId) - { - ClientId = clientId; - } + /// + /// Initializes a new instance of the class. + /// + /// The client id. + public DisconnectedArgs(Guid clientId) + { + ClientId = clientId; + } - /// - /// Gets or sets the client id. - /// - /// - /// The client id. - /// - public Guid ClientId - { - get; - set; - } - - } -} + /// + /// Gets or sets the client id. + /// + /// + /// The client id. + /// + public Guid ClientId { get; set; } + } +} \ No newline at end of file diff --git a/SocketService/Net/Client/SocketDataRecievedArgs.cs b/SocketService/Net/Client/SocketDataRecievedArgs.cs index 5e8c459..f484250 100644 --- a/SocketService/Net/Client/SocketDataRecievedArgs.cs +++ b/SocketService/Net/Client/SocketDataRecievedArgs.cs @@ -1,45 +1,41 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Net.Sockets; namespace SocketService.Net.Client { - public class DataRecievedArgs : EventArgs - { - /// - /// Initializes a new instance of the class. - /// - public DataRecievedArgs() - { - } + public class DataRecievedArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + public DataRecievedArgs() + { + } - /// - /// Initializes a new instance of the class. - /// - /// The client id. - /// The data. - public DataRecievedArgs(Guid clientId, byte [] data) - { - ClientId = clientId; - Data = data; - } + /// + /// Initializes a new instance of the class. + /// + /// The client id. + /// The data. + public DataRecievedArgs(Guid clientId, byte[] data) + { + ClientId = clientId; + Data = data; + } - /// - /// Gets or sets the client id. - /// - /// - /// The client id. - /// - public Guid ClientId { get; set; } + /// + /// Gets or sets the client id. + /// + /// + /// The client id. + /// + public Guid ClientId { get; set; } - /// - /// Gets or sets the data. - /// - /// - /// The data. - /// - public byte[] Data { get; set; } - } -} + /// + /// Gets or sets the data. + /// + /// + /// The data. + /// + public byte[] Data { get; set; } + } +} \ No newline at end of file diff --git a/SocketService/Net/SocketManager.cs b/SocketService/Net/SocketManager.cs index 976b611..b6695c0 100644 --- a/SocketService/Net/SocketManager.cs +++ b/SocketService/Net/SocketManager.cs @@ -1,22 +1,20 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading; +using System.Configuration; using System.Reflection; -using System.IO; -using SocketService.Framework.Messaging; using SocketService.Command; -using SocketService.Framework.Configuration; -using System.Configuration; -using SocketService.Framework.ServiceHandlerLib; +using SocketService.Core.Configuration; +using SocketService.Core.Messaging; using SocketService.Net.Client; +using log4net; namespace SocketService.Net { public class SocketManager //: IServerContext { + private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly SocketServer _socketServer; + /// /// Initializes a new instance of the class. /// @@ -25,29 +23,30 @@ public SocketManager() // create server, doesn't start pumping until we get the Start command _socketServer = new SocketServer(); - _socketServer.ClientConnecting += new EventHandler(SocketServer_ClientConnecting); - _socketServer.ClientDisconnecting += new EventHandler(SocketServer_ClientDisconnecting); - _socketServer.DataRecieved += new EventHandler(SocketServer_DataRecieved); + _socketServer.ClientConnecting += SocketServerClientConnecting; + _socketServer.ClientDisconnecting += SocketServerClientDisconnecting; + _socketServer.DataRecieved += SocketServerDataRecieved; } - protected void SocketServer_DataRecieved(object sender, DataRecievedArgs e) + protected void SocketServerDataRecieved(object sender, DataRecievedArgs e) { - Connection connection = ConnectionRepository.Instance.FindConnectionByClientId(e.ClientId); + var connection = ConnectionRepository.Instance.Query( c => c.ClientId == e.ClientId).FirstOrDefault(); if (connection != null) { ParseRequest(connection.ClientId, e.Data); } } - protected void SocketServer_ClientConnecting(object sender, ConnectArgs e) + protected void SocketServerClientConnecting(object sender, ConnectArgs e) { + Logger.InfoFormat("Client {0} connecting from {1}", e.ClientId, e.RemoteAddress); SocketRepository.Instance.AddSocket(e.ClientId, e.RawSocket); - Connection connection = new Connection(e.ClientId); - ConnectionRepository.Instance.AddConnection(connection); + var connection = ConnectionRepository.Instance.NewConnection(); + connection.ClientId = e.ClientId; } - protected void SocketServer_ClientDisconnecting(object sender, DisconnectedArgs e) + protected void SocketServerClientDisconnecting(object sender, DisconnectedArgs e) { MSMQQueueWrapper.QueueCommand(new LogoutUserCommand(e.ClientId)); } @@ -55,22 +54,26 @@ protected void SocketServer_ClientDisconnecting(object sender, DisconnectedArgs /// /// Starts the server. /// - /// The port. public void StartServer() { SocketServiceConfiguration configuration = null; try { - configuration = (SocketServiceConfiguration)ConfigurationManager.GetSection("SocketServerConfiguration"); + configuration = + (SocketServiceConfiguration) ConfigurationManager.GetSection("SocketServerConfiguration"); + } + catch (Exception exception) + { + Logger.Error(exception.ToString()); } - catch (Exception) - { } if (configuration != null) { MSMQQueueWrapper.QueueCommand(new ServerStartingCommand()); _socketServer.StartServer(configuration.ListenPort); + + Logger.InfoFormat("Server started and listening on {0}", configuration.ListenPort); } } @@ -82,9 +85,9 @@ public void StopServer() _socketServer.StopServer(); } - private void ParseRequest(Guid clientId, byte[] requestData) + private static void ParseRequest(Guid clientId, byte[] requestData) { MSMQQueueWrapper.QueueCommand(new ParseRequestCommand(clientId, requestData)); } } -} +} \ No newline at end of file diff --git a/SocketService/Net/SocketRepository.cs b/SocketService/Net/SocketRepository.cs index 57346c1..3763d9d 100644 --- a/SocketService/Net/SocketRepository.cs +++ b/SocketService/Net/SocketRepository.cs @@ -1,15 +1,15 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Net.Sockets; using System.Threading; -using SocketService.Framework.Client.Sockets; +using SocketService.Client.Core.Sockets; namespace SocketService.Net { public class SocketRepository { + private static SocketRepository _instance; private readonly Dictionary _connectionList = new Dictionary(); private readonly Mutex _connectionMutex = new Mutex(); @@ -17,22 +17,20 @@ protected SocketRepository() { } - private static SocketRepository _instance = null; - /// /// Gets the instance. /// public static SocketRepository Instance { - get - { - if (_instance == null) - { - _instance = new SocketRepository(); - } + get { return _instance ?? (_instance = new SocketRepository()); } + } - return _instance; - } + /// + /// Gets the connection list. + /// + public List ConnectionList + { + get { return _connectionList.Values.ToList(); } } /// @@ -53,7 +51,6 @@ public ZipSocket FindByClientId(Guid clientId) { return null; } - } finally { @@ -88,26 +85,12 @@ public void AddSocket(Guid clientId, Socket connection) _connectionMutex.WaitOne(); try { - _connectionList.Add(clientId, new ZipSocket(connection, clientId)); + _connectionList.Add(clientId, new ZipSocket(connection)); } finally { _connectionMutex.ReleaseMutex(); } } - - - /// - /// Gets the connection list. - /// - public List ConnectionList - { - get - { - return _connectionList.Values.ToList(); - } - } - - } -} +} \ No newline at end of file diff --git a/SocketService/Net/SocketServer.cs b/SocketService/Net/SocketServer.cs index fd4dfb4..7eedcbd 100644 --- a/SocketService/Net/SocketServer.cs +++ b/SocketService/Net/SocketServer.cs @@ -1,347 +1,341 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Net.Sockets; -using System.Threading; using System.Net; -using System.Collections; -using System.Diagnostics; +using System.Net.Sockets; using System.Reflection; -using SocketService.Framework.Client.Sockets; -using log4net; +using System.Threading; +using SocketService.Client.Core.Sockets; using SocketService.Net.Client; +using log4net; namespace SocketService.Net { - public class SocketServer - { - private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public event EventHandler ClientConnecting; - public event EventHandler DataRecieved; - public event EventHandler ClientDisconnecting; - - private Mutex _clientListLock = new Mutex(); - - private Dictionary _connectionList = new Dictionary(); - private Socket _listenSocket; - private ManualResetEvent _stopEvent = new ManualResetEvent(false); - private bool _stopped = true; - - /// - /// Gets or sets a value indicating whether this instance is stopped. - /// - /// - /// true if this instance is stopped; otherwise, false. - /// - public bool IsStopped - { - get - { - Thread.MemoryBarrier(); - return _stopped; - } - - set - { - _stopped = value; - Thread.MemoryBarrier(); - } - } - - /// - /// Starts the server. - /// - /// The server port. - public void StartServer(int serverPort) - { - if (IsStopped) - { - _stopEvent.Reset(); - - IsStopped = false; - - Thread serverThread = new Thread(new ParameterizedThreadStart(ServerMain)); - serverThread.Start(serverPort); - } - } - - /// - /// Stops the server. - /// - public void StopServer() - { - _stopEvent.Set(); - DisconnectAllClients(); - } - - /// - /// Disconnects the client. - /// - /// The client. - public void DisconnectClient(Guid clientId) - { - _clientListLock.WaitOne(); - try - { - if (_connectionList.ContainsKey(clientId)) - { - _connectionList[clientId].Close(); - OnClientDisconnected(clientId); - - _connectionList.Remove(clientId); - } - - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - } - finally - { - _clientListLock.ReleaseMutex(); - } - - } - - virtual protected void OnDataRecieved(Guid clientId, byte[] data) - { - var dataRecieved = this.DataRecieved; - if (dataRecieved != null) - { - DataRecievedArgs args = new DataRecievedArgs(clientId, data); - dataRecieved(this, args); - } - } - - virtual protected void OnClientConnected(Guid clientId, Socket socket, string remoteAddress) - { - var clientConnected = this.ClientConnecting; - if (clientConnected != null) - { - ConnectArgs args = new ConnectArgs(clientId, socket, remoteAddress); - clientConnected(this, args); - } - } - - virtual protected void OnClientDisconnected(Guid clientId) - { - var clientDisconnected = this.ClientDisconnecting; - if (clientDisconnected != null) - { - DisconnectedArgs args = new DisconnectedArgs(clientId); - clientDisconnected(this, args); - } - } - - private void DisconnectAllClients() - { - _clientListLock.WaitOne(); - try - { - foreach (Guid key in _connectionList.Keys) - { - _connectionList[key].Close(); - OnClientDisconnected(key); - } - - _connectionList.Clear(); - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - } - finally - { - _clientListLock.ReleaseMutex(); - } - } - - private void ServerMain(object threadParam) - { - int port = (int)threadParam; - - _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - - IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port); - _listenSocket.Bind(localEndPoint); - _listenSocket.Listen(30); - - _listenSocket.BeginAccept(new AsyncCallback(OnBeginAccept), null); - - Thread pollThread = new Thread(new ThreadStart(Poll)); - pollThread.Start(); - } - - private void OnBeginAccept(IAsyncResult result) - { - if (result.IsCompleted) - { - Socket socket = null; - - try - { - socket = _listenSocket.EndAccept(result); - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - } - - if (socket != null) - { - Guid clientId = Guid.NewGuid(); - ZipSocket client = new ZipSocket(socket, clientId); - - AddConnection(clientId, client); - OnClientConnected(clientId, socket, ((IPEndPoint)socket.RemoteEndPoint).Address.ToString()); - - _listenSocket.BeginAccept(new AsyncCallback(OnBeginAccept), null); - } - } - else - { - _listenSocket.BeginAccept(new AsyncCallback(OnBeginAccept), null); - } - - } - - /// - /// Retrieves the guid (clientId) associated with this socket - /// - /// - /// - private ZipSocket FindClientBySocket(Socket socket, out Guid clientId) - { - clientId = Guid.Empty; - - _clientListLock.WaitOne(); - try - { - var query = from li in _connectionList - where li.Value.RawSocket == socket - select li; - - - var kvp = query.FirstOrDefault(); - clientId = kvp.Key; - return kvp.Value; - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - return null; - } - finally - { - _clientListLock.ReleaseMutex(); - } - } - - private void Poll() - { - while (!_stopEvent.WaitOne(20)) - { - IList readList = BuildSocketList(); - if (readList.Count > 0) - { - Socket.Select(readList, null, null, 0); - ProcessSelectedSockets(readList); - } - } - - //_listenSocket.Shutdown(SocketShutdown.Both); - _listenSocket.Close(); - - IsStopped = true; - } - - private void ProcessSelectedSockets(IList readList) - { - foreach (object listObject in readList) - { - Socket socket = listObject as Socket; - if (socket != null && !IsStopped) - { - Guid clientId; - ZipSocket client = FindClientBySocket(socket, out clientId); - if (client != null) - { - if (socket.Connected) - { - int availableBytes = socket.Available; - - if (availableBytes > 0) - { - OnDataRecieved(clientId, client.ReceiveData()); - } - else - { - DisconnectClient(clientId); - } - } - else - { - //log.Debug(string.Format("SocketServer.ProcessReadList => Zombie socket, client id {0}", FindClientIdForSocket(socket)) ); - DisconnectClient(clientId); - } - } - } - - } - } - - private List BuildSocketList() - { - List clientList = new List(); - - Socket[] socketArray = null; - - _clientListLock.WaitOne(); - try - { - socketArray = new Socket[_connectionList.Count]; - - var q = from nvp in _connectionList - select nvp.Value.RawSocket; - - q.ToArray().CopyTo(socketArray, 0); - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - } - finally - { - _clientListLock.ReleaseMutex(); - } - - if (socketArray != null) - { - clientList.AddRange(socketArray); - } - - return clientList; - } - - private void AddConnection(Guid clientId, ZipSocket clientSocket) - { - _clientListLock.WaitOne(); - - try - { - _connectionList.Add(clientId, clientSocket); - } - catch (Exception ex) - { - Log.ErrorFormat("Error: {0}", ex.Message); - } - finally - { - _clientListLock.ReleaseMutex(); - } - - } - } -} + public class SocketServer + { + private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private readonly Mutex _clientListLock = new Mutex(); + + private readonly Dictionary _connectionList = new Dictionary(); + private readonly ManualResetEvent _stopEvent = new ManualResetEvent(false); + private Socket _listenSocket; + private bool _stopped = true; + + /// + /// Gets or sets a value indicating whether this instance is stopped. + /// + /// + /// true if this instance is stopped; otherwise, false. + /// + public bool IsStopped + { + get + { + Thread.MemoryBarrier(); + return _stopped; + } + + set + { + _stopped = value; + Thread.MemoryBarrier(); + } + } + + public event EventHandler ClientConnecting; + public event EventHandler DataRecieved; + public event EventHandler ClientDisconnecting; + + /// + /// Starts the server. + /// + /// The server port. + public void StartServer(int serverPort) + { + if (IsStopped) + { + _stopEvent.Reset(); + + IsStopped = false; + + var serverThread = new Thread(ServerMain); + serverThread.Start(serverPort); + } + } + + /// + /// Stops the server. + /// + public void StopServer() + { + _stopEvent.Set(); + DisconnectAllClients(); + } + + /// + /// Disconnects the client. + /// + /// + public void DisconnectClient(Guid clientId) + { + _clientListLock.WaitOne(); + try + { + if (_connectionList.ContainsKey(clientId)) + { + _connectionList[clientId].Close(); + OnClientDisconnected(clientId); + + _connectionList.Remove(clientId); + } + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + } + finally + { + _clientListLock.ReleaseMutex(); + } + } + + protected virtual void OnDataRecieved(Guid clientId, byte[] data) + { + EventHandler dataRecieved = DataRecieved; + if (dataRecieved != null) + { + var args = new DataRecievedArgs(clientId, data); + dataRecieved(this, args); + } + } + + protected virtual void OnClientConnected(Guid clientId, Socket socket, string remoteAddress) + { + EventHandler clientConnected = ClientConnecting; + if (clientConnected != null) + { + var args = new ConnectArgs(clientId, socket, remoteAddress); + clientConnected(this, args); + } + } + + protected virtual void OnClientDisconnected(Guid clientId) + { + EventHandler clientDisconnected = ClientDisconnecting; + if (clientDisconnected != null) + { + var args = new DisconnectedArgs(clientId); + clientDisconnected(this, args); + } + } + + private void DisconnectAllClients() + { + _clientListLock.WaitOne(); + try + { + foreach (Guid key in _connectionList.Keys) + { + _connectionList[key].Close(); + OnClientDisconnected(key); + } + + _connectionList.Clear(); + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + } + finally + { + _clientListLock.ReleaseMutex(); + } + } + + private void ServerMain(object threadParam) + { + var port = (int) threadParam; + + _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + + var localEndPoint = new IPEndPoint(IPAddress.Any, port); + _listenSocket.Bind(localEndPoint); + _listenSocket.Listen(30); + + _listenSocket.BeginAccept(OnBeginAccept, null); + + var pollThread = new Thread(Poll); + pollThread.Start(); + } + + private void OnBeginAccept(IAsyncResult result) + { + if (result.IsCompleted) + { + Socket socket = null; + + try + { + socket = _listenSocket.EndAccept(result); + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + } + + if (socket != null) + { + Guid clientId = Guid.NewGuid(); + var client = new ZipSocket(socket); + + AddConnection(clientId, client); + OnClientConnected(clientId, socket, ((IPEndPoint) socket.RemoteEndPoint).Address.ToString()); + + _listenSocket.BeginAccept(OnBeginAccept, null); + } + } + else + { + _listenSocket.BeginAccept(OnBeginAccept, null); + } + } + + /// + /// Retrieves the guid (clientId) associated with this socket + /// + /// + /// + /// + private ZipSocket FindClientBySocket(Socket socket, out Guid clientId) + { + clientId = Guid.Empty; + + _clientListLock.WaitOne(); + try + { + IEnumerable> query = from li in _connectionList + where li.Value.RawSocket == socket + select li; + + + KeyValuePair kvp = query.FirstOrDefault(); + clientId = kvp.Key; + return kvp.Value; + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + return null; + } + finally + { + _clientListLock.ReleaseMutex(); + } + } + + private void Poll() + { + while (!_stopEvent.WaitOne(20)) + { + IList readList = BuildSocketList(); + if (readList.Count > 0) + { + Socket.Select(readList, null, null, 0); + ProcessSelectedSockets(readList); + } + } + + //_listenSocket.Shutdown(SocketShutdown.Both); + _listenSocket.Close(); + + IsStopped = true; + } + + private void ProcessSelectedSockets(IList readList) + { + foreach (object listObject in readList) + { + var socket = listObject as Socket; + if (socket != null && !IsStopped) + { + Guid clientId; + ZipSocket client = FindClientBySocket(socket, out clientId); + if (client != null) + { + if (socket.Connected) + { + int availableBytes = socket.Available; + + if (availableBytes > 0) + { + OnDataRecieved(clientId, client.ReceiveData()); + } + else + { + DisconnectClient(clientId); + } + } + else + { + //log.Debug(string.Format("SocketServer.ProcessReadList => Zombie socket, client id {0}", FindClientIdForSocket(socket)) ); + DisconnectClient(clientId); + } + } + } + } + } + + private List BuildSocketList() + { + var clientList = new List(); + + Socket[] socketArray = null; + + _clientListLock.WaitOne(); + try + { + socketArray = new Socket[_connectionList.Count]; + + IEnumerable q = from nvp in _connectionList + select nvp.Value.RawSocket; + + q.ToArray().CopyTo(socketArray, 0); + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + } + finally + { + _clientListLock.ReleaseMutex(); + } + + if (socketArray != null) + { + clientList.AddRange(socketArray); + } + + return clientList; + } + + private void AddConnection(Guid clientId, ZipSocket clientSocket) + { + _clientListLock.WaitOne(); + + try + { + _connectionList.Add(clientId, clientSocket); + } + catch (Exception ex) + { + Log.ErrorFormat("Error: {0}", ex.Message); + } + finally + { + _clientListLock.ReleaseMutex(); + } + } + } +} \ No newline at end of file diff --git a/SocketService/Program.cs b/SocketService/Program.cs index 0f666a5..15b3e88 100644 --- a/SocketService/Program.cs +++ b/SocketService/Program.cs @@ -1,16 +1,15 @@ using System; -using System.Collections.Generic; -using System.Linq; +using System.Configuration.Install; +using System.Reflection; using System.ServiceProcess; -using System.Text; using System.Windows.Forms; -using System.Reflection; using log4net; namespace SocketService { static class Program { + private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// The main entry point for the application. /// @@ -18,22 +17,63 @@ static void Main(String [] args) { log4net.Config.XmlConfigurator.Configure(); - if (args.Length > 0) + //var servicesToRun = new ServiceBase[] { new SocketService() }; + + //if (args.Length > 0) + //{ + // if (args[0].ToLower() == "/gui") + // { + // var form = new ServerControlForm(); + // Application.Run(form); + // } + //} + //else + //{ + // ServiceBase.Run(servicesToRun); + //} + + if (args.Length > 0 && args[0].Trim().ToLower() == "/i") { - if (args[0].ToLower() == "/gui") + //Install service + try { - ServerControlForm form = new ServerControlForm(); - Application.Run(form); + ManagedInstallerClass.InstallHelper(new[] { "/i", Assembly.GetExecutingAssembly().Location }); + + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } + } + else if (args.Length > 0 && args[0].Trim().ToLower() == "/u") + { + try + { + //Uninstall service + ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location }); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); } } else { - ServiceBase[] ServicesToRun; - ServicesToRun = new ServiceBase[] - { - new SocketService() - }; - ServiceBase.Run(ServicesToRun); + using (var service = new SocketService()) + { + if (args.Length > 0 && args[0].Equals("RunAsService")) + { + service.RunAsService = true; + } + else + { + service.RunAsService = false; + } + + //ConfigureUnhandledExceptionHandling(); + + service.Run(); + } } } } diff --git a/SocketService/Properties/AssemblyInfo.cs b/SocketService/Properties/AssemblyInfo.cs index 80ad3fb..e425c43 100644 --- a/SocketService/Properties/AssemblyInfo.cs +++ b/SocketService/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following diff --git a/SocketService/Repository/IRepository.cs b/SocketService/Repository/IRepository.cs index 03050d9..8348851 100644 --- a/SocketService/Repository/IRepository.cs +++ b/SocketService/Repository/IRepository.cs @@ -1,14 +1,12 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Linq.Expressions; namespace SocketService.Repository { public interface IRepository { - T Find(int id); + T Find(long id); T[] GetAll(); IQueryable Query(Expression> filter); diff --git a/SocketService/Repository/RoomRepository.cs b/SocketService/Repository/RoomRepository.cs index 37ab26d..f7177f2 100644 --- a/SocketService/Repository/RoomRepository.cs +++ b/SocketService/Repository/RoomRepository.cs @@ -1,9 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Data; +using SocketService.Core.Data; using System.Linq.Expressions; +using Room = SocketService.Core.Data.Room; namespace SocketService.Repository { @@ -16,15 +15,7 @@ public class RoomRepository : IRepository, IDisposable /// public static RoomRepository Instance { - get - { - if (_instance == null) - { - _instance = new RoomRepository(); - } - - return _instance; - } + get { return _instance ?? (_instance = new RoomRepository()); } } private readonly ServerDataEntities _context; @@ -32,9 +23,9 @@ public RoomRepository() : this(DatabaseContextFactory.Context) { } - public RoomRepository(ServerDataEntities Context) + public RoomRepository(ServerDataEntities context) { - _context = Context; + _context = context; } ///// @@ -68,7 +59,7 @@ public void Dispose() } - public Room Find(int id) + public Room Find(long id) { return _context.Rooms. Where(r => r.Id == id). diff --git a/SocketService/Repository/ServiceHandlerRepository.cs b/SocketService/Repository/ServiceHandlerRepository.cs index 5c3ff7d..354f99d 100644 --- a/SocketService/Repository/ServiceHandlerRepository.cs +++ b/SocketService/Repository/ServiceHandlerRepository.cs @@ -1,23 +1,18 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; -using System.Reflection; using System.IO; -using System.Configuration; -using SocketService.Framework.Configuration; -using SocketService.Framework.ServiceHandlerLib; +using System.Linq; +using System.Reflection; +using SocketService.Core.ServiceHandlerLib; -namespace SocketService +namespace SocketService.Repository { public class ServiceHandlerLookup // : IServiceHandlerRepository { - [ImportMany] - protected IEnumerable> _handlerList; - - private static ServiceHandlerLookup _instance = null; + private static ServiceHandlerLookup _instance; + [ImportMany] protected IEnumerable> HandlerList; /// /// Initializes the class. @@ -27,40 +22,29 @@ static ServiceHandlerLookup() Instance.LoadHandlers(); } + protected ServiceHandlerLookup() + { + //string handlerPath + } + /// /// Gets the instance. /// public static ServiceHandlerLookup Instance { - get - { - if (_instance == null) - { - _instance = new ServiceHandlerLookup(); - } - - return _instance; - } - } - - protected ServiceHandlerLookup() - { - //string handlerPath + get { return _instance ?? (_instance = new ServiceHandlerLookup()); } } /// /// Gets the handler list by type. /// - /// The type. /// public List GetHandlerListByType(Type type) { - List serviceHandlers = new List(); - - serviceHandlers = _handlerList - .Where((h) => h.Metadata.HandlerType == type) - .Select((lz) => lz.Value) - .ToList(); + List serviceHandlers = HandlerList + .Where(h => h.Metadata.HandlerType == type) + .Select(lz => lz.Value) + .ToList(); return serviceHandlers; } @@ -68,26 +52,31 @@ public List GetHandlerListByType(Type type) /// /// Loads the handlers. /// - /// The handler path. public void LoadHandlers() { - SocketServiceConfiguration config = null; - - try - { config = (SocketServiceConfiguration)ConfigurationManager.GetSection("SocketServerConfiguration"); } - catch (Exception) - { } + //try + //{ + // (SocketServiceConfiguration) ConfigurationManager.GetSection("SocketServerConfiguration"); + //} + //catch (Exception) + //{ + //} var aggregateCatalog = new AggregateCatalog(); - Assembly callingAssembly = Assembly.GetExecutingAssembly(); + var callingAssembly = Assembly.GetExecutingAssembly(); // an assembly catalog to load information about parts from this assembly var assemblyCatalog = new AssemblyCatalog(callingAssembly); - var directoryCatalog = new DirectoryCatalog(Path.GetDirectoryName(callingAssembly.Location), "*.dll"); - aggregateCatalog.Catalogs.Add(assemblyCatalog); - aggregateCatalog.Catalogs.Add(directoryCatalog); + var assemblyLocation = Path.GetDirectoryName(callingAssembly.Location); + if (assemblyLocation != null) + { + var directoryCatalog = new DirectoryCatalog(assemblyLocation, "*.dll"); + + aggregateCatalog.Catalogs.Add(assemblyCatalog); + aggregateCatalog.Catalogs.Add(directoryCatalog); + } // create a container for our catalogs var container = new CompositionContainer(aggregateCatalog); @@ -96,4 +85,4 @@ public void LoadHandlers() container.ComposeParts(this); } } -} +} \ No newline at end of file diff --git a/SocketService/Repository/UserRepository.cs b/SocketService/Repository/UserRepository.cs index cc65458..6cd6869 100644 --- a/SocketService/Repository/UserRepository.cs +++ b/SocketService/Repository/UserRepository.cs @@ -1,29 +1,23 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Data; +using System.Reflection; +using SocketService.Core.Data; +using log4net; +using User = SocketService.Core.Data.User; namespace SocketService.Repository { public class UserRepository : IRepository, IDisposable { - private static UserRepository _instance = null; + private static UserRepository _instance; + private static ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// Gets the instance. /// public static UserRepository Instance { - get - { - if (_instance == null) - { - _instance = new UserRepository(); - } - - return _instance; - } + get { return _instance ?? (_instance = new UserRepository()); } } private readonly ServerDataEntities _context; @@ -33,10 +27,12 @@ public UserRepository() : this(DatabaseContextFactory.Context) { } - public UserRepository(ServerDataEntities Context) + public UserRepository(ServerDataEntities context) { - _context = Context; + if (context == null) throw new ArgumentNullException("context"); + _context = context; } + #endregion ///// ///// Finds the users by room. @@ -98,7 +94,7 @@ public UserRepository(ServerDataEntities Context) //} #region IRepository Members - public User Find(int id) + public User Find(long id) { return _context.Users. Where(u => u.Id == id). @@ -133,19 +129,41 @@ public void Dispose() public void Add(User value) { - _context.AddToUsers(value); - _context.SaveChanges(); + try + { + _context.AddToUsers(value); + _context.SaveChanges(); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } + } public void Delete(User value) { - _context.DeleteObject(value); - _context.SaveChanges(); + try + { + _context.DeleteObject(value); + _context.SaveChanges(); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } } public void Update(User value) { - _context.SaveChanges(); + try + { + _context.SaveChanges(); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } } } } diff --git a/SocketService/Repository/ZoneRepository.cs b/SocketService/Repository/ZoneRepository.cs index b80abda..9cf42c1 100644 --- a/SocketService/Repository/ZoneRepository.cs +++ b/SocketService/Repository/ZoneRepository.cs @@ -1,8 +1,7 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using SocketService.Framework.Data; +using SocketService.Core.Data; +using Zone = SocketService.Core.Data.Zone; namespace SocketService.Repository { @@ -10,19 +9,11 @@ public class ZoneRepository : IRepository, IDisposable { private readonly ServerDataEntities _context; - private static ZoneRepository _instance = null; + private static ZoneRepository _instance; public static ZoneRepository Instance { - get - { - if (_instance == null) - { - _instance = new ZoneRepository(); - } - - return _instance; - } + get { return _instance ?? (_instance = new ZoneRepository()); } } #region ctor @@ -30,13 +21,13 @@ public ZoneRepository() : this(DatabaseContextFactory.Context) { } - public ZoneRepository(ServerDataEntities Context) + public ZoneRepository(ServerDataEntities context) { - _context = Context; + _context = context; } #endregion - public Zone Find(int id) + public Zone Find(long id) { return _context.Zones. Where(z => z.Id == id). diff --git a/SocketService/ServerControlForm.Designer.cs b/SocketService/ServerControlForm.Designer.cs index c6ba7cf..9107fb4 100644 --- a/SocketService/ServerControlForm.Designer.cs +++ b/SocketService/ServerControlForm.Designer.cs @@ -40,7 +40,7 @@ private void InitializeComponent() this.startButton.TabIndex = 0; this.startButton.Text = "Start"; this.startButton.UseVisualStyleBackColor = true; - this.startButton.Click += new System.EventHandler(this.startButton_Click); + this.startButton.Click += new System.EventHandler(this.StartButtonClick); // // stopButton // @@ -50,7 +50,7 @@ private void InitializeComponent() this.stopButton.TabIndex = 1; this.stopButton.Text = "Stop"; this.stopButton.UseVisualStyleBackColor = true; - this.stopButton.Click += new System.EventHandler(this.stopButton_Click); + this.stopButton.Click += new System.EventHandler(this.StopButtonClick); // // ServerControlForm // @@ -61,7 +61,7 @@ private void InitializeComponent() this.Controls.Add(this.startButton); this.Name = "ServerControlForm"; this.Text = "ServerControlForm"; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ServerControlForm_FormClosing); + this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ServerControlFormFormClosing); this.ResumeLayout(false); } diff --git a/SocketService/ServerControlForm.cs b/SocketService/ServerControlForm.cs index fe156b2..9c49c69 100644 --- a/SocketService/ServerControlForm.cs +++ b/SocketService/ServerControlForm.cs @@ -1,47 +1,36 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; -using System.Security.Cryptography; -using System.IO; -using System.Threading; -using System.Runtime.Serialization.Formatters.Binary; -using System.IO.Compression; -using SocketService.Framework.Messaging; +using SocketService.Core.Messaging; using SocketService.Net; namespace SocketService { public partial class ServerControlForm : Form { - private readonly SocketManager serverManager = new SocketManager(); - private readonly MessageServer messageServer = new MessageServer(); + private readonly SocketManager _serverManager = new SocketManager(); + private readonly MessageServer _messageServer = new MessageServer(); public ServerControlForm() { InitializeComponent(); } - private void startButton_Click(object sender, EventArgs e) + private void StartButtonClick(object sender, EventArgs e) { - messageServer.Start(); - serverManager.StartServer(); + _messageServer.Start(); + _serverManager.StartServer(); } - private void stopButton_Click(object sender, EventArgs e) + private void StopButtonClick(object sender, EventArgs e) { - serverManager.StopServer(); - messageServer.Stop(); + _serverManager.StopServer(); + _messageServer.Stop(); } - private void ServerControlForm_FormClosing(object sender, FormClosingEventArgs e) + private void ServerControlFormFormClosing(object sender, FormClosingEventArgs e) { - serverManager.StopServer(); - messageServer.Stop(); + _serverManager.StopServer(); + _messageServer.Stop(); } } diff --git a/SocketService/SocketService.cs b/SocketService/SocketService.cs index 454fb7d..04400ee 100644 --- a/SocketService/SocketService.cs +++ b/SocketService/SocketService.cs @@ -1,38 +1,69 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Diagnostics; -using System.Linq; using System.ServiceProcess; -using System.Text; -using SocketService.Framework.Messaging; +using SocketService.Core.Messaging; using SocketService.Net; namespace SocketService { - public partial class SocketService : ServiceBase + public partial class SocketService : SocketServiceBase { - private readonly SocketManager serverManager = new SocketManager(); - private readonly MessageServer messageServer = new MessageServer(); + private readonly SocketManager _serverManager = new SocketManager(); + private readonly MessageServer _messageServer = new MessageServer(); public SocketService() { InitializeComponent(); + } + + public override void StartService() + { + InitializeCounters(); + _serverManager.StartServer(); + _messageServer.Start(); } - protected override void OnStart(string[] args) + private static void InitializeCounters() { - // TODO: Make port configurable - serverManager.StartServer(); - messageServer.Start(); + try + { + var counterDatas = + new CounterCreationDataCollection(); + + // Create the counters and set their properties. + var cdCounter1 = + new CounterCreationData(); + var cdCounter2 = + new CounterCreationData(); + + cdCounter1.CounterName = "Total Requests Handled"; + cdCounter1.CounterHelp = "Total number of requests handled"; + cdCounter1.CounterType = PerformanceCounterType.NumberOfItems64; + cdCounter2.CounterName = "Requests Per Secpmd"; + cdCounter2.CounterHelp = "Average number of requests per second."; + cdCounter2.CounterType = PerformanceCounterType.RateOfCountsPerSecond64; + + // Add both counters to the collection. + counterDatas.Add(cdCounter1); + counterDatas.Add(cdCounter2); + + // Create the category and pass the collection to it. + PerformanceCounterCategory.Create( + "Socket Service Data Stats", "Stats for the socket service.", + PerformanceCounterCategoryType.MultiInstance, counterDatas); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } + } - protected override void OnStop() + public override void StopService() { - serverManager.StopServer(); - messageServer.Stop(); + _serverManager.StopServer(); + _messageServer.Stop(); } } } diff --git a/SocketService/SocketService.cs.orig b/SocketService/SocketService.cs.orig new file mode 100644 index 0000000..e19e82f --- /dev/null +++ b/SocketService/SocketService.cs.orig @@ -0,0 +1,75 @@ +<<<<<<< Updated upstream +using System.ServiceProcess; +using SocketService.Core.Messaging; +======= +using System; +using System.Diagnostics; +using System.ServiceProcess; +using SocketService.Framework; +using SocketService.Framework.Messaging; +>>>>>>> Stashed changes +using SocketService.Net; + +namespace SocketService +{ + public partial class SocketService : SocketServiceBase + { + private readonly SocketManager _serverManager = new SocketManager(); + private readonly MessageServer _messageServer = new MessageServer(); + + public SocketService() + { + InitializeComponent(); + } + + public override void StartService() + { + InitializeCounters(); + + _serverManager.StartServer(); + _messageServer.Start(); + } + + private void InitializeCounters() + { + try + { + var counterDatas = + new CounterCreationDataCollection(); + + // Create the counters and set their properties. + var cdCounter1 = + new CounterCreationData(); + var cdCounter2 = + new CounterCreationData(); + + cdCounter1.CounterName = "Total Bytes Received"; + cdCounter1.CounterHelp = "Total number of bytes recieved"; + cdCounter1.CounterType = PerformanceCounterType.NumberOfItems64; + cdCounter2.CounterName = "Total Bytes Sent"; + cdCounter2.CounterHelp = "Total number of bytes transmitted."; + cdCounter2.CounterType = PerformanceCounterType.NumberOfItems64; + + // Add both counters to the collection. + counterDatas.Add(cdCounter1); + counterDatas.Add(cdCounter2); + + // Create the category and pass the collection to it. + PerformanceCounterCategory.Create( + "Socket Service Data Stats", "Stats for the socket service.", + PerformanceCounterCategoryType.MultiInstance, counterDatas); + } + catch (Exception ex) + { + Logger.Error(ex.ToString()); + } + + } + + public override void StopService() + { + _serverManager.StopServer(); + _messageServer.Stop(); + } + } +} diff --git a/SocketService/SocketService.csproj b/SocketService/SocketService.csproj index 042fdbb..aba4d99 100644 --- a/SocketService/SocketService.csproj +++ b/SocketService/SocketService.csproj @@ -6,7 +6,7 @@ 8.0.30703 2.0 {3B89D58C-5E4E-4F7A-B256-2DE189684322} - WinExe + Exe Properties SocketService SocketService @@ -34,6 +34,9 @@ prompt 4 + + + ..\References\log4net.dll @@ -85,6 +88,7 @@ + @@ -110,23 +114,34 @@ + + Component + Component - + {93FD4F32-5214-40E3-8E36-5B4E354F10C4} - SocketService.Framework.Client + SocketService.Client.Core - + {4138075A-49CD-4A46-92CB-DFF64A0BB0B6} - SocketService.Crypto + SocketService.Core.Crypto - + {A0CAE0A0-EFA9-452B-98FB-5FE3172FCD1B} - SocketService.Framework + SocketService.Core + + + {656E34AF-78EA-4ED0-B67C-B3EA28E002C9} + SocketService.Event + + + {7C9013CF-CEC4-4F7D-B80D-C6FA2E243CF1} + SocketService.Shared diff --git a/SocketService/SocketServiceInstaller.cs b/SocketService/SocketServiceInstaller.cs index 3fe8e8a..1141c23 100644 --- a/SocketService/SocketServiceInstaller.cs +++ b/SocketService/SocketServiceInstaller.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.ComponentModel; using System.Configuration.Install; -using System.ComponentModel; -using System.ServiceProcess; using System.Diagnostics; +using System.ServiceProcess; namespace SocketService { @@ -16,15 +12,14 @@ public SocketServiceInstaller() { var processInstaller = new ServiceProcessInstaller(); var serviceInstaller = new ServiceInstaller(); - + ////Create Instance of EventLogInstaller - var myEventLogInstaller = new EventLogInstaller(); + var myEventLogInstaller = new EventLogInstaller + {Source = "Blazing Sockets Messaging Server", Log = "Application"}; //// Set the Source of Event Log, to be created. - myEventLogInstaller.Source = "Blazing Sockets Messaging Server"; //// Set the Log that source is created in - myEventLogInstaller.Log = "Application"; //set the process privileges processInstaller.Account = ServiceAccount.User; @@ -36,9 +31,9 @@ public SocketServiceInstaller() serviceInstaller.ServiceName = "Blazing Sockets Messaging Server"; - this.Installers.Add(processInstaller); - this.Installers.Add(serviceInstaller); - this.Installers.Add(myEventLogInstaller); + Installers.Add(processInstaller); + Installers.Add(serviceInstaller); + Installers.Add(myEventLogInstaller); } } -} +} \ No newline at end of file diff --git a/SocketService/app.config b/SocketService/app.config index aeb44a2..5c00b49 100644 --- a/SocketService/app.config +++ b/SocketService/app.config @@ -2,25 +2,75 @@
-
+
- + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + + diff --git a/SocketService/app.config.orig b/SocketService/app.config.orig new file mode 100644 index 0000000..e712c80 --- /dev/null +++ b/SocketService/app.config.orig @@ -0,0 +1,97 @@ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +<<<<<<< Updated upstream + + + + +======= + + + + + + +>>>>>>> Stashed changes + + + + + + + + + + + \ No newline at end of file