Example #1
0
        public void GetGoalDirectionDoesNotReturnOppositeDirection()
        {
            int shortTime = 4;
            AgentConfiguration agentConfiguration = new AgentConfiguration();

            agentConfiguration.TeamID = "Red";
            agentConfiguration.CsIP   = "127.0.0.1";
            agentConfiguration.CsPort = 54321;
            Agent.Agent agentRed  = new Agent.Agent(agentConfiguration);
            var         teamMates = new int[3] {
                2, 3, 4
            };
            var enemiesIds = new int[3] {
                5, 7, 6
            };

            startGamePayload = new StartGamePayload(1, teamMates, 1, enemiesIds, TeamId.Red, new Point(5, 5), 1, 3, 3, 4, 4, new System.Collections.Generic.Dictionary <ActionType, TimeSpan>(), 0.5f, new Point(0, 0));
            agentRed.StartGameComponent.Initialize(startGamePayload);
            Assert.AreNotEqual(Common.GetGoalDirection(agentRed, shortTime, out _), Direction.South);
            agentConfiguration.TeamID = "Blue";
            Agent.Agent agentBlue = new Agent.Agent(agentConfiguration);
            startGamePayload = new StartGamePayload(1, teamMates, 1, enemiesIds, TeamId.Blue, new Point(5, 5), 1, 3, 3, 4, 4, new System.Collections.Generic.Dictionary <ActionType, TimeSpan>(), 0.5f, new Point(0, 0));
            agentBlue.StartGameComponent.Initialize(startGamePayload);
            Assert.AreNotEqual(Common.GetGoalDirection(agentBlue, shortTime, out _), Direction.North);
        }
        public void TestSendingGameJoin()
        {
            File.WriteAllText("TMPpath.txt",
                              "{\"CsIP\": \"127.0.0.1\"," +
                              "\"CsPort\": 8080," +
                              "\"teamID\": \"red\"," +
                              "\"strategy\": 1}");
            string[] args = new string[1] {
                "./TMPpath.txt"
            };

            AgentConfiguration configuration = AgentConfiguration.ReadConfiguration(args);

            TcpListener serverSideListener = new TcpListener(IPAddress.Any, configuration.CsPort);

            serverSideListener.Start();
            TcpClient serverSide = null;
            var       task       = new Task(() => serverSide = serverSideListener.AcceptTcpClient());

            task.Start();

            Agent.Agent agent = new Agent.Agent(configuration);
            agent.StartListening();

            task.Wait();
            serverSideListener.Stop();
            IMessageSenderReceiver senderReceiver = new StreamMessageSenderReceiver(serverSide.GetStream(), new Parser());

            senderReceiver.StartReceiving(message =>
            {
                Assert.AreEqual(message.MessageId, MessageType.JoinGameRequest);
            });
        }
Example #3
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(txtHighPrice.Text) >= Convert.ToInt32(txtLowerPrice.Text))
            {
                //SqlConnection con = new SqlConnection(conn);
                //SqlCommand cmd = new SqlCommand("Insert into BuyForMePreference values(@uid,@ubrand,@ucolor,@ulowprice,@uhighprice)", con);
                //cmd.Parameters.AddWithValue("@uid", (string)Session["uid"]);
                //cmd.Parameters.AddWithValue("@ubrand", ddlBrand.Text.ToLower());
                //cmd.Parameters.AddWithValue("@ucolor", ddlColor.Text.ToLower());
                //cmd.Parameters.AddWithValue("@ulowprice", txtLowerPrice.Text);
                //cmd.Parameters.AddWithValue("@uhighprice", txtHighPrice.Text);
                //con.Open();
                //cmd.ExecuteNonQuery();
                //con.Close();
                //ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('')", true);

                //Changes to make use of agent
                Agent.Agent a           = new Agent.Agent();
                string      agentConfig = ConfigurationManager.AppSettings["agentVal"];

                int redirect = 0;

                if (agentConfig.ToUpper() == "X")
                {
                    redirect = a.AgentX(ddlBrand.Text, ddlColor.Text, txtLowerPrice.Text, txtHighPrice.Text, ddlCategory.Text, conn, (string)Session["uid"]);
                }
                if (agentConfig.ToUpper() == "Y")
                {
                    redirect = a.AgentY(ddlBrand.Text, ddlColor.Text, txtLowerPrice.Text, txtHighPrice.Text, ddlCategory.Text, conn, (string)Session["uid"]);
                }
                if (agentConfig.ToUpper() == "Z")
                {
                    redirect = a.AgentZ(ddlBrand.Text, ddlColor.Text, txtLowerPrice.Text, txtHighPrice.Text, ddlCategory.Text, conn, (string)Session["uid"]);
                }

                if (agentConfig.ToUpper() == "X" || agentConfig.ToUpper() == "Y" || agentConfig.ToUpper() == "Z")
                {
                    if (redirect == 1)
                    {
                        Response.Redirect("Cart.aspx?msg=added");
                    }
                    else if (redirect == 0)
                    {
                        Response.Redirect("BuyPreference.aspx?msg=noData");
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('Incorrect agent, set appropriate agent')", true);
                }

                //randomProductsForUserPref(ddlBrand.Text, ddlColor.Text, txtLowerPrice.Text, txtHighPrice.Text, ddlCategory.Text);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('Higher range cannot be less than lower range')", true);
            }
        }
Example #4
0
        private Agent.Agent GetInitializedAgent(AgentConfiguration config)
        {
            agent = new Agent.Agent(config);

            var startGamePayload = GetDefaultStartGamePayload();

            agent.StartGameComponent.Initialize(startGamePayload);
            return(agent);
        }
Example #5
0
        public void AcceptMessage_ShouldNotJoinWnehRejected()
        {
            var config = AgentConfiguration.GetDefault();

            agent            = new Agent.Agent(config);
            agent.AgentState = AgentState.WaitingForJoin;
            agent.AcceptMessage(GetBaseMessage(new JoinResponse(false, 1), 1));
            Assert.AreEqual(agent.AgentState, AgentState.WaitingForJoin);
        }
Example #6
0
        public void AcceptMessage_ShouldJoinWhenAccepted()
        {
            var config = AgentConfiguration.GetDefault();

            agent            = new Agent.Agent(config);
            agent.AgentState = AgentState.WaitingForJoin;
            agent.AcceptMessage(GetBaseMessage(new JoinResponse(true, 1), 1));
            Assert.AreEqual(agent.AgentState, AgentState.WaitingForStart);
        }
Example #7
0
        public static List <Agent.Agent> CreateAgents(int agentsInTeam)
        {
            var agents = new List <Agent.Agent>();

            for (int i = 0; i < agentsInTeam * 2; i++)
            {
                var agent = new Agent.Agent(new AgentConfiguration
                {
                    CsIP   = "127.0.0.1",
                    CsPort = 54321,
                    TeamID = i < agentsInTeam ? "red" : "blue",
                });

                agents.Add(agent);
            }

            return(agents);
        }
Example #8
0
        public static void RunAgent(Agent.Agent agent, int agentSleepMs)
        {
            agent.ConnectToCommunicationServer();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            ActionResult actionResult = ActionResult.Continue;

            while (actionResult == ActionResult.Continue)
            {
                stopwatch.Stop();
                var timeElapsed = stopwatch.Elapsed.TotalSeconds;
                stopwatch.Reset();
                stopwatch.Start();

                actionResult = agent.Update(timeElapsed);
                Thread.Sleep(agentSleepMs);
            }

            agent.OnDestroy();
        }
Example #9
0
		static void Main( string[] args )
		{
            // Read args
            ParseArgs(args);

            // Start up the GUI thread
            InitGUIThread();

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..." );
			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service" );

			// Register the local agent singleton
			RemotingConfiguration.RegisterWellKnownServiceType( typeof( Agent ), "SwarmAgent", WellKnownObjectMode.Singleton );

            AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels" );

			// We're going to have two channels for the Agent: one for the actual Agent
			// application (IPC with infinite timeout) and one for all other remoting
			// traffic (TCP with infinite timeout that we monitor for drops)
			IpcChannel AgentIPCChannel = null;
            TcpChannel AgentTCPChannel = null;
            while( ( Ticking == true ) &&
				   ( ( AgentIPCChannel == null ) ||
				     ( AgentTCPChannel == null ) ) )
			{
				try
				{
					if( AgentIPCChannel == null )
					{
						// Register the IPC connection to the local agent
						string IPCChannelPortName = String.Format( "127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort );
						AgentIPCChannel = new IpcChannel( IPCChannelPortName );
						ChannelServices.RegisterChannel( AgentIPCChannel, false );
					}

					if( AgentTCPChannel == null )
					{
						// Register the TCP connection to the local agent
						AgentTCPChannel = new TcpChannel( Properties.Settings.Default.AgentRemotingPort );
						ChannelServices.RegisterChannel( AgentTCPChannel, false );
					}
				}
				catch( Exception )
				{
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running." );
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of" );
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them." );
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again..." );
					Thread.Sleep( 3000 );
				}
			}

			// if we're still ticking, we should have both of our channels initialized
			if( Ticking )
			{
				Debug.Assert( AgentIPCChannel != null );
				Debug.Assert( AgentTCPChannel != null );
			}
			else
			{
				// Otherwise, we can simply return to exit
				return;
			}

			// Get the agent interface object using the IPC channel
			string LocalAgentURL = String.Format( "ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
			LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

			AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent" );
            
            // Init the local agent object (if this is the first call to it, it will be created now)
			bool AgentInitializedSuccessfully = false;
			try
			{
				AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
			}
			catch( Exception Ex )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..." );
				AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString() );

				// Try again with the TCP channel, which is slower but should work
				LocalAgentURL = String.Format( "tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() );
				LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL );

				try
				{
					AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id );
					if( AgentInitializedSuccessfully )
					{
						AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!" );
					}
				}
				catch( Exception Ex2 )
				{
					AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error." );
					AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString() );

					ChannelServices.UnregisterChannel( AgentTCPChannel );
					ChannelServices.UnregisterChannel( AgentIPCChannel );
					return;
				}
			}

			// Only continue if we have a fully initialized agent
			if( ( LocalAgent != null ) && AgentInitializedSuccessfully )
			{
				AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running" );
                
                // Loop until a quit/restart event has been requested
				while( !LocalAgent.ShuttingDown() )
				{
					try
					{
						// If we've stopped ticking, notify the agent that we want to shutdown
						if( !Ticking )
						{
							LocalAgent.RequestShutdown();
						}

						// Maintain the agent itself
						LocalAgent.MaintainAgent();

						// Maintain any running active connections
						LocalAgent.MaintainConnections();

						// Maintain the Agent's cache
						if( CacheRelocationRequested )
						{
							LocalAgent.RequestCacheRelocation();
							CacheRelocationRequested = false;
						}
						if( CacheClearRequested )
						{
							LocalAgent.RequestCacheClear();
							CacheClearRequested = false;
						}
						if( CacheValidateRequested )
						{
							LocalAgent.RequestCacheValidate();
							CacheValidateRequested = false;
						}
						LocalAgent.MaintainCache();

						// Maintain any running jobs
						LocalAgent.MaintainJobs();

						// If this is a deployed application which is configured to auto-update,
						// we'll check for any updates and, if there are any, request a restart
						// which will install them prior to restarting
#if !__MonoCS__
						if( ( AgentApplication.DeveloperOptions.UpdateAutomatically ) &&
							( ApplicationDeployment.IsNetworkDeployed ) &&
                            (DateTime.UtcNow > NextUpdateCheckTime))
						{
							if( CheckForUpdates() )
							{
								LocalAgent.RequestRestart();
							}
                            NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1);
						}
#endif
					}
					catch( Exception Ex )
					{
                        AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message );
						AgentApplication.Log( EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString() );
					}

					// Sleep for a little bit
					Thread.Sleep( 500 );
				}

				// Let the GUI destroy itself
				RequestQuit();
				
				bool AgentIsRestarting = LocalAgent.Restarting();

				// Do any required cleanup
				LocalAgent.Destroy();

				ChannelServices.UnregisterChannel( AgentTCPChannel );
				ChannelServices.UnregisterChannel( AgentIPCChannel );

				// Now that everything is shut down, restart if requested
				if( AgentIsRestarting )
				{
					ClearCache();
					InstallAllUpdates();
					Application.Restart();
				}
			}
		}
Example #10
0
		public AgentJob( Agent NewManager )
		{
			// Everything else is already initialized to defaults
			Manager = NewManager;
		}
Example #11
0
        public RemoteConnectionInterfaceWrapper( Int32 NewRemoteAgentHandle, string NewRemoteAgentName, string NewRemoteAgentIPAddress, Agent NewRemoteInterface )
        {
            RemoteAgentName = NewRemoteAgentName;
            RemoteAgentIPAddress = NewRemoteAgentIPAddress;
            RemoteAgentHandle = NewRemoteAgentHandle;
            RemoteInterface = NewRemoteInterface;

            RemoteInterfaceDropped = new ManualResetEvent( false );
            RemoteInterfaceAlive = true;
            RemoteInterfaceMonitorThread = null;
        }
Example #12
0
 public static void startAgent(Type type)
 {
     Agent a = new Agent();
     a.start(type);
 }
Example #13
0
 public void Setup()
 {
     agent                = GetDefaultAgent();
     startTime            = DateTime.Now;
     defaultConfiguration = AgentConfiguration.GetDefault();
 }
Example #14
0
 public AgentTaskState(Agent.Agent agent, int agentSleepMs)
 {
     Agent        = agent;
     AgentSleepMs = agentSleepMs;
 }
        public void TestJoinGameResponse()
        {
            GameStarted defaultGameStartedMessage = new GameStarted
            {
                AgentId   = 0,
                AlliesIds = new List <int> {
                    1
                },
                BoardSize = new BoardSize {
                    X = 10, Y = 10
                },
                EnemiesIds = new List <int> {
                    2, 3
                },
                GoalAreaSize    = 3,
                LeaderId        = 1,
                NumberOfGoals   = 3,
                NumberOfPieces  = 5,
                NumberOfPlayers = new NumberOfPlayers {
                    Allies = 2, Enemies = 2
                },
                Penalties = new Penalties
                {
                    CheckForSham        = "100",
                    DestroyPiece        = "100",
                    Discovery           = "100",
                    InformationExchange = "100",
                    Move     = "100",
                    PutPiece = "100"
                },
                Position = new Position {
                    X = 2, Y = 2
                },
                ShamPieceProbability = 0.5,
                TeamId = "red"
            };

            //gets random free port
            TcpListener serverSideListener = new TcpListener(IPAddress.Any, 0);

            serverSideListener.Start();
            int port = ((IPEndPoint)serverSideListener.LocalEndpoint).Port;

            File.WriteAllText("TMPpath.txt",
                              "{\"CsIP\": \"127.0.0.1\"," +
                              $"\"CsPort\": {port}," +
                              "\"teamID\": \"red\"," +
                              "\"strategy\": 1}");
            string[] args = new string[1] {
                "./TMPpath.txt"
            };
            AgentConfiguration configuration = AgentConfiguration.ReadConfiguration(args);

            TcpClient serverSide = null;
            var       task       = new Task(() => serverSide = serverSideListener.AcceptTcpClient());

            task.Start();

            Agent.Agent agent      = new Agent.Agent(configuration);
            var         listenTask = new Task(() => agent.StartListening());

            listenTask.Start();

            task.Wait();
            serverSideListener.Stop();
            IMessageSenderReceiver senderReceiver = new StreamMessageSenderReceiver(serverSide.GetStream(), new Parser());
            Message joinGameMessage     = null;
            Message exchangeInfoRequest = null;

            Semaphore semaphore = new Semaphore(0, 100);

            senderReceiver.StartReceiving(message =>
            {
                switch (message.MessageId)
                {
                case MessageType.JoinGameRequest:

                    senderReceiver.Send(new Message <JoinGameResponse>(new JoinGameResponse()
                    {
                        AgentID = 1, Accepted = true
                    }));
                    senderReceiver.Send(new Message <GameStarted>(defaultGameStartedMessage));
                    joinGameMessage = message;
                    break;

                default:
                    exchangeInfoRequest = message;
                    semaphore.Release();
                    break;
                }
            });

            semaphore.WaitOne();
            Assert.AreEqual(joinGameMessage.MessageId, MessageType.JoinGameRequest);
            Assert.AreEqual(exchangeInfoRequest.MessageId, MessageType.ExchangeInformationRequest);
        }