public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
        {
            Mobile pm = ( Mobile )sender.Mobile;

            if( pm == null )
                return;

            switch (info.ButtonID)
            {
                case 2:
                    {
                        TextRelay text = info.GetTextEntry( 1 );

                        if (text == null || text.Text == "")
                        {
                            pm.CloseGump(typeof(AccountSearch));
                            pm.SendGump(new AccountSearch());
                            return;
                        }

                        ArrayList authors = new ArrayList();

                        if (ForumCore.AuthorExists( out authors, text.Text))
                        {
                            pm.CloseGump( typeof(AccountListingGump));
                            pm.SendGump( new AccountListingGump( authors, 0 ) );
                        }
                        else
                        {
                            pm.SendMessage("Either that player does not exist, or no posts have been made by that player.");
                        }
                        break;
                    }
            }
        }
Exemplo n.º 2
0
        public void Init()
        {
            _client = new Client.Core.CacheClient();
            var channel = new InProcessChannel();

            _client.Channel = channel;

            var cfg          = new ServerConfig();
            var cfgDatastore = new ServerDatastoreConfig
            {
                Eviction =
                    new EvictionPolicyConfig(
                        EvictionType.LessRecentlyUsed, 100, 10),
                FullTypeName = typeof(CacheableTypeOk).FullName
            };

            //activate eviction when more than 100 items in cache (evict 10 items)
            cfg.ConfigByType.Add(cfgDatastore.FullTypeName, cfgDatastore);
            _server = new Server.Server(cfg)
            {
                Channel = channel
            };
            _server.Start();

            _client.RegisterTypeIfNeeded(typeof(CacheableTypeOk));
        }
        public void Init()
        {
            _client = new CacheClient();
            var channel = new InProcessChannel();

            _client.Channel = channel;


            _server = new Server.Server(new NodeConfig())
            {
                Channel = channel
            };
            _server.Start();

            _client.RegisterTypeIfNeeded(typeof(CacheableTypeOk));

            var cfg = new ClientConfig();

            cfg.LoadFromFile("CacheClientConfig.xml");

            foreach (var description in cfg.TypeDescriptions)
            {
                if (description.Value.FullTypeName == "UnitTests.TestData.Trade")
                {
                    _client.RegisterTypeIfNeeded(typeof(Trade), description.Value);
                }
            }
        }
Exemplo n.º 4
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			if ( ! AuctionSystem.Running )
			{
				sender.Mobile.SendMessage( AuctionConfig.MessageHue, AuctionSystem.ST[ 15 ] );
				return;
			}

			switch( info.ButtonID )
			{
				case 0:

					if ( m_Callback != null )
					{
						try { m_Callback.DynamicInvoke( new object[] { sender.Mobile } ); }
						catch {}
					}
					break;

				case 1: // View your auctions

					sender.Mobile.SendGump( new AuctionListing( sender.Mobile, AuctionSystem.GetAuctions( sender.Mobile ), false, false ) );
					break;

				case 2: // View your bids

					sender.Mobile.SendGump( new AuctionListing( sender.Mobile, AuctionSystem.GetBids( sender.Mobile ), false, false ) );
					break;

				case 3: // View your pendencies

					sender.Mobile.SendGump( new AuctionListing( sender.Mobile, AuctionSystem.GetPendencies( sender.Mobile ), false, false ) );
					break;
			}
		}
Exemplo n.º 5
0
		public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
		{
			if ( info.ButtonID == 2 )
			{
				if ( !m_Pet.Deleted && m_Pet.Controlled && m_From == m_Pet.ControlMaster && m_From.CheckAlive() && m_Pet.CheckControlChance( m_From ) )
				{
					if ( m_Pet.Map == m_From.Map )
					{
						if ( m_RangeCheck == true && !m_Pet.InRange( m_From, 14 ) )
						{
							m_From.SendMessage( "You are too far away from your pet." );
							return;
						}

						m_Pet.ControlTarget = null;
						m_Pet.ControlOrder = OrderType.Release;
						//Pix: added kick to Obey because when we added the ability to release a 'lost'
						// pet, if there were no players around, the pet would not release until a player
						// got in range of the pet.  This wasn't an issue before because there was 
						// a range check involved so there was always a player around when releasing the pet.
						m_Pet.AIObject.Obey();
						BaseHire m_Hire = m_Pet as BaseHire;	//added by Old Salty from here . . .
						if ( m_Hire != null && m_Hire.IsHired ) 
						{
							m_Hire.IsHired = false;
						}										//. . . to here
					}
				}
			}
		}
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			switch ( info.ButtonID )
			{
				case 1: // Validate

					AuctionSystem.VerifyAuctions();
					AuctionSystem.VerifyPendencies();

					sender.Mobile.SendGump( new AuctionAdminGump( sender.Mobile ) );
					break;

				case 2: // Profile

					AuctionSystem.ProfileAuctions();

					sender.Mobile.SendGump( new AuctionAdminGump( sender.Mobile ) );
					break;

				case 3: // Disable

					AuctionSystem.Disable();
					sender.Mobile.SendMessage( AuctionConfig.MessageHue, "The system has been stopped. It will be restored with the next reboot." );
					break;

				case 4: // Delete

					sender.Mobile.SendGump( new DeleteAuctionGump( sender.Mobile ) );
					break;
			}
		}
Exemplo n.º 7
0
        public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
        {
            int val, type, index;
            DecodeButtonId(info.ButtonID, out val, out type, out index);

            if( val < 0 )
                return;

            switch( type )
            {
                case 1:
                    {
                        switch( index )
                        {
                            case 0: //purchase
                                {
                                    Market.BuyItem(sender.Mobile, _entry);
                                    break;
                                }
                            case 1: //go back
                                {
                                    sender.Mobile.CloseGump(typeof(MarketDetailsGump));
                                    break;
                                }
                        }

                        break;
                    }
            }
        }
Exemplo n.º 8
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			string web = null;

			switch ( info.ButtonID )
			{
				case 1 : web = "http://www.chessvariants.com/d.chess/chess.html";
					break;
				case 2 : web = "http://www.chessvariants.com/d.chess/faq.html";
					break;
				case 3 : web = "http://www.chessvariants.com/d.chess/matefaq.html";
					break;
				case 4 : web = "http://www.chessvariants.com/d.chess/castlefaq.html";
					break;
				case 5 : web = "http://www.chessvariants.com/d.chess/enpassant.html";
					break;
				case 6 : web = "http://www.chessvariants.com/d.chess/pawnfaq.html";
					break;
				case 7 : web = "http://www.chessvariants.com/d.chess/knightfaq.html";
					break;
				case 8 : web = "http://www.chessvariants.com/d.chess/queenfaq.html";
					break;
				case 9 : web = "http://www.chessvariants.com/d.chess/kingfaq.html";
					break;
			}

			if ( web != null )
			{
				sender.Mobile.LaunchBrowser( web );
				sender.Mobile.SendGump( this );
			}
		}
Exemplo n.º 9
0
		public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
		{
			if ( info.ButtonID == 1 && m_Callback != null )
				m_Callback( sender.Mobile, true, m_State );
			else if ( m_Callback != null )
				m_Callback( sender.Mobile, false, m_State );
		}
Exemplo n.º 10
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			if ( info.ButtonID == 1 )
			{
				AuctionSystem.ForceDelete( sender.Mobile );
			}
		}
Exemplo n.º 11
0
		public static void FindRunes_OnCommand( Server.Commands.CommandEventArgs e )
		{
			foreach ( Item item in World.Items.Values )
			{
				if ( item is RecallRune )
				{
					RecallRune rune = (RecallRune)item;

					if ( rune.Marked && rune.TargetMap != null && IsBad( rune.Target, rune.TargetMap ) )
					{
						object root = item.RootParent;

						if ( root is Mobile )
						{
							if ( ((Mobile)root).AccessLevel < AccessLevel.GameMaster )
								e.Mobile.SendAsciiMessage( "Rune: '{4}' {0} [{1}]: {2} ({3})", item.GetWorldLocation(), item.Map, root.GetType().Name, ((Mobile)root).Name, rune.Description );
						}
						else
						{
							e.Mobile.SendAsciiMessage( "Rune: '{3}' {0} [{1}]: {2}", item.GetWorldLocation(), item.Map, root==null ? "(null)" : root.GetType().Name, rune.Description );
						}
					}
				}
			}
		}
Exemplo n.º 12
0
 static void Main(string[] args)
 {
     var server = new Server();
     server.LoadConfig();
     server.Run();
     Console.ReadLine();
 }
Exemplo n.º 13
0
        /// <summary>
        /// Serialization
        /// </summary>
        protected override void Serialize( Server.GenericWriter writer )
        {
            base.Serialize(writer);

            writer.Write((int)1); //version
            writer.Write(Ambush);
        }
Exemplo n.º 14
0
        public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
        {
            if ( m_IsOwner )
            {
                if ( info.ButtonID == 3 )
                {
                    // Switch the allow spectators flag
                    m_Game.AllowSpectators = !m_AllowSpectators;
                    sender.Mobile.SendGump( new StartGameGump( sender.Mobile, m_Game, m_IsOwner, !m_AllowSpectators ) );
                }
                else if ( info.ButtonID == 2 )
                {
                    m_Game.CancelGameStart( sender.Mobile );
                }
                else if ( info.ButtonID == 1 )
                {
                    sender.Mobile.Target = new ChessTarget( m_Game, sender.Mobile, "Please select your partner...",
                        new ChessTargetCallback( m_Game.ChooseOpponent ) );

                    sender.Mobile.SendGump( new StartGameGump( sender.Mobile, m_Game, m_IsOwner, m_AllowSpectators ) );
                }
            }
            else
            {
                if ( info.ButtonID == 2 )
                {
                    m_Game.CancelGameStart( sender.Mobile );
                }
                else if ( info.ButtonID == 1 )
                {
                    m_Game.AcceptGame( sender.Mobile );
                }
            }
        }
Exemplo n.º 15
0
        public void ExecuteCommands()
        {
            var client  = new CacheClient();
            var channel = new InProcessChannel();

            client.Channel = channel;
            var server = new Server.Server(new NodeConfig())
            {
                Channel = channel
            };

            server.Start();


            client.RegisterTypeIfNeeded(typeof(TradeLike));


            var serverDesc = client.GetClusterInformation();

            Assert.AreEqual(serverDesc.Schema.Length, 1);
            var parser = new CommandLineParser(serverDesc);

            var cmd = parser.Parse("desc");

            cmd.TryExecute(client);


            cmd = parser.Parse("desc TRADELIKE");
            cmd.TryExecute(client);


            cmd = parser.Parse("count from TRADELIKE where folder=aaa ");
            cmd.TryExecute(client);
        }
Exemplo n.º 16
0
        /// <summary>
        /// The main entry point for the server application.
        /// </summary>
        static void Main()
        {
            Console.Title = "Server is stopped";

            Server server = new Server(443);

            // commands
            Console.WriteLine("Server is stopped.");
            Console.WriteLine("==================");
            Console.WriteLine("Commands:");
            Console.WriteLine("start - Start listening to clients.");
            Console.WriteLine("stop - Stop listening to clients.");
            Console.WriteLine("exit - Close server.");
            Console.WriteLine();

            while (true)
            {
                string command = Console.ReadLine();

                if ("start".Equals(command))
                {
                    server.Start();
                    Console.Title = "Server is running";
                }
                else if ("stop".Equals(command))
                {
                    server.Stop();
                    Console.Title = "Server is stopped";
                }
                else if ("exit".Equals(command))
                    return;
            }
        }
Exemplo n.º 17
0
 public ObjectWindow(Server.Objects.Object objct)
 {
     InitializeComponent();
     this.objct = objct;
     this.Text = "View " + objct.Id;
     refresher.RefreshTick += new EventHandler(refresher_RefreshTick);
 }
Exemplo n.º 18
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			if ( ! m_Buttons.Contains( info.ButtonID ) )
			{
				Console.WriteLine( @"The auction system located a potential exploit. 
					Player {0} (Acc. {1}) tried to press an unregistered button in a gump of type: {2}",
					sender.Mobile != null ? sender.Mobile.ToString() : "Unkown",
					sender.Mobile != null && sender.Mobile.Account != null ? ( sender.Mobile.Account as Server.Accounting.Account ).Username : "******",
					this.GetType().Name );

				return;
			}

			if ( ! AuctionSystem.Running )
			{
				sender.Mobile.SendMessage( AuctionSystem.MessageHue, AuctionSystem.ST[ 15 ] );
				return;
			}

			switch ( info.ButtonID )
			{
				case 0: // Exit

					break;

				case 1: // Create auction

					AuctionSystem.AuctionRequest( sender.Mobile );

					break;

				case 2: // View all auctions

					sender.Mobile.SendGump( new AuctionListing(
						sender.Mobile,
						AuctionSystem.Auctions,
						true,
						true ) );

					break;

				case 3: // View your auctions

					sender.Mobile.SendGump( new AuctionListing(
						sender.Mobile, AuctionSystem.GetAuctions( sender.Mobile ), true, true ) );
					break;

				case 4: // View your bids

					sender.Mobile.SendGump( new AuctionListing(
						sender.Mobile, AuctionSystem.GetBids( sender.Mobile ), true, true ) );
					break;

				case 5: // View pendencies

					sender.Mobile.SendGump( new AuctionListing(
						sender.Mobile, AuctionSystem.GetPendencies( sender.Mobile ), true, true ) );
					break;
			}
		}
Exemplo n.º 19
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			PawnPromotion type = PawnPromotion.None;

			switch ( info.ButtonID )
			{
				case 0 :
						return; // This fixes a crash when staff deletes the pawn being promoted

				case 1 : type = PawnPromotion.Queen;
					break;

				case 2 : type = PawnPromotion.Rook;
					break;

				case 3 : type = PawnPromotion.Knight;
					break;

				case 4 : type = PawnPromotion.Bishop;
					break;

				case 5: type = PawnPromotion.None;
					break;
			}

			m_Game.OnPawnPromoted( type );
		}
Exemplo n.º 20
0
 public override void ExecuteList( Server.Commands.CommandEventArgs e, ArrayList list )
 {
     if ( list.Count > 0 )
         e.Mobile.SendGump( new InterfaceGump( e.Mobile, list, 0 ) );
     else
         AddResponse( "No matching objects found." );
 }
        public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
        {
            switch ( info.ButtonID )
            {
                case 0: // Close Gump
                {
                    switch ( Select )
                    {
                        case 1: { MessagesTitle = "Delete All Items"; Messages = "You have chosen not to delete all items."; break; }
                        case 2: { MessagesTitle = "Delete Selected Items"; Messages = "You have chosen not to delete selected items."; break; }
                    }

                    SetArgsList();

                    gumpMobile.SendGump( new AddItemsToContainerGump( gumpMobile, ArgsList ) );

                    break;
                }
                case 1: // Delete Items
                {
                    switch ( Select )
                    {
                        case 1: // Delete All Items
                        {
                            InsideItemList.Clear();
                            AITCCheckBoxesList.Clear();

                            MessagesTitle = "Delete All Items";
                            Messages = "All of the items have been deleted.";

                            break;
                        }
                        case 2: // Delete Selected Items
                        {
                            for ( int i = 0; i < InsideItemList.Count; i++ )
                            {
                                if ( (bool) AITCCheckBoxesList[i] )
                                {
                                    InsideItemList.RemoveAt( i );
                                    AITCCheckBoxesList.RemoveAt( i );

                                    i--;
                                }
                            }

                            MessagesTitle = "Delete Selected Items";
                            Messages = "All selected items have been deleted.";

                            break;
                        }
                    }

                    SetArgsList();

                    gumpMobile.SendGump( new AddItemsToContainerGump( gumpMobile, ArgsList ) );

                    break;
                }
            }
        }
Exemplo n.º 22
0
		public override void OnResponse( Server.Network.NetState state, int index )
		{
			if( index == 0 )
			{
				OnCancel( state );
			}
			else if( index == 1 )
			{
				PageEntry entry = PageQueue.GetEntry( _from );

				if( entry != null )
				{
					if( entry.Handler != null )
					{
						_from.SendMessage( "Your page is currently being handled by a staff member, and cannot be cancelled at this time." );
					}
					else
					{
						_from.SendLocalizedMessage( 1005307, "", 0x35 ); //Removed help request.

						PageQueue.Remove( entry );
					}
				}
				else
				{
					OnCancel( state );
				}
			}
		}
Exemplo n.º 23
0
		public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
		{
			if( info.ButtonID == 0 )
			{
				_from.SendLocalizedMessage( 501235, "", 0x35 ); //Help request aborted.
				return;
			}
			else
			{
				TextRelay txtEntry = info.GetTextEntry( 0 );
				string text = (txtEntry == null ? "" : txtEntry.Text);

				if( text.Length == 0 )
				{
					_from.SendMessage( 0x35, "You must enter a description of your problem." );
					_from.SendGump( new PagePromptGump( _from, _type ) );
				}
				else
				{
					_from.SendMessage( 0x35, "The next available staff member will be with you as soon as possible. If your issue is resolved early, please revoke it from the page queue. To check the statue of your page, type \'[CheckPage\'." );

					PageQueue.AddNewPage( new PageEntry( _from, text, _type ) );
				}
			}
		}
Exemplo n.º 24
0
        public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
        {
            switch ( info.ButtonID )
            {
                case 0: // Close Gump
                {
                    MessagesTitle = "Delete Account";
                    Messages = "You have chosen not to delete the account.";

                    SetArgsList();

                    gumpMobile.SendGump( new EditAccountGump( gumpMobile, ArgsList ) );

                    break;
                }
                case 1: // Delete Account
                {
                    MC.AccountsList.RemoveAt( index );
                    MC.AccessList.RemoveAt( index );
                    MC.AdminMenuAccessList.RemoveAt( index );
                    MC.AccountEditors.RemoveAt( index );

                    MC.SaveAccountsAccess();

                    MessagesTitle = "Delete Account";
                    Messages = "Account has been removed.";

                    SetArgsList();

                    gumpMobile.SendGump( new AccountsManagementGump( gumpMobile, ArgsList ) );

                    break;
                }
            }
        }
Exemplo n.º 25
0
        public override bool ValidateArgs( BaseCommandImplementor impl, Server.Commands.CommandEventArgs e )
        {
            if ( e.Length >= 1 )
            {
                Type t = ScriptCompiler.FindTypeByName( e.GetString( 0 ) );

                if ( t == null )
                {
                    e.Mobile.SendMessage( "No type with that name was found." );

                    string match = e.GetString( 0 ).Trim();

                    if ( match.Length < 3 )
                    {
                        e.Mobile.SendMessage( "Invalid search string." );
                        e.Mobile.SendGump( new Server.Gumps.AddGump( e.Mobile, match, 0, Type.EmptyTypes, false ) );
                    }
                    else
                    {
                        e.Mobile.SendGump( new Server.Gumps.AddGump( e.Mobile, match, 0, (Type[])Server.Gumps.AddGump.Match( match ).ToArray( typeof( Type ) ), true ) );
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                e.Mobile.SendGump( new Server.Gumps.CategorizedAddGump( e.Mobile ) );
            }

            return false;
        }
Exemplo n.º 26
0
		public static void ClearGuildListeners_OnCommand( Server.Commands.CommandEventArgs args )
		{
			if( _table.ContainsKey( args.Mobile ) )
				_table.Remove( args.Mobile );

			args.Mobile.SendMessage( "You are no longer listening to any private guild chat." );
		}
Exemplo n.º 27
0
		public override void OnResponse(Server.Network.NetState sender, RelayInfo info)
		{
			if ( ! m_Buttons.Contains( info.ButtonID ) )
			{
				Console.WriteLine( @"The auction system located a potential exploit. 
					Player {0} (Acc. {1}) tried to press an unregistered button in a gump of type: {2}",
					sender.Mobile != null ? sender.Mobile.ToString() : "Unkown",
					sender.Mobile != null && sender.Mobile.Account != null ? ( sender.Mobile.Account as Server.Accounting.Account ).Username : "******",
					this.GetType().Name );

				return;
			}

			if ( ! AuctionSystem.Running )
			{
				sender.Mobile.SendMessage( AuctionSystem.MessageHue, AuctionSystem.ST[ 15 ] );
				return;
			}

			if ( info.ButtonID == 1 )
			{
				if ( m_Message != null )
				{
					m_Message.SendTo( sender.Mobile );
				}
			}
		}
Exemplo n.º 28
0
        public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
        {
            switch ( info.ButtonID )
            {
                case 0: // Close Gump
                {
                    MessagesTitle = "Delete Entry";
                    Messages = "You have chosen not to delete the entry.";

                    SetArgsList();

                    gumpMobile.SendGump( new EditSpawnGump( gumpMobile, ArgsList ) );

                    break;
                }
                case 1: // Delete Entry
                {
                    if ( CheckProcess() )
                        break;

                    MSEGCheckBoxesList.RemoveAt( index );
                    megaSpawner.DeleteEntry( index );

                    MessagesTitle = "Delete Entry";
                    Messages = "Entry has been removed.";

                    SetArgsList();

                    gumpMobile.SendGump( new MegaSpawnerEditGump( gumpMobile, ArgsList ) );

                    break;
                }
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            bool exit = false;

            var obj = new Server();
            obj.Start();

            while (!exit)
            {
                var input = Console.ReadKey();

                switch (input.Key)
                {
                    case ConsoleKey.Escape:
                        exit = true;
                        obj.Close();
                        break;
                    case ConsoleKey.Spacebar:
                        obj.InterdaceUpdate();
                        break;
                    default:
                        break;
                }
            }
        }
        public void Init()
        {
            _client = new CacheClient();
            var channel = new InProcessChannel();

            _client.Channel = channel;
            _server         = new Server.Server(new NodeConfig())
            {
                Channel = channel
            };
            _server.Start();

            _client.RegisterTypeIfNeeded(typeof(CacheableTypeOk));
            _client.RegisterTypeIfNeeded(typeof(TradeLike));

            var serverDesc = _client.GetClusterInformation();

            _parser = new CommandLineParser(serverDesc);

            Logger.CommandLogger = _logger;

            if (File.Exists("export_test.json"))
            {
                File.Delete("export_test.json");
            }
        }
Exemplo n.º 31
0
        public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
        {
            Mobile m_Player = ( Mobile )sender.Mobile;

            if( m_Player == null )
                return;

            switch( info.ButtonID )
            {
                case 1:
                    {
                        ForumCore.AutoCleanup = true;
                        m_Player.CloseGump( typeof( AdministrationGump ) );
                        m_Player.SendGump( new AdministrationGump( ) );
                        break;
                    }
                case 2:
                    {
                        ForumCore.AutoCleanup = false;
                        m_Player.CloseGump( typeof( AdministrationGump ) );
                        m_Player.SendGump( new AdministrationGump( ) );
                        break;
                    }
            }
        }
Exemplo n.º 32
0
        private static void Main(string[] args)
        {
            var channelServ = new TcpChannel();
            ChannelServices.RegisterChannel(channelServ, false);

            var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
            ServerInit serverInit = mainServer.AddServer();

            channelServ.StopListening(null);
            ChannelServices.UnregisterChannel(channelServ);

            var server = new Server(serverInit);
            IDictionary properties = new Hashtable();
            int serverPort = Config.GetServerPort(serverInit.Uuid);
            const int serverTimeout = Config.InvocationTimeout;
            properties["port"] = serverPort;
            properties["timeout"] = serverTimeout;
            channelServ = new TcpChannel(properties, null, null);
            ChannelServices.RegisterChannel(channelServ, false);
            RemotingServices.Marshal(server, Config.RemoteServerObjName);

            server.StartSplitLock();

            foreach (var faultDetection in serverInit.FaultDetection)
            {
                var fd = (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(faultDetection.Key));
                fd.OnFaultDetectionReborn(serverInit.Uuid);
            }

            int backupId = -1;
            if ((serverInit.FaultDetection.Count == 1 && serverInit.FaultDetection.ContainsKey(serverInit.Parent) &&
                 serverInit.Parent != -1) || (serverInit.FaultDetection.Count == 0 && serverInit.Parent != -1))
            {
                backupId = serverInit.Parent;
            }
            else if (serverInit.FaultDetection.Count > 0)
            {
                backupId = serverInit.FaultDetection.Keys.Max();
            }

            if (backupId != -1)
            {
                /* Get data from backup */
                var backupServer = (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(backupId));
                backupServer.StartSplitLock();
                ParticipantStatus status = backupServer.OnChild(serverInit.Uuid, serverInit.Version,
                    serverInit.ServerCount);
                server.SetStatus(status);
                backupServer.EndSplitLock();
            }
            else
            {
                Console.WriteLine("Server need to have a backup server! Is it the first one?");
            }

            server.EndSplitLock();

            Console.WriteLine("Press <enter> to exit");
            Console.ReadLine();
        }
Exemplo n.º 33
0
 public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
 {
     if ( info.ButtonID == 2 )
     {
         if ( m_Victim != null && !m_Victim.Blessed && m_Vamp != null && m_Vamp.InRange(m_Victim, 1) && m_Victim.Alive &&
             m_Vamp.Alive && !m_Vamp.Paralyzed && m_Victim is PlayerMobile && !((PlayerMobile)m_Victim).IsVampire )
         {
             m_Vamp.Emote( "*feeds on {0}*", m_Victim.Name );
             m_Vamp.PlaySound( 49 );
             m_Victim.FixedParticles( 0x377A, 244, 25, 9950, 31, 0, EffectLayer.Head );
             m_Victim.Damage( 10 );
             ((PlayerMobile)m_Vamp).BPs += 2;
             ((PlayerMobile)m_Vamp).NextFeedingAllowed = DateTime.Now + TimeSpan.FromSeconds( 5 );
             foreach (DiseaseTimer timer in HealthAttachment.GetHA(m_Victim).CurrentDiseases)
             {
                 if (!HealthAttachment.GetHA(m_Vamp).HasDisease(timer.Disease))
                 {
                     DiseaseTimer newDis = new DiseaseTimer(m_Vamp, timer.Disease);
                     HealthAttachment.GetHA(m_Vamp).CurrentDiseases.Add(newDis);
                     newDis.Start();
                 }
             }
         }
     }
 }
Exemplo n.º 34
0
 public override void OnResponse( Server.Network.NetState sender, int index )
 {
     if ( index == 0 && m_Callback != null )
         m_Callback( sender.Mobile, true, m_State );
     else if ( m_Callback != null )
         m_Callback( sender.Mobile, false, m_State );
 }
Exemplo n.º 35
0
        public Connector(ClientConfig config)
        {
            if (Client == null)
            {
                if (config.Servers == null || config.Servers.Count == 0)
                {
                    var channel = new InProcessChannel();
                    Client = new DataClient {
                        Channel = channel
                    };

                    _server = new Server.Server(new NodeConfig
                    {
                        IsPersistent = config.IsPersistent,
                        DataPath     = "."
                    })
                    {
                        Channel = channel
                    };

                    _server.Start();
                }
                else if (config.Servers.Count == 1)
                {
                    var serverCfg = config.Servers[0];

                    var channel = new TcpClientChannel(new TcpClientPool(4, 1, serverCfg.Host, serverCfg.Port));

                    Client = new DataClient {
                        Channel = channel
                    };
                }
                else // multiple servers
                {
                    var aggregator = new DataAggregator();

                    var index = 0;
                    foreach (var serverConfig in config.Servers)
                    {
                        var channel =
                            new TcpClientChannel(new TcpClientPool(4, 1, serverConfig.Host, serverConfig.Port));

                        var client = new DataClient
                        {
                            Channel     = channel,
                            ShardIndex  = index,
                            ShardsCount = config.Servers.Count
                        };
                        aggregator.CacheClients.Add(client);
                        index++;
                    }


                    Client = aggregator;
                }
            }
        }
Exemplo n.º 36
0
 private void Server_button_listen_Click(object sender, EventArgs e)
 {
     try
     {
         serverEnd = new Server.Server(IPAddress.Parse(server_ip.Text), Convert.ToInt32(server_port.Text));
         serverEnd.StartListen();
     }
     catch (Exception ex) { MessageBox.Show(ex.ToString()); }
 }
Exemplo n.º 37
0
        public bool Start()
        {
            HostServices.HostServices.Start();

            Log.LogInfo("----------------------------------------------------------");


            try
            {
                int port = Constants.DefaultPort;

                if (File.Exists(Constants.NodeConfigFileName))
                {
                    try
                    {
                        var nodeConfig = SerializationHelper.FormattedSerializer.Deserialize <NodeConfig>(new JsonTextReader(new StringReader(File.ReadAllText(Constants.NodeConfigFileName))));
                        port = nodeConfig.TcpPort;
                    }
                    catch (Exception e)
                    {
                        Log.LogError($"Error reading configuration file {Constants.NodeConfigFileName} : {e.Message}");
                    }
                }
                else
                {
                    Log.LogWarning($"Configuration file {Constants.NodeConfigFileName} not found. Using defaults");
                }
                _cacheServer = new Server.Server(new ServerConfig(), true);

                _listener            = new TcpServerChannel();
                _cacheServer.Channel = _listener;
                _listener.Init(port);
                _listener.Start();


                Log.LogInfo("Starting hosted service on port " + port);

                _cacheServer.StopRequired += (sender, args) =>
                {
                    HostServices.HostServices.Stop();
                    Stop();

                    _stopEvent.Set();
                };
                _cacheServer.Start();
            }
            catch (Exception e)
            {
                Log.LogError($"Failed to start host: {e}");

                return(false);
            }

            Log.LogInfo("Host started successfully");

            return(true);
        }
Exemplo n.º 38
0
        protected override void OnStart(string[] args)
        {
            var Configuration = Server.ServerConfiguration.LoadSetting();

            //Создаем объект и загружаем настройки из файла с конфигом
            server = new Server.Server(Configuration.IP, Configuration.PORT);
            //Запускаем сервер в отдельном потоке
            new Thread(() => server.Start()).Start();
        }
Exemplo n.º 39
0
        public void Dispose()
        {
            Client.Dispose();
            Client = null;

            if (_server != null)
            {
                _server.Stop();
                _server = null;
            }
        }
Exemplo n.º 40
0
        public void Init()
        {
            IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAdress   = iphostInfo.AddressList[0];

            // _sender = new Comm.Sender("127.0.0.1", 3000);
            _server         = new Server.Server(ipAdress);
            _timer.Elapsed += _timer_Elapsed;
            _worker.DoWork += _worker_DoWork;
            _worker.RunWorkerAsync();
            _nextState2 = ProcessState.Station_0;
        }
Exemplo n.º 41
0
        public void Init()
        {
            _serverChannel = new TcpServerChannel();

            _server = new Server.Server(new NodeConfig())
            {
                Channel = _serverChannel
            };
            _serverPort = _serverChannel.Init();
            _serverChannel.Start();
            _server.Start();
            Thread.Sleep(500); //be sure the server is started
        }
Exemplo n.º 42
0
 public Form1()
 {   //读取配置文件,生成Server对象
     Terminal.OnNewMessagePrint += print;
     myServer = new Server.Server(
         ConfigurationManager.AppSettings["IP"],
         int.Parse(ConfigurationManager.AppSettings["PORT"]),
         ConfigurationManager.AppSettings["SQL_USER"],
         ConfigurationManager.AppSettings["SQL_PWD"],
         ConfigurationManager.AppSettings["SQL_IP"],
         ConfigurationManager.AppSettings["SQL_DATABASE"],
         ConfigurationManager.AppSettings["DATABASE_TYPE"]);
     InitializeComponent();
 }
Exemplo n.º 43
0
        public void Init()
        {
            _serverChannel1 = new TcpServerChannel();
            _server1        = new Server.Server(new NodeConfig {
                DataPath = "server1"
            })
            {
                Channel = _serverChannel1
            };
            _serverPort1 = _serverChannel1.Init();
            _serverChannel1.Start();
            _server1.Start();

            _serverChannel2 = new TcpServerChannel();
            _server2        = new Server.Server(new NodeConfig {
                DataPath = "server2"
            })
            {
                Channel = _serverChannel2
            };
            _serverPort2 = _serverChannel2.Init();
            _serverChannel2.Start();
            _server2.Start();


            Thread.Sleep(500); //be sure the server nodes are started

            _client1 = new DataClient
            {
                Channel     = new TcpClientChannel(new TcpClientPool(4, 1, "localhost", _serverPort1)),
                ShardIndex  = 0,
                ShardsCount = 2
            };

            _client2 = new DataClient
            {
                Channel     = new TcpClientChannel(new TcpClientPool(4, 1, "localhost", _serverPort2)),
                ShardIndex  = 1,
                ShardsCount = 2
            };

            _aggregator = new DataAggregator {
                CacheClients = { _client1, _client2 }
            };


            _aggregator.DeclareCollection <CacheableTypeOk>();
        }
Exemplo n.º 44
0
        public void Init()
        {
            _serverChannel1 = new TcpServerChannel();
            _server1        = new Server.Server(new ServerConfig())
            {
                Channel = _serverChannel1
            };
            _serverPort1 = _serverChannel1.Init();
            _serverChannel1.Start();
            _server1.Start();

            _serverChannel2 = new TcpServerChannel();
            _server2        = new Server.Server(new ServerConfig())
            {
                Channel = _serverChannel2
            };
            _serverPort2 = _serverChannel2.Init();
            _serverChannel2.Start();
            _server2.Start();


            Thread.Sleep(500); //be sure the server nodes are started

            _client1 = new CacheClient
            {
                Channel =
                    new TcpClientChannel(new TcpClientPool(4, 1, "localhost",
                                                           _serverPort1)),
                ShardIndex  = 0,
                ShardsCount = 2
            };

            _client2 = new CacheClient
            {
                Channel =
                    new TcpClientChannel(new TcpClientPool(4, 1, "localhost",
                                                           _serverPort2)),
                ShardIndex  = 1,
                ShardsCount = 2
            };

            _aggregator = new Aggregator {
                CacheClients = { _client1, _client2 }
            };


            _aggregator.RegisterTypeIfNeeded(typeof(CacheableTypeOk));
        }
Exemplo n.º 45
0
        public void Init()
        {
            _client = new CacheClient();
            var channel = new InProcessChannel();

            _client.Channel = channel;


            _server = new Server.Server(new NodeConfig())
            {
                Channel = channel
            };
            _server.Start();

            _client.RegisterTypeIfNeeded(typeof(CacheableTypeOk));
        }
Exemplo n.º 46
0
        public void Init()
        {
            _serverChannel = new TcpServerChannel();

            _server = new Server.Server(new NodeConfig())
            {
                Channel = _serverChannel
            };
            _serverPort = _serverChannel.Init();
            _serverChannel.Start();
            _server.Start();

            _client = NewClient();


            _client.DeclareCollection <CacheableTypeOk>();
        }
Exemplo n.º 47
0
        public void Init()
        {
            _client = new DataClient();
            var channel = new InProcessChannel();

            _client.Channel = channel;


            _server = new Server.Server(new NodeConfig())
            {
                Channel = channel
            };
            _server.Start();

            _client.DeclareCollection <CacheableTypeOk>();
            _client.DeclareCollection <Trade>();
        }
Exemplo n.º 48
0
        public void Init()
        {
            _serverChannel = new TcpServerChannel();

            _server = new Server.Server(new NodeConfig())
            {
                Channel = _serverChannel
            };
            _serverPort = _serverChannel.Init();
            _serverChannel.Start();
            _server.Start();

            Thread.Sleep(500); //be sure the server is started

            _client = NewClient();


            _client.RegisterTypeIfNeeded(typeof(CacheableTypeOk));
        }
 static void Main(string[] args)
 {
     Server s = new Server();
     s.Run();
 }
Exemplo n.º 50
0
 public Form1()
 {
     Terminal.OnNewMessagePrint += print;
     myServer = new Server.Server("127.0.0.1", 9840, "sa", "1213141516", "127.0.0.1", "NCDB");
     InitializeComponent();
 }
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting programm...");
            Console.Title = "Chat: Server";

            Server.Server server = new Server.Server();
            Console.CancelKeyPress += (a, b) => server.StopServer();

            string ip, tmp = null;
            ushort port;

            while (true)
            {
                Console.Write("Input ip, or [Enter] for {0}: ", Server.Server.defaultIp);
                tmp = Console.ReadLine();
                if (tmp.Length == 0)
                {
                    tmp = Server.Server.defaultIp;
                }
                if (!IPAddress.TryParse(tmp, out IPAddress tmpIp))
                {
                    ConsoleColor prev = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: Cant parse ip!");
                    Console.ForegroundColor = prev;
                }
                else
                {
                    break;
                }
            }
            ip = tmp;

            while (true)
            {
                Console.Write("Input port, or [Enter] for {0}: ", Server.Server.defaultPort);
                tmp = Console.ReadLine();
                if (tmp.Length == 0)
                {
                    tmp = Server.Server.defaultPort.ToString();
                }
                if (!ushort.TryParse(tmp, out port))
                {
                    ConsoleColor prev = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: Wrong port!");
                    Console.ForegroundColor = prev;
                }
                else
                {
                    break;
                }
            }

            Console.WriteLine("Setting Connection...");
            server.SetConnection(ip, port);
            Console.WriteLine("Starting Server...");
            server.StartServer();

            Console.WriteLine("Server started");
            Console.WriteLine("Type \"Send [Message]\" to send smth to all users");
            Console.WriteLine("Type \"Stop\" to kick all users");
            Console.WriteLine("Type \"Exit\" or CTRL+C to shutdown server");

            bool   isRunning = true;
            string message, sub;

            string[] split;

            while (isRunning)
            {
                message = Console.ReadLine();
                split   = message.Split(' ');
                sub     = split[0].Trim().ToLower();
                if (sub == "send")
                {
                    server.SendEveryoneMessage(message.Replace(split[0], "").Trim());
                }
                else if (sub == "stop")
                {
                    server.SendEveryoneMessage("All kicked!");
                    server.SendEveryoneCommand(MyProtocol.CommandType.Exit);
                }
                else if (sub == "exit")
                {
                    server.SendEveryoneMessage("Server shutdown!");
                    isRunning = false;
                }
            }

            server.StopServer();
        }
Exemplo n.º 52
0
        public Connector(ClientConfig config)
        {
            if (Client == null)
            {
                if (config.Servers == null || config.Servers.Count == 0)
                {
                    var channel = new InProcessChannel();
                    Client = new CacheClient {
                        Channel = channel
                    };

                    _server = new Server.Server(new NodeConfig {
                        IsPersistent = config.IsPersistent
                    })
                    {
                        Channel = channel
                    };

                    _server.Start();
                }
                else if (config.Servers.Count == 1)
                {
                    var serverCfg = config.Servers[0];

                    var channel = new TcpClientChannel(new TcpClientPool(4, 1, serverCfg.Host, serverCfg.Port));

                    Client = new CacheClient {
                        Channel = channel
                    };
                }
                else // multiple servers
                {
                    var aggregator = new Aggregator();

                    var index = 0;
                    foreach (var serverConfig in config.Servers)
                    {
                        var channel =
                            new TcpClientChannel(new TcpClientPool(4, 1, serverConfig.Host, serverConfig.Port));

                        var client = new CacheClient
                        {
                            Channel     = channel,
                            ShardIndex  = index,
                            ShardsCount = config.Servers.Count
                        };
                        aggregator.CacheClients.Add(client);
                        index++;
                    }


                    Client = aggregator;
                }
            }


            // register types from client configuration
            foreach (var description in config.TypeDescriptions)
            {
                var type            = Type.GetType(description.Value.FullTypeName + ", " + description.Value.AssemblyName);
                var typeDescription = Client.RegisterTypeIfNeeded(type, description.Value);

                _typeDescriptions.Add(typeDescription.FullTypeName, typeDescription);
            }
        }
Exemplo n.º 53
0
 private void StartServer()
 {
     Server.Server serverListen = new Server.Server(panel1, this.IP, this.ReceivePort, this.UserId);
 }
Exemplo n.º 54
0
        public bool Start(string instance)
        {
            try
            {
                string configFile = Constants.NodeConfigFileName;

                if (instance != null)
                {
                    var baseName = configFile.Split('.').FirstOrDefault();
                    configFile = $"{baseName}_{instance}.json";
                }

                var    port       = Constants.DefaultPort;
                var    persistent = true;
                string dataPath   = null;

                if (File.Exists(configFile))
                {
                    try
                    {
                        var nodeConfig = SerializationHelper.FormattedSerializer.Deserialize <NodeConfig>(
                            new JsonTextReader(new StringReader(File.ReadAllText(configFile))));
                        port       = nodeConfig.TcpPort;
                        persistent = nodeConfig.IsPersistent;
                        dataPath   = nodeConfig.DataPath;

                        HostServices.HostServices.Start(dataPath);

                        Log.LogInfo("----------------------------------------------------------");
                        Log.LogInfo($"Reading configuration file {configFile} ");
                    }
                    catch (Exception e)
                    {
                        Log.LogError($"Error reading configuration file {configFile} : {e.Message}");
                    }
                }
                else
                {
                    HostServices.HostServices.Start(dataPath);
                    Log.LogWarning($"Configuration file {configFile} not found. Using defaults");
                }


                _cacheServer = new Server.Server(new ServerConfig(), persistent, dataPath);

                _listener            = new TcpServerChannel();
                _cacheServer.Channel = _listener;
                _listener.Init(port);
                _listener.Start();

                var fullDataPath = Path.GetFullPath(dataPath ?? Constants.DataPath);

                var persistentDescription = persistent ? fullDataPath: " NO";

                Console.Title = $"Cachalot Core on port {port} persistent = {persistentDescription}";

                Log.LogInfo($"Starting hosted service on port {port} persistent = {persistentDescription}");

                _cacheServer.StopRequired += (sender, args) =>
                {
                    HostServices.HostServices.Stop();
                    Stop();

                    _stopEvent.Set();
                };
                _cacheServer.Start();
            }
            catch (Exception e)
            {
                Log.LogError($"Failed to start host: {e}");

                return(false);
            }

            Log.LogInfo("Host started successfully");

            return(true);
        }
Exemplo n.º 55
0
 public void Setup()
 {
     myServer = new Server.Server();
 }
Exemplo n.º 56
0
 public Client(TcpClient tcpClient, int num, Server serv)
 {
     client = tcpClient;
     numb   = num;
     server = serv;
 }
Exemplo n.º 57
0
        public void CreateMeeting(string coordinatorUser, RemotingAddress coordinatorRA, string topic,
                                  uint minAttendees, List <Slot> slots, List <string> invitees)
        {
            Server.freezeHandle.WaitOne(); // For Freeze command
            this.Delay();                  // For induced delay

            #region Validate arguments (topic exists, locations exist, invitees exist...)

            if (topic == "")
            {
                throw new ApplicationException("Must add a topic!");
            }
            if (coordinatorUser == "")
            {
                throw new ApplicationException("You do not have a username!");
            }
            if (coordinatorRA == null)
            {
                throw new ApplicationException("You did not provide a Remoting Address!");
            }
            if (minAttendees == 0)
            {
                throw new ApplicationException("Minimum attendees must be higher than 0!");
            }
            if (slots.Count == 0)
            {
                throw new ApplicationException("Must add slots to the meeting!");
            }

            // Find repeated slots
            var myListSlots    = new List <Slot>();
            var duplicateSlots = new List <Slot>();

            foreach (var s in slots)
            {
                if (!myListSlots.Contains(s))
                {
                    myListSlots.Add(s);
                }
                else
                {
                    duplicateSlots.Add(s);
                }
            }

            if (duplicateSlots.Count > 0)
            {
                throw new ApplicationException("You have repeated slots.");
            }

            // Find repeated invitees
            var myListInvitees    = new List <string>();
            var duplicateInvitees = new List <string>();

            foreach (var s in invitees)
            {
                if (!myListInvitees.Contains(s))
                {
                    myListInvitees.Add(s);
                }
                else
                {
                    duplicateInvitees.Add(s);
                }
            }

            if (duplicateInvitees.Count > 0)
            {
                throw new ApplicationException("You have repeated invitees.");
            }

            // Check if all invitees exist
            foreach (string invitee in invitees)
            {
                if (Server.clients.Where(i => i.Username == invitee).Count() == 0)
                {
                    throw new ApplicationException($"Invitee '{invitee}' does not exist or is not connected.");
                }
            }

            // Check if locations exist
            foreach (Slot s in slots)
            {
                if (!Server.locationRooms.ContainsKey(s.location))
                {
                    throw new ApplicationException($"Location '{s.location}' does not exist in the server.");
                }
            }

            // Check if a meeting with this topic does not exist already
            foreach (MeetingProposal mp2 in Server.meetingPropList)
            {
                if (mp2.Topic == topic)
                {
                    throw new ApplicationException("A meeting with this topic already exists.");
                }
            }

            #endregion

            MeetingProposal mp = new MeetingProposal(coordinatorUser, coordinatorRA, topic, minAttendees, slots, invitees);

            Server.meetingPropList.Add(mp);

            //Send new meetingToAllOtherServers
            Thread threadS = new Thread(() => Server.InformAllServersOfNewMeeting(mp));
            threadS.Start();

            //Inforam all clients
            Thread thread = new Thread(() => Server.InformClientsOfNewMeeting(mp));
            thread.Start();

            Console.WriteLine("[Server] Created meeting:" +
                              "\n\tTopic: " + topic +
                              "\n\tCoordinator: " + coordinatorUser +
                              "\n\tCoordinator URL: " + coordinatorRA +
                              "\n\tMinimum attendees: " + minAttendees);


            Console.WriteLine("[SERVER]: " + Server.serverID + " MeetingsList: " + Server.meetingPropList.Count);
        }
Exemplo n.º 58
0
        public void CloseMeeting(string topic, string coordinatorUsername)
        {
            Server.freezeHandle.WaitOne(); // For Freeze command
            this.Delay();                  // For induced delay

            #region Validate arguments

            if (topic == null || topic == "")
            {
                throw new ApplicationException("Topic cannot be empty!");
            }
            else if (coordinatorUsername == null || coordinatorUsername == "")
            {
                throw new ApplicationException("You don't have a username!");
            }
            else if (Server.meetingPropList.Where(mp => mp.Topic == topic).Count() == 0)
            {
                throw new ApplicationException("Topic does not exist!");
            }
            else if (Server.clients.Where(c => c.Username == coordinatorUsername).Count() == 0)
            {
                throw new ApplicationException("You are not registered in the server!");
            }

            #endregion

            foreach (MeetingProposal mp in Server.meetingPropList)
            {
                //Closing wanted meeting and client closing is coordinator and meeting is not yet closed
                if (mp.Topic == topic && mp.CoordinatorUsername == coordinatorUsername)
                {
                    //Causal and Total Order Check if object is not locked (Mutex)
                    lock (mp.SyncLock)
                    {
                        if (mp.Status == MeetingProposal.StatusEnum.Closed)
                        {
                            throw new ApplicationException("This meeting is already closed!");
                        }
                        else if (mp.Status == MeetingProposal.StatusEnum.Cancelled)
                        {
                            throw new ApplicationException("This meeting is cancelled!");
                        }
                        else if (mp.CoordinatorUsername != coordinatorUsername)
                        {
                            throw new ApplicationException("You are not the coordinator of this meeting!");
                        }
                        else if (mp.ClientsJoined == null || mp.ClientsJoined.Count < mp.MinAttendees)
                        {
                            int numJoinedClients = (mp.ClientsJoined != null ? mp.ClientsJoined.Count : 0);

                            throw new ApplicationException($"Min. attendees is {mp.MinAttendees}, but only " +
                                                           $"{numJoinedClients} have joined so far.");
                        }

                        //Get slot that maximizes participant count
                        uint nClients, maxClients = 0;
                        Slot maxClientsSlot = Slot.FromString("empty,2000-1-1");
                        Room maxGlobalCapacityRoom = new Room("empty", 0), maxLocalCapacityRoom;
                        foreach (Slot slot in mp.ClientPerSlot.Keys)
                        {
                            //Skip room search if
                            if (mp.ClientPerSlot[slot].Count() < maxClients)
                            {
                                continue;
                            }

                            //Get max capacity room that is available on slot location
                            if (Server.locationRooms[slot.location].Count() > 0)
                            {
                                //Get max capacity room that is available
                                maxLocalCapacityRoom = new Room("empty", 0);
                                foreach (Room room in Server.locationRooms[slot.location])
                                {
                                    if (!room.bookedDates.Contains(slot.date) && room.Capacity >= maxLocalCapacityRoom.Capacity)
                                    {
                                        maxLocalCapacityRoom = room;
                                    }
                                }

                                //Ignore this slot since no room is available
                                if (maxLocalCapacityRoom.Capacity == 0)
                                {
                                    continue;
                                }

                                //Set nClients as number of possible participants in this location
                                if ((uint)mp.ClientPerSlot[slot].Count() > maxLocalCapacityRoom.Capacity)
                                {
                                    nClients = maxLocalCapacityRoom.Capacity;
                                }
                                else
                                {
                                    nClients = (uint)mp.ClientPerSlot[slot].Count();
                                }

                                if (nClients > maxClients)
                                {
                                    //Set max participant number, slot and room
                                    maxClients            = nClients;
                                    maxClientsSlot        = slot;
                                    maxGlobalCapacityRoom = maxLocalCapacityRoom;
                                }
                            }
                        }

                        //no valid slot was found, clients want slots with no room available
                        if (maxClients == 0)
                        {
                            mp.Status = MeetingProposal.StatusEnum.Cancelled;
                            Console.WriteLine("Meeting Cancelled.");
                            throw new ApplicationException("No room is available, Meeting was cancelled.");
                        }

                        //Booking, updating values in meeting
                        maxGlobalCapacityRoom.bookedDates.Add(maxClientsSlot.date);
                        mp.BookedSlot = maxClientsSlot;
                        mp.BookedRoom = maxGlobalCapacityRoom;
                        mp.Status     = MeetingProposal.StatusEnum.Closed;

                        //Only add clients to meeting up to max room size
                        uint del = maxClients;
                        foreach (string clientName in mp.ClientPerSlot[maxClientsSlot])
                        {
                            if (del-- == 0)
                            {
                                break;
                            }
                            mp.ClientsAccepted[clientName] = mp.ClientsJoined[clientName];
                        }

                        //Inform all replicas of meeting state
                        Thread threadS = new Thread(() => Server.InformAllServersOfMeetingState(mp));
                        threadS.Start();

                        //Inforam all clients
                        Thread thread = new Thread(() => Server.InformAllClientsOfMeetingState(mp));
                        thread.Start();

                        Console.WriteLine("Meeting Booked with: " + mp.ClientsAccepted.Keys.Count +
                                          " Clients, in Slot: " + mp.BookedSlot.location +
                                          " " + mp.BookedSlot.date + " " +
                                          " and in Room: " + mp.BookedRoom.Name);
                    }
                }
            }
        }
Exemplo n.º 59
0
        public bool Start(HostControl hostControl)
        {
            HostServices.HostServices.Start();

            Log.LogInfo("----------------------------------------------------------");


            try
            {
                var nodeConfig = new NodeConfig
                {
                    TcpPort      = Constants.DefaultPort,
                    IsPersistent = true
                };

                if (File.Exists(Constants.NodeConfigFileName))
                {
                    try
                    {
                        var configFromFile = SerializationHelper.FormattedSerializer.Deserialize <NodeConfig>(
                            new JsonTextReader(new StringReader(File.ReadAllText(Constants.NodeConfigFileName))));

                        nodeConfig = configFromFile;
                    }
                    catch (Exception e)
                    {
                        Log.LogError($"Error reading configuration file {Constants.NodeConfigFileName} : {e.Message}");
                    }
                }
                else
                {
                    Log.LogWarning($"Configuration file {Constants.NodeConfigFileName} not found. Using defaults");
                }

                _cacheServer = new Server.Server(nodeConfig);

                _listener            = new TcpServerChannel();
                _cacheServer.Channel = _listener;
                _listener.Init(nodeConfig.TcpPort);
                _listener.Start();

                var fullDataPath = Path.GetFullPath(nodeConfig.DataPath ?? Constants.DataPath);

                var persistentDescription = nodeConfig.IsPersistent ? fullDataPath : " NO";

                Log.LogInfo(
                    $"Starting Cachalot server on port {nodeConfig.TcpPort}  persistent {persistentDescription}");

                Console.Title = $"Cachalot server on port {nodeConfig.TcpPort} persistent = {persistentDescription}";


                _cacheServer.Start();
            }
            catch (Exception e)
            {
                Log.LogError($"Failed to start host: {e}");

                return(false);
            }

            Log.LogInfo("Host started successfully");

            return(true);
        }
Exemplo n.º 60
0
        public void JoinMeeting(string topic, string clientName,
                                RemotingAddress clientRA, List <Slot> slots)
        {
            Server.freezeHandle.WaitOne(); // For Freeze command
            this.Delay();                  // For induced delay



            #region Validate arguments (topic exists, locations exist...)

            if (topic == "")
            {
                throw new ApplicationException("Must select a topic!");
            }
            if (clientName == "")
            {
                throw new ApplicationException("You do not have a username!");
            }
            if (clientRA == null)
            {
                throw new ApplicationException("You did not provide a Remoting Address!");
            }
            if (slots.Count == 0)
            {
                throw new ApplicationException("Must select slots on which you are available.");
            }

            // Check if a meeting with this topic exists
            if (Server.meetingPropList.Where(mp => mp.Topic == topic).Count() == 0)
            {
                throw new ApplicationException($"There is no meeting with topic '{topic}'.");
            }

            // Find repeated slots
            var myListSlots    = new List <Slot>();
            var duplicateSlots = new List <Slot>();

            foreach (var s in slots)
            {
                if (!myListSlots.Contains(s))
                {
                    myListSlots.Add(s);
                }
                else
                {
                    duplicateSlots.Add(s);
                }
            }

            if (duplicateSlots.Count > 0)
            {
                throw new ApplicationException("You have repeated slots.");
            }

            // Check if locations exist
            foreach (Slot s in slots)
            {
                if (!Server.locationRooms.ContainsKey(s.location))
                {
                    throw new ApplicationException($"Location '{s.location}' does not exist in the server.");
                }
            }

            #endregion



            foreach (MeetingProposal mp in Server.meetingPropList)
            {
                if (mp.Topic == topic)
                {
                    //Causal and Total Order Check if object is not locked (Mutex)
                    lock (mp.SyncLock)
                    {
                        if (mp.Status == MeetingProposal.StatusEnum.Closed)
                        {
                            throw new ApplicationException($"Meeting '{topic}' is closed.");
                        }
                        else if (mp.Status == MeetingProposal.StatusEnum.Cancelled)
                        {
                            throw new ApplicationException($"Meeting '{topic}' is cancelled.");
                        }
                        else if (mp.ClientsJoined.Keys.Contains(clientName))
                        {
                            throw new ApplicationException($"You have already joined meeting '{topic}'.");
                        }
                        else if (mp.Invitees.Count > 0 &&
                                 mp.CoordinatorUsername != clientName &&
                                 !mp.Invitees.Contains(clientName))
                        {
                            throw new ApplicationException($"You have not been invited for meeting '{topic}'!");
                        }

                        foreach (Slot s in slots)
                        {
                            if (!mp.Slots.Contains(s))
                            {
                                throw new ApplicationException($"Slot '{s.ToString()}' does not exist in this meeting.");
                            }
                        }

                        mp.AddClientToMeeting(clientName, clientRA, slots);

                        //Inform server replicas that new client joined meeting
                        Thread threadS = new Thread(() => Server.InformAllServersOfJoinedMeeting(mp, clientName, clientRA, slots));
                        threadS.Start();

                        //Inform all clients
                        Thread thread = new Thread(() => Server.InformAllClientsOfJoinedMeeting(mp, clientName));
                        thread.Start();
                    }
                }
            }
        }