//assuming this SA is a manager it will broadcast the simulation data needed to connect to a simulation
        public void broadCastNewSimulation(object source, ElapsedEventArgs e)
        {
            //build XML sim setup message
            XMLSimSetupNotification setup = new XMLSimSetupNotification();
            setup.SimulationId = _appConfig.SIM_ID;
            setup.SimulationName = _appConfig.SIM_NAME;
            setup.ManagerIp = _appConfig.LOCAL_IP_ADDRESS;
            setup.ManagerPort = SimulationRunningConfig.TCP_SIMULATION_APP_PORT;
            setup.ManagerId = _appConfig.APP_ID;
            setup.Secure = false;
            //setup.Password = "******"
            setup.SimulationDescription = _appConfig.SIM_DESCRIPTION;

            //wrap XML message with DEM header and send out
            MessageWrapper wrap = new MessageWrapper();
            wrap.ApplicationId = _appConfig.APP_ID;
            wrap.ApplicationRole = _appConfig.APP_ROLE;
            wrap.MessageType = MessageBase.MESSAGE_SIM_SETUP;
            wrap.Message = setup;

            //setup.printToConsole();

            NetworkConnection netPipe = new NetworkConnection(_appConfig);
            netPipe.sendUdpBroadcast(wrap.toXmlString(), SimulationRunningConfig.UDP_NETWORK_BROADCAST_ADDRESS, SimulationRunningConfig.UDP_SIMULATION_APP_PORT);
        }
 public MessageWrapper generateMessageWrapper(string type)
 {
     MessageWrapper wrap = new MessageWrapper();
     wrap.ApplicationId = _appConfig.APP_ID;
     wrap.ApplicationRole = _appConfig.APP_ROLE;
     wrap.MessageType = type;
     return wrap;
 }
        //used to notify all simulation participants - iterates through network streams and sends to each one
        private void notifyParticipants(MessageWrapper message)
        {
            //notify each participant - threaded since we dont want to block this thread if
            //connection is hung or erroneous
            List<KeyValuePair<string, SimulationParticipant>> allParticipants = _participantList.ToList();

            //build a list of applications to update the new app that joined
            foreach (var app in allParticipants)
            {
                SimulationParticipant current = app.Value;
                if (current.SimulationApplication.ParticipantId == _simConfig.SIM_ID) //skip yourself
                    continue;

                if (!current.StatefulSocket.active()) //inactive connection...
                {
                    _participantList.Remove(current.SimulationApplication.Status="Disconnected");
                    logToConsole("Error: Participant with App Id# "+current.SimulationApplication.ParticipantId+" is disconnected");
                }

                //send the message then
                Task.Factory.StartNew(() => send(current.StatefulSocket.TcpClient,message.toXmlString()));

            }
        }
        private void handleSimServerRequests(MessageWrapper wrappedMessage, ConsoleTcpListenerArgs args)
        {
            //retreive actual message payload and handle the different message types
            switch (wrappedMessage.MessageType)
            {
                case MessageBase.MESSAGE_JOIN_REQUEST:
                    XMLSimJoinRequest message = (XMLSimJoinRequest)wrappedMessage.Message;
                    if (message.valid())
                    {
                        try
                        {
                            //accept the connection from the SA
                            XMLSimJoinAcceptance joinAccept = new XMLSimJoinAcceptance();
                            joinAccept.ParticipantId = message.ParticipantId; //echo back
                            joinAccept.ParticipantIp = message.ParticipantIp;
                            joinAccept.ElementId = SimulationManagementHelper.generateElementId();
                            joinAccept.RequestConfig = true;

                            //wrap XML message with DEM header and send out
                            MessageWrapper wrap = new MessageWrapper();
                            wrap.ApplicationId = _simConfig.APP_ID;
                            wrap.ApplicationRole = _simConfig.APP_ROLE;
                            wrap.MessageType = MessageBase.MESSAGE_JOIN_ACCEPTANCE;
                            wrap.Message = joinAccept;

                            System.Console.WriteLine("Sending: \n" + wrap.toXmlString());
                            byte[] data = Encoding.UTF8.GetBytes(wrap.toXmlString());
                            NetworkStream netstream;
                            netstream = args.Client.GetStream();
                            netstream.Write(data, 0, data.Length);

                            String incoming = String.Empty;

                            bool done = false;
                            System.Console.WriteLine("Waiting for SA ");
                            //wait for the config from the SA
                            while (!done)
                            {
                                netstream = args.Client.GetStream();
                                if (netstream.DataAvailable && netstream != null)
                                {
                                    data = new Byte[args.Client.ReceiveBufferSize];
                                    netstream.Read(data, 0, (int)args.Client.ReceiveBufferSize);
                                    incoming = Encoding.UTF8.GetString(data);
                                    //System.Console.WriteLine("Received Data"+incoming);

                                    XmlSerializer deserializer = new XmlSerializer(typeof(MessageWrapper));
                                    MessageWrapper incomingWrappedMessage;

                                    //deserialize
                                    using (TextReader reader = new StringReader(incoming))
                                    {
                                        incomingWrappedMessage = (MessageWrapper)deserializer.Deserialize(reader);
                                    }

                                    //accepted to join the simulation, send config
                                    if (String.Equals(incomingWrappedMessage.MessageType, MessageBase.MESSAGE_SIM_APP_CONFIG))
                                    {
                                        System.Console.WriteLine("Received:" + incomingWrappedMessage.toXmlString());
                                        XMLSimApplication current = (XMLSimApplication)incomingWrappedMessage.Message;
                                        //add the SA to the list

                                        SimulationParticipant participant = new SimulationParticipant(current,new NetworkConnectionState(args.Client));

                                        _participantList.Add(current.ParticipantId, participant);
                                        done = true;

                                        if (_participantList.Values.Count > 1)
                                        {
                                            List<KeyValuePair<string,SimulationParticipant>> allParticipants = _participantList.ToList();
                                            List<XMLSimApplication> allApplications = new List<XMLSimApplication>();

                                            //build a list of applications to update the new app that joined
                                            foreach (var app in allParticipants)
                                            {
                                                allApplications.Add(app.Value.SimulationApplication);
                                            }

                                            XMLParticipantList updatedList = new XMLParticipantList();
                                            updatedList.Participants = allApplications;

                                            //wrap XML message with DEM header and send out
                                            wrap = new MessageWrapper();
                                            wrap.ApplicationId = _simConfig.APP_ID;
                                            wrap.ApplicationRole = _simConfig.APP_ROLE;
                                            wrap.MessageType = MessageBase.MESSAGE_UPDATE_PARTICPANT_LIST;
                                            wrap.Message = updatedList;

                                            //notifyParticipants(wrap);//tell everybody
                                        }
                                    }
                                }

                            }//end while

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                        finally
                        {
                            args.Stream.Close();
                            args.Client.Close();
                        }
                    }
                    break;
            }
        }
        private void requestJoinSimulation(XMLSimSetupNotification simulation)
        {
            XMLSimJoinRequest joinRequest = new XMLSimJoinRequest();
            joinRequest.ParticipantId = _appConfig.APP_ID;
            joinRequest.ParticipantIp = _appConfig.LOCAL_IP_ADDRESS;

            //wrap XML message with Communications header and send out
            MessageWrapper wrap = new MessageWrapper();
            wrap.ApplicationId = _appConfig.APP_ID;
            wrap.ApplicationRole = _appConfig.APP_ROLE;
            wrap.MessageType = MessageBase.MESSAGE_JOIN_REQUEST;
            wrap.Message = joinRequest;

            System.Console.WriteLine("Sending: " + wrap.toXmlString());

            NetworkConnection netPipe = new NetworkConnection(_appConfig);
            netPipe.sendTcpDataConnectionRequest(wrap.toXmlString(), simulation.ManagerIp, simulation.ManagerPort);
        }