Пример #1
0
 public FindNextSystemCommand(ICommunicator communicator, INavigator navigator, IGalaxyMap galaxyMap, FindNextSystemPhrases phrases)
 {
     _communicator = communicator;
     _navigator    = navigator;
     _galaxyMap    = galaxyMap;
     _phraseBook   = PhraseBook.Ingest(phrases.Phrases);
 }
Пример #2
0
 /// <summary>
 /// Adds a TCPCommunicator object to _communicators list.
 /// </summary>
 /// <param name="communicator">TCPCommunicator to be added</param>
 private void AddToCommunicators(ICommunicator communicator)
 {
     lock (_communicators)
     {
         _communicators[communicator.ComminicatorId] = communicator;
     }
 }
Пример #3
0
 public AbstractLockstep(float deltaTime, ICommunicator communicator, IPhysicsManagerBase physicsManager, int syncWindow, int panicWindow, int rollbackWindow, TrueSyncEventCallback OnGameStarted, TrueSyncEventCallback OnGamePaused, TrueSyncEventCallback OnGameUnPaused, TrueSyncEventCallback OnGameEnded, TrueSyncPlayerDisconnectionCallback OnPlayerDisconnection, TrueSyncUpdateCallback OnStepUpdate, TrueSyncInputDataProvider InputDataProvider)
 {
     AbstractLockstep.instance  = this;
     this.deltaTime             = deltaTime;
     this.syncWindow            = syncWindow;
     this.panicWindow           = panicWindow;
     this.rollbackWindow        = rollbackWindow;
     this.totalWindow           = syncWindow + rollbackWindow;
     this.StepUpdate            = OnStepUpdate;
     this.OnGameStarted         = OnGameStarted;
     this.OnGamePaused          = OnGamePaused;
     this.OnGameUnPaused        = OnGameUnPaused;
     this.OnGameEnded           = OnGameEnded;
     this.OnPlayerDisconnection = OnPlayerDisconnection;
     this.InputDataProvider     = InputDataProvider;
     this.ticks                = 0;
     this.players              = new Dictionary <byte, TSPlayer>(4);
     this.activePlayers        = new List <TSPlayer>(4);
     this.auxPlayersSyncedData = new List <SyncedData>(4);
     this.auxPlayersInputData  = new List <InputDataBase>(4);
     this.communicator         = communicator;
     this.physicsManager       = physicsManager;
     this.compoundStats        = new CompoundStats();
     this.bufferSyncedInfo     = new GenericBufferWindow <SyncedInfo>(3);
     this.checksumOk           = true;
     this.simulationState      = AbstractLockstep.SimulationState.NOT_STARTED;
     this.bodiesToDestroy      = new Dictionary <int, List <IBody> >();
     this.playersDisconnect    = new Dictionary <int, List <byte> >();
     this.ReplayMode           = ReplayRecord.replayMode;
 }
 public void ProcessMessage(BotUser user, ICommunicator communicator, string message)
 {
     try
     {
         var command = _commandFactory.GetCommand(message, user);
         if (command.HasValue)
         {
             ProcessCommandMessage(user, communicator, command.Value);
         }
         else
         {
             ProcessSimpleMessage(user, communicator, message);
         }
     }
     catch (UnauthorizedException exception)
     {
         communicator.SendMessage("У вас нет прав для выполнения этой команды");
         _logger.Error(exception);
     }
     catch (InvalidOperationException e)
     {
         communicator.SendMessage(e.Message);
         _logger.Error(e);
     }
     catch (Exception e)
     {
         _logger.Error(e);
     }
 }
Пример #5
0
        public void TestCreateCommunicator()
        {
            ICommunicator communicatorInterface = Factory.CreateCommunicator(DICT, API_KEY_ID, SECRET_API_KEY);

            Assert.IsInstanceOf <Communicator>(communicatorInterface);
            Communicator communicator = (Communicator)communicatorInterface;

            Assert.AreSame(DefaultMarshaller.Instance, communicator.Marshaller);

            IConnection connection = communicator.Connection;

            Assert.True(connection is DefaultConnection);

            IAuthenticator authenticator = communicator.Authenticator;

            Assert.True(authenticator is DefaultAuthenticator);
            Assert.AreEqual(AuthorizationType.V1HMAC, GetInstanceField(typeof(DefaultAuthenticator), authenticator, "_authorizationType"));
            Assert.AreEqual(API_KEY_ID, GetInstanceField(typeof(DefaultAuthenticator), authenticator, "_apiKeyId"));
            Assert.AreEqual(SECRET_API_KEY, GetInstanceField(typeof(DefaultAuthenticator), authenticator, "_secretApiKey"));

            MetaDataProvider metaDataProvider = communicator.MetaDataProvider;

            Assert.AreEqual(typeof(MetaDataProvider), metaDataProvider.GetType());
            IEnumerable <RequestHeader> requestHeaders = metaDataProvider.ServerMetaDataHeaders;

            Assert.AreEqual(1, requestHeaders.Count());
            RequestHeader requestHeader = requestHeaders.ElementAt(0);

            Assert.AreEqual("X-GCS-ServerMetaInfo", requestHeader.Name);
        }
Пример #6
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="Communicator">Communicator used to create the message</param>
 public EmailMessage(ICommunicator Communicator)
     : base(Communicator)
 {
     Attachments       = new List <Attachment>();
     EmbeddedResources = new List <LinkedResource>();
     Priority          = MailPriority.Normal;
 }
Пример #7
0
 /// <summary>
 /// Creates a new ReceiverCommunicator object.
 /// </summary>
 /// <param name="communicator">The communicator</param>
 public ConnectedCommunicator(ICommunicator communicator)
 {
     IsSuspended                 = false;
     SuspendExpireDate           = DateTime.MinValue;
     ProcessingMessageExpireDate = DateTime.MaxValue;
     Communicator                = communicator;
 }
Пример #8
0
 static bool SendFile(ICommunicator service, string file)
 {
     long blockSize = 1024;//can be bigger
     try
     {
         FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read);//open local
         string filename = Path.GetFileName(file);
         service.OpenFileForWrite(filename);//open remote 
         int bytesRead = 0;
         while (true)
         {
             long remainder = (int)(fs.Length - fs.Position);
             if (remainder == 0)
                 break;
             long size = Math.Min(blockSize, remainder);
             byte[] block = new byte[size];
             bytesRead = fs.Read(block, 0, block.Length);
             service.WriteFileBlock(block);//write remote
         }
         fs.Close();
         service.CloseFile();//close remote
         return true;
     }
     catch (Exception ex)
     {
         Console.Write("\n  can't open {0} for writing - {1}", file, ex.Message);
         return false;
     }
 }
Пример #9
0
        /// <summary>
        /// This method is called by ProcessDataTransferMessage when a message must be sent to an adjacent server of this server.
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="senderCommunicator">Sender communicator</param>
        /// <param name="message">Message</param>
        private void SentToAdjacentServer(NGRIDRemoteApplication senderApplication, ICommunicator senderCommunicator, NGRIDDataTransferMessage message)
        {
            /* On one of these conditions, message is stored:
             * - TransmitRule = StoreAndForward
             * - (TransmitRule = StoreOnSource OR StoreOnEndPoints) AND (This server is the source server)
             */
            if (message.TransmitRule == MessageTransmitRules.StoreAndForward ||
                message.TransmitRule == MessageTransmitRules.NonPersistent)
            {
                EnqueueMessage(
                    senderApplication,
                    senderCommunicator,
                    _serverGraph.AdjacentServers[message.DestinationServerName],
                    message
                    );
            }

            /* Else, message is not stored in these conditions:
             * - TransmitRule = DirectlySend OR StoreOnDestination (this server can not be destination because message is being sent to another server right now)
             * - All Other conditions
             */
            else
            {
                SendMessageDirectly(
                    senderApplication,
                    senderCommunicator,
                    _serverGraph.AdjacentServers[message.DestinationServerName],
                    message
                    );
            }
        }
Пример #10
0
        public GameLoadCommand(ICommunicator communicator, IPlayerStatus playerStatus, GameLoadPhrases phrases)
        {
            _communicator = communicator;
            _playerStatus = playerStatus;

            _genericPhrases = PhraseBook.Ingest(phrases.Generic);
        }
Пример #11
0
 protected ApiResource(ICommunicator communicator, string clientMetaInfo, IDictionary <string, string> pathContext)
 {
     _parent         = null;
     _pathContext    = pathContext;
     _communicator   = communicator ?? throw new ArgumentException("communicator is required");
     _clientMetaInfo = clientMetaInfo;
 }
Пример #12
0
 public void ProcessMessage(string message, ICommunicator communicator)
 {
     DoAction(message, new List <ICommunicator>()
     {
         communicator
     });
 }
Пример #13
0
 protected ApiResource(ApiResource parent, IDictionary <string, string> pathContext)
 {
     _parent         = parent ?? throw new ArgumentException("parent is required");
     _pathContext    = pathContext;
     _communicator   = parent._communicator;
     _clientMetaInfo = parent._clientMetaInfo;
 }
Пример #14
0
 public MessageSender(ICommunicator communicator, ILogger <MessageSender> logger, IApplicationLifetime applicationLifetime)
 {
     _communicator      = communicator;
     _logger            = logger;
     _cancellationToken = applicationLifetime.ApplicationStopping;
     _messageTypes      = new List <ISender>();
 }
Пример #15
0
        public Bootstrapper(ICommunicator communicator, IContestEntry contestEntry)
        {
            this.communicator = communicator;
            this.contestEntry = contestEntry;

            ScanWholeContestantAssembly = false;
        }
Пример #16
0
 public PollModule(ISettingsService settings, ICommunicator communicator, IFrameworkReflector frameworkReflector, HelpBuilder helpBuilder)
 {
     _settings = settings;
     _communicator = communicator;
     _frameworkReflector = frameworkReflector;
     _helpBuilder = helpBuilder;
 }
Пример #17
0
        public static async ValueTask <ATResult <OkResult> > SendSmsAsync(
            this ICommunicator <string> comm,
            ResponseFormat responseFormat,
            PhoneNumber phoneNumber,
            string message,
            CancellationToken cancellationToken = default)
        {
            if (message.Length > 160)
            {
                throw new ArgumentOutOfRangeException($"Message exceeded maximum length of 160");
            }

            await comm.Write($"AT+CMGS=\"{phoneNumber}\"\r", cancellationToken);

            Thread.Sleep(100);
            var response = await comm.ReadSingleMessageAsync((byte)'>', cancellationToken);

            await comm.Write($"{message}\r{0x1A}");

            Thread.Sleep(2000);
            response = await comm.ReadSingleMessageAsync((byte)'\r', cancellationToken);

            var result = OkParser.TryParse(response, responseFormat, out _);

            return(default);
Пример #18
0
        private ICommunicator CreateCommunicator(CommunicatorType type, string user, string env, string application, bool isFromApplicatonProcess = false)
        {
            var           key  = string.Format(KEY_FORMAT, user, env, application, isFromApplicatonProcess ? "_App" : "");
            ICommunicator comm = null;

            switch (type)
            {
            case CommunicatorType.MappedFileType:
                comm = new MemoryMappedFileCommunicator(user, env, application, isFromApplicatonProcess);
                break;

            default:
                break;
            }
            if (comm != null)
            {
                lock (lockObj)
                {
                    commList.Add(key, comm);
                }
                comm.StartReader();
            }
            //logger.DebugFormat("CreateCommunicator, Key = {0}", key);
            return(comm);
        }
Пример #19
0
        /// <summary>
        /// Add a generic peer to the recording
        /// </summary>
        /// <param name="commLink">ICommunicator to record</param>
        /// <param name="dumpToFile">True if packets for this peer should be written to individual file</param>
        /// <param name="dumpFileExtension">Extension for the individual dump file</param>
        public bool AddPeer(ICommunicator commLink, bool dumpToFile, string dumpFileExtension = ".dump")
        {
            if (CurrentState == State.Recording)
            {
                return(false);
            }

            if (!socketListeners.ContainsKey(commLink.ID))
            {
                commLink.DataReadySyncEvent += DataReadyEventCallback;
                commLink.DataRateEvent      += OnDataRate;

                RecPeerInfo p = new RecPeerInfo()
                {
                    ID                = commLink.ID,
                    DumpToFile        = dumpToFile,
                    DumpFileExtension = dumpFileExtension,
                    commsLink         = commLink,
                    IP                = commLink.CommsUri.IP,
                    Port              = commLink.CommsUri.LocalPort
                };

                bool doneRight = socketListeners.TryAdd(commLink.ID, p) && _dataRate.TryAdd(commLink.ID, 0);
                return(doneRight);
            }

            return(false);
        }
Пример #20
0
 /// <summary>
 /// Raises CommunicatorConnected event.
 /// </summary>
 /// <param name="communicator">Communicator</param>
 protected void OnCommunicatorConnected(ICommunicator communicator)
 {
     if (CommunicatorConnected != null)
     {
         CommunicatorConnected(this, new CommunicatorConnectedEventArgs {Communicator = communicator});
     }
 }
Пример #21
0
 public FSDTargetCommand(IDetourPlanner detourPlanner, INavigator navigator, ICommunicator communicator, ILogger logger)
 {
     _detourPlanner = detourPlanner;
     _navigator     = navigator;
     _communicator  = communicator;
     _logger        = logger;
 }
Пример #22
0
 public Do Run( string input, AlchemyController controller, ICommunicator communicator )
 {
     string elementname = input.TrimStart( '*' );
     if( controller.ElementExists( elementname ) )
         controller.ForeachNonterminalElement( ( e ) => controller.ReportChangedRule( new Rule( new[] { elementname, e.Name } ) ) );
     return Do.AnotherRule;
 }
Пример #23
0
        /// <summary>
        /// Processes UpdateServerGraphMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controlMessage">The message to be processed</param>
        /// <param name="controllerMessage">NGRIDControllerMessage object that includes controlMessage</param>
        private void ProcessUpdateServerGraphMessage(ICommunicator communicator, UpdateServerGraphMessage controlMessage, NGRIDControllerMessage controllerMessage)
        {
            try
            {
                var newSettings = new NGRIDSettings(Path.Combine(GeneralHelper.GetCurrentDirectory(), "NGRIDSettings.xml"));
                //var newDesignSettings = new NGRIDDesignSettings(Path.Combine(GeneralHelper.GetCurrentDirectory(), "NGRIDSettings.design.xml"));

                //Clear existing server lists
                newSettings.Servers.Clear();
                //newDesignSettings.Servers.Clear();

                //Add servers from UpdateServerGraphMessage
                newSettings.ThisServerName = controlMessage.ServerGraph.ThisServerName;
                foreach (var server in controlMessage.ServerGraph.Servers)
                {
                    //Settings
                    newSettings.Servers.Add(
                        new ServerInfoItem
                    {
                        Name      = server.Name,
                        IpAddress = server.IpAddress,
                        Port      = server.Port,
                        Adjacents = server.Adjacents
                    });

                    /*Design settings
                     * newDesignSettings.Servers.Add(
                     *  new ServerDesignItem
                     *  {
                     *      Name = server.Name,
                     *      Location = server.Location
                     *  });*/
                }

                //Save settings
                newSettings.SaveToXml();
                //newDesignSettings.SaveToXml();
            }
            catch (Exception ex)
            {
                //Send fail message
                ReplyMessageToCommunicator(
                    communicator,
                    new OperationResultMessage {
                    Success = false, ResultMessage = ex.Message
                },
                    controllerMessage
                    );
                return;
            }

            //Send success message
            ReplyMessageToCommunicator(
                communicator,
                new OperationResultMessage {
                Success = true, ResultMessage = "Success"
            },
                controllerMessage
                );
        }
Пример #24
0
        /// <summary>
        /// Processes GetApplicationListMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessGetApplicationListMessage(ICommunicator communicator, MDSControllerMessage controllerMessage)
        {
            //Get all client applications
            var applicationList = OrganizationLayer.GetClientApplications();

            //Create ClientApplicationInfo array
            var clientApplications = new GetApplicationListResponseMessage.ClientApplicationInfo[applicationList.Length];

            for (var i = 0; i < applicationList.Length; i++)
            {
                clientApplications[i] = new GetApplicationListResponseMessage.ClientApplicationInfo
                {
                    Name = applicationList[i].Name,
                    CommunicatorCount = applicationList[i].ConnectedCommunicatorCount
                };
            }

            //Send response message
            ReplyMessageToCommunicator(
                communicator,
                new GetApplicationListResponseMessage
            {
                ClientApplications = clientApplications
            },
                controllerMessage
                );
        }
Пример #25
0
 public LocalEndPoint(ICommunicator communicator)
 {
     _communicator = communicator;
     _communicator.RegisterReceiver(this);
     _root = new RootResource();
     AddResource(new DiscoveryResource(_root));
 }
 public DeviceDetailPageModel(ICommunicator communicator, IEventAggregator eventAggregator)
 {
     _communicator       = communicator;
     _eventAggregator    = eventAggregator;
     SaveDeviceCommand   = new DelegateCommand <object, object>(OnSaveDevice);
     DeleteDeviceCommand = new DelegateCommand <object, object>(OnDeleteDevice);
 }
 protected ObjectOverviewPageModelBase(ICommunicator communicator, IEventAggregator eventAggregator)
 {
     _communicator           = communicator;
     _eventAggregator        = eventAggregator;
     NewObjectCommand        = new DelegateCommand <object, object>(OnNewObjectAsync);
     NavigateToObjectCommand = new DelegateCommand <object, object>(OnNavigateToObjectAsync);
 }
Пример #28
0
        /// <summary>
        /// Initializes the environment, configures it and initialized the Academy.
        /// </summary>
        void InitializeEnvironment()
        {
            EnableAutomaticStepping();

            var floatProperties = new FloatPropertiesChannel();

            FloatProperties = floatProperties;

            // Try to launch the communicator by using the arguments passed at launch
            var port = ReadPortFromArgs();

            if (port > 0)
            {
                Communicator = new RpcCommunicator(
                    new CommunicatorInitParameters
                {
                    port = port
                }
                    );
            }

            if (Communicator != null)
            {
                Communicator.RegisterSideChannel(new EngineConfigurationChannel());
                Communicator.RegisterSideChannel(floatProperties);
                // We try to exchange the first message with Python. If this fails, it means
                // no Python Process is ready to train the environment. In this case, the
                //environment must use Inference.
                try
                {
                    var unityRlInitParameters = Communicator.Initialize(
                        new CommunicatorInitParameters
                    {
                        version = k_ApiVersion,
                        name    = "AcademySingleton",
                    });
                    UnityEngine.Random.InitState(unityRlInitParameters.seed);
                }
                catch
                {
                    Debug.Log($"" +
                              $"Couldn't connect to trainer on port {port} using API version {k_ApiVersion}. " +
                              "Will perform inference instead."
                              );
                    Communicator = null;
                }

                if (Communicator != null)
                {
                    Communicator.QuitCommandReceived  += OnQuitCommandReceived;
                    Communicator.ResetCommandReceived += OnResetCommand;
                }
            }

            // If a communicator is enabled/provided, then we assume we are in
            // training mode. In the absence of a communicator, we assume we are
            // in inference mode.

            ResetActions();
        }
Пример #29
0
        public static async ValueTask <ATResult <PinStatusResult> > GetPinStatusAsync(
            this ICommunicator <string> comm,
            ResponseFormat responseFormat,
            CancellationToken cancellationToken = default)
        {
            await comm.Write($"AT+CPIN?\r", cancellationToken);

            var message = await comm.ReadSingleMessageAsync(Constants.BYTE_LF, cancellationToken);

            if (PinStatusParser.TryParse(message, responseFormat, out ATResult <PinStatusResult> pinResult))
            {
                message = await comm.ReadSingleMessageAsync(Constants.BYTE_LF, cancellationToken);

                if (OkParser.TryParse(message, responseFormat, out ATResult <OkResult> _))
                {
                    return(pinResult);
                }
                else if (ErrorParser.TryParse(message, responseFormat, out ATResult <ErrorResult> errorResult))
                {
                    return(ATResult.Error <PinStatusResult>(errorResult.ErrorMessage));
                }
            }
            else if (ErrorParser.TryParse(message, responseFormat, out ATResult <ErrorResult> errorResult))
            {
                return(ATResult.Error <PinStatusResult>(errorResult.ErrorMessage));
            }
            return(ATResult.Error <PinStatusResult>(Constants.PARSING_FAILED));
        }
Пример #30
0
        void _HandleConnectionBroken(ICommunicator ptr, string broken_info)
        {
            BrokenInfo info = new BrokenInfo();

            info.Commer = ptr;
            info.Info   = broken_info;

            lock (m_BrokenClient)
                m_BrokenClient.Add(info);
            //bool isclient = false;
            //int count = 0;
            //lock (m_ClientCommunicators)
            //{
            //    isclient = m_ClientCommunicators.Remove(id);
            //    count = m_ClientCommunicators.Count;
            //}

            //lock (m_ClientActiveCounter)
            //    m_ClientActiveCounter.Remove(id);

            //if (isclient)
            //{
            //    MSGTYPE command = new MSGTYPE();
            //    command.TK_CommandType = Constants.TK_CommandType.UNREGISTERCLIENT;
            //    command.SetValue("ClientID", id);
            //    command.SeqID = CommandProcessor.AllocateID();
            //    CommandProcessor.instance().DispatchCommand(command);

            //    SendLog("客户端: " + clientinfo + " 已经从" + Name + "断开.");

            //    SendLog(Name + "当前客户端的数量:" + count);
            //}
        }
Пример #31
0
        /// <summary>
        /// Shut down the Academy.
        /// </summary>
        public void Dispose()
        {
            DisableAutomaticStepping();
            // Signal to listeners that the academy is being destroyed now
            DestroyAction?.Invoke();

            Communicator?.Dispose();
            Communicator = null;

            if (m_ModelRunners != null)
            {
                foreach (var mr in m_ModelRunners)
                {
                    mr.Dispose();
                }
                m_ModelRunners = null;
            }

            // Clear out the actions so we're not keeping references to any old objects
            ResetActions();

            // TODO - Pass worker ID or some other identifier,
            // so that multiple envs won't overwrite each others stats.
            TimerStack.Instance.SaveJsonTimers();

            FloatProperties = null;
            m_Initialized   = false;

            // Reset the Lazy instance
            s_Lazy = new Lazy <Academy>(() => new Academy());
        }
Пример #32
0
        public static T MultiplyAll <T>(ICommunicator comm, T value)
            where T : ICloneable, SettableToProduct <T>
        {
            string     key = StringUtil.TypeToString(typeof(T));
            TimingInfo timingInfo;

            lock (MultiplyAllTimingInfos)
            {
                if (!MultiplyAllTimingInfos.TryGetValue(key, out timingInfo))
                {
                    timingInfo = new TimingInfo();
                    MultiplyAllTimingInfos.Add(key, timingInfo);
                }
            }
            timingInfo.watch.Start();
            var reduced = comm.Allreduce(value, (a, b) =>
            {
                T result = (T)a.Clone();
                result.SetToProduct(a, b);
                return(result);
            });

            timingInfo.watch.Stop();
            timingInfo.ItemsTransmitted++;
            return(reduced);
        }
Пример #33
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="Communicator">Communicator used to create the message</param>
 public EmailMessage(ICommunicator Communicator)
     : base(Communicator)
 {
     Attachments = new List<Attachment>();
     EmbeddedResources = new List<LinkedResource>();
     Priority = MailPriority.Normal;
 }
Пример #34
0
        public void Send(ICommunicator communicator)
        {
            //Kontakt holen (public Key des Empfaengers)
            //Message zu Xml serialisieren
            //Xml verschluesseln
            //Verschluesseltes Xml verschicken

            throw new NotImplementedException();
        }
Пример #35
0
        public void Recieve(ICommunicator communicator)
        {
            //Nach neuen Nachrichten suchen
            //Nachrichten herunterladen
            //Nachrichten entschluesseln
            //Nachrichten zurückliefern

            throw new NotImplementedException();
        }
Пример #36
0
 public async Task Start(ICommunicator communicator)
 {
     this.communicator = communicator;
     await OnStart();
     Task.Factory.StartNew(async () =>
     {
         while (true)
         {
             var message = await communicator.GetNextMessage();
             await OnMessageReceived(message.Sender, message.Content);
         }
     });
 }
        public SafeHouseUserControl(string baseUri, SafeHouseNode node, ICommunicator communicator)
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(SafeHouseUserControl_Loaded);

            _safeHouseNode = node;
            _baseUri = baseUri;
            _communicator = communicator;

            if (_safeHouseIcon == null)
            {
                string uri = String.Concat(_baseUri, "Content/", "images/", "safehouse.png");
                _safeHouseIcon = new BitmapImage(new Uri(uri));
            }
        }
        public ZombiePackUserControl(string baseUri, Node node, ICommunicator communicator)
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(HotZoneUserControl_Loaded);

            _hotZone = node;
            _baseUri = baseUri;
            _communicator = communicator;

            if (_zombiePackIcon == null)
            {
                string uri = String.Concat(_baseUri, "Content/", "images/", "zombie.png");
                _zombiePackIcon = new BitmapImage(new Uri(uri));
            }
        }
        public UserNodeUserControl(string baseUri, UserNode userNode, ICommunicator communicator)
        {
            InitializeComponent();

            _baseUri = baseUri;
            _userNode = userNode;
            _communicator = communicator;

            Loaded += new RoutedEventHandler(UserNodeUserControl_Loaded);

            if (_moveIcon == null)
            {
                string uri = String.Concat(_baseUri, "Content/", "images/", "move.png");
                _moveIcon = new BitmapImage(new Uri(uri));
            }
        }
        public HotZoneUserControl(string baseUri, HotZoneNode node, ICommunicator communicator)
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(HotZoneUserControl_Loaded);

            _hotZone = node;
            _baseUri = baseUri;
            _communicator = communicator;

            if (_hotZoneIcon == null)
            {
                string uri = String.Concat(_baseUri, "Content/", "images/", "hotzone.png");
                _hotZoneIcon = new BitmapImage(new Uri(uri));
            }

            if (_clearedHotZoneIcon == null)
            {
                string uri = String.Concat(_baseUri, "Content/", "images/", "information.png");
                _clearedHotZoneIcon = new BitmapImage(new Uri(uri));
            }
        }
        public Do Run( string input, AlchemyController controller, ICommunicator communicator )
        {
            var splitinput = input.TrimStart( ' ', '#' ).Split( ':' );
            if( splitinput.Length < 2 )
                return Do.AnotherRule;

            var ingredients = splitinput[0].Split( ',' );

            foreach( var ingredient in ingredients )
            {
                if( !controller.ElementExists( ingredient ) )
                {
                    communicator.Display( "Bad data, element named '" + ingredient + "' isnt in list of known elements. If this isnt a typo, please add element using '>element', or, if possible, add rule that creates element" );
                    return Do.AnotherRule;
                }
            }

            var rule = new Rule( ingredients );
            rule.SetResult( splitinput[1] );
            controller.ReportChangedRule( rule, true );

            return Do.AnotherRule;
        }
Пример #42
0
        /// <summary>
        /// Sends message directly to application (not stores) and waits ACK.
        /// This method adds message to queue by MDSPersistentRemoteApplicationBase.AddMessageToHeadOfQueue method
        /// and waits a signal/pulse from RemoteApplication_MessageReceived method to get ACK/Reject.
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="senderCommunicator">Sender communicator</param>
        /// <param name="destApplication">Destination application/server</param>
        /// <param name="message">Message</param>
        private void SendMessageDirectly(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSPersistentRemoteApplicationBase destApplication, MDSDataTransferMessage message)
        {
            //Create a WaitingMessage to wait and get ACK/Reject message and add it to waiting messages
            var waitingMessage = new WaitingMessage();
            lock (_waitingMessages)
            {
                _waitingMessages[message.MessageId] = waitingMessage;
            }

            try
            {
                //Add message to head of queue of remote application
                destApplication.AddMessageToHeadOfQueue(message);

                //Wait until thread is signalled by another thread to get response (Signalled by RemoteApplication_MessageReceived method)
                waitingMessage.WaitEvent.WaitOne((int) (_settings.MessageResponseTimeout*1.2));

                //Evaluate response
                if (waitingMessage.ResponseMessage.Success)
                {
                    SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Success.");
                }
                else
                {
                    SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Message is not acknowledged. Reason: " + waitingMessage.ResponseMessage.ResultText);
                }
            }
            finally
            {
                //Remove message from waiting messages
                lock (_waitingMessages)
                {
                    _waitingMessages.Remove(message.MessageId);
                }
            }
        }
Пример #43
0
        /// <summary>
        /// This method is called by ProcessDataTransferMessage when a message must be sent to a server
        /// that is not an adjacent of this server. Message is forwarded to next server.
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="senderCommunicator">Sender communicator</param>
        /// <param name="message">Message</param>
        private void SendToNextServer(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
        {
            //If there is a path from this server to destination server...
            if (_serverGraph.ThisServerNode.BestPathsToServers.ContainsKey(message.DestinationServerName))
            {
                //Find best path to destination server 
                var bestPath = _serverGraph.ThisServerNode.BestPathsToServers[message.DestinationServerName];
                //If path is regular (a path must consist of 2 nodes at least)...
                if (bestPath.Count > 1)
                {
                    //Next server
                    var nextServerName = bestPath[1].Name;

                    /* On one of these conditions, message is stored:
                     * - TransmitRule = StoreAndForward
                     * - (TransmitRule = StoreOnSource OR StoreOnEndPoints) AND (This server is the source server)
                     */
                    if (message.TransmitRule == MessageTransmitRules.StoreAndForward ||
                        message.TransmitRule == MessageTransmitRules.NonPersistent)
                    {
                        EnqueueMessage(
                            senderApplication,
                            senderCommunicator,
                            _serverGraph.AdjacentServers[nextServerName],
                            message
                            );
                    }
                    /* Else, message is not stored in these conditions:
                     * - TransmitRule = DirectlySend OR StoreOnDestination (this server can not be destination because message is being sent to another server right now)
                     * - All Other conditions
                     */
                    else
                    {
                        SendMessageDirectly(
                            senderApplication,
                            senderCommunicator,
                            _serverGraph.AdjacentServers[nextServerName],
                            message
                            );
                    }
                }
                //Server graph may be wrong (this is just for checking case, normally this situation must not become)
                else
                {
                    SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Server graph is wrong.");
                }
            }
            //No path from this server to destination server
            else
            {
                SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "There is no path from this server to destination.");
            }
        }
Пример #44
0
 /// <summary>
 /// This method is called by ProcessDataTransferMessage when a message must be sent to an adjacent server of this server.
 /// </summary>
 /// <param name="senderApplication">Sender application/server</param>
 /// <param name="senderCommunicator">Sender communicator</param>
 /// <param name="message">Message</param>
 private void SentToAdjacentServer(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
 {
     /* On one of these conditions, message is stored:
      * - TransmitRule = StoreAndForward
      * - (TransmitRule = StoreOnSource OR StoreOnEndPoints) AND (This server is the source server)
      */
     if (message.TransmitRule == MessageTransmitRules.StoreAndForward || 
         message.TransmitRule == MessageTransmitRules.NonPersistent)
     {
         EnqueueMessage(
             senderApplication,
             senderCommunicator,
             _serverGraph.AdjacentServers[message.DestinationServerName],
             message
             );
     }
     /* Else, message is not stored in these conditions:
      * - TransmitRule = DirectlySend OR StoreOnDestination (this server can not be destination because message is being sent to another server right now)
      * - All Other conditions
      */
     else
     {
         SendMessageDirectly(
             senderApplication,
             senderCommunicator,
             _serverGraph.AdjacentServers[message.DestinationServerName],
             message
             );
     }
 }
Пример #45
0
        /// <summary>
        /// This method is called by ProcessDataTransferMessage when a message must be sent to a aclient application
        /// that is running on this server.
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="senderCommunicator">Sender communicator</param>
        /// <param name="message">Message</param>
        private void SentToClientApplication(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
        {
            MDSClientApplication destinationApplication = null;

            //If application exists on this server, get it
            lock (_clientApplicationList.Applications)
            {
                if (_clientApplicationList.Applications.ContainsKey(message.DestinationApplicationName))
                {
                    destinationApplication = _clientApplicationList.Applications[message.DestinationApplicationName];
                }
            }
            
            //If application doesn't exist on this server...
            if (destinationApplication == null)
            {
                SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Application does not exists on this server (" + _settings.ThisServerName + ").");
                return;
            }

            //Send message according TransmitRule
            switch (message.TransmitRule)
            {
                case MessageTransmitRules.DirectlySend:
                    SendMessageDirectly(
                        senderApplication,
                        senderCommunicator,
                        destinationApplication,
                        message
                        );
                    break;
                default:
                    // case MessageTransmitRules.StoreAndForward:
                    // case MessageTransmitRules.NonPersistent:
                    EnqueueMessage(
                        senderApplication,
                        senderCommunicator,
                        destinationApplication,
                        message
                        );
                    break;
            }
        }
Пример #46
0
        /// <summary>
        /// Checks a MDSDataTransferMessage and fills it's empty fields by default values.
        /// </summary>
        /// <param name="dataTransferMessage">Message</param>
        /// <param name="senderApplication">Sender application</param>
        /// <param name="communicator">Sender communicator of application</param>
        private void FillEmptyMessageFields(MDSDataTransferMessage dataTransferMessage, MDSRemoteApplication senderApplication, ICommunicator communicator)
        {
            //Default SourceApplicationName: Name of the sender application.
            if (string.IsNullOrEmpty(dataTransferMessage.SourceApplicationName))
            {
                dataTransferMessage.SourceApplicationName = senderApplication.Name;
            }

            //Default SourceServerName: Name of this server.
            if (string.IsNullOrEmpty(dataTransferMessage.SourceServerName))
            {
                dataTransferMessage.SourceServerName = _settings.ThisServerName;
            }

            //Default DestinationApplicationName: Name of the sender application.
            if (string.IsNullOrEmpty(dataTransferMessage.DestinationApplicationName))
            {
                dataTransferMessage.DestinationApplicationName = senderApplication.Name;
            }

            //Default DestinationServerName: Name of this server.
            if (string.IsNullOrEmpty(dataTransferMessage.DestinationServerName))
            {
                dataTransferMessage.DestinationServerName = _settings.ThisServerName;
            }

            if (dataTransferMessage.SourceServerName == _settings.ThisServerName)
            {
                //Sender communicator id is being set.
                dataTransferMessage.SourceCommunicatorId = communicator.ComminicatorId;
            }
        }
Пример #47
0
        /// <summary>
        /// This method is used to process a MDSDataTransferMessage that is gotten from a mds server or client application.
        /// Message is sent to destination or next server in one of these three conditions:
        /// - Destination server is this server and application exists on this server
        /// - Destination server is an adjacent server of this server
        /// - Destination server in server graph and there is a path from this server to destination server
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="senderCommunicator">Sender communicator</param>
        /// <param name="message">Message</param>
        private void ProcessDataTransferMessage(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSDataTransferMessage message)
        {
            //Check for duplicate messages
            if (senderApplication.LastAcknowledgedMessageId == message.MessageId)
            {
                SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Duplicate message.");
                return;
            }

            try
            {
                AddThisServerToPassedServerList(message);

                FillEmptyMessageFields(message, senderApplication, senderCommunicator);

                _routingTable.ApplyRouting(message);

                //If Destination server is this server then deliver message to the destination application
                if (message.DestinationServerName.Equals(_settings.ThisServerName, StringComparison.OrdinalIgnoreCase))
                {
                    SentToClientApplication(senderApplication, senderCommunicator, message);
                }
                //Else, if destination server is an adjacent of this server (so they can communicate directly)
                else if (_serverGraph.AdjacentServers.ContainsKey(message.DestinationServerName))
                {
                    SentToAdjacentServer(senderApplication, senderCommunicator, message);
                }
                //Else, if destination server is not adjacent but in server graph (so, send message to next server)
                else if (_serverGraph.ServerNodes.ContainsKey(message.DestinationServerName))
                {
                    SendToNextServer(senderApplication, senderCommunicator, message);
                }
                else
                {
                    //return error to sender
                    SendOperationResultMessage(senderApplication, senderCommunicator, message, false, "Destination does not exists.");
                }
            }
            catch (Exception ex)
            {
                SendOperationResultMessage(senderApplication, senderCommunicator, message, false, ex.Message);
            }
        }
Пример #48
0
        /// <summary>
        /// Process GetWaitingMessagesOfApplicationMessage
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="message"></param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessGetWaitingMessagesOfApplicationMessage(ICommunicator communicator, GetWaitingMessagesOfApplicationMessage message, MDSControllerMessage controllerMessage)
        {
            var messageList = OrganizationLayer.GetWaitingMessagesOfApplication(message.ApplicationName);

            //Send response message
            //ReplyMessageToCommunicator(communicator, new GetWaitingMessagesOfApplicationResponseMessage() { Messages = messageList }, controllerMessage );
            SendMessageToAllReceivers(new GetWaitingMessagesOfApplicationResponseMessage() { Messages = messageList });

        }
Пример #49
0
 /// <summary>
 /// Adds message to destination's send queue.
 /// </summary>
 /// <param name="senderApplication">Sender application/server</param>
 /// <param name="senderCommunicator">Sender communicator</param>
 /// <param name="destApplication">Destination application/server</param>
 /// <param name="message">Message</param>
 private static void EnqueueMessage(MDSRemoteApplication senderApplication, ICommunicator senderCommunicator, MDSPersistentRemoteApplicationBase destApplication, MDSDataTransferMessage message)
 {
     destApplication.EnqueueMessage(message);
     SendOperationResultMessage(senderApplication, senderCommunicator, message, true, "Success.");
 }
Пример #50
0
        private void ProcessUpdateApplicationWebServicesMessage(ICommunicator communicator, UpdateApplicationWebServicesMessage message, MDSControllerMessage controllerMessage)
        {
            try
            {
                //Find application
                ApplicationInfoItem application = null;
                foreach (var applicationInfoItem in _settings.Applications)
                {
                    if (applicationInfoItem.Name == message.ApplicationName)
                    {
                        application = applicationInfoItem;
                    }
                }

                if (application == null)
                {
                    //Send message
                    ReplyMessageToCommunicator(
                        communicator,
                        new OperationResultMessage()
                        {
                            Success = false,
                            ResultMessage = "No application found with name '" + message.ApplicationName + "'."
                        },
                        controllerMessage
                        );
                    return;
                }

                //Delete old service list
                application.CommunicationChannels.Clear();

                //Add new services
                if (message.WebServices != null && message.WebServices.Length > 0)
                {
                    foreach (var webServiceInfo in message.WebServices)
                    {
                        var channelInfo = new ApplicationInfoItem.CommunicationChannelInfoItem { CommunicationType = "WebService" };
                        channelInfo.CommunicationSettings["Url"] = webServiceInfo.Url;
                        application.CommunicationChannels.Add(channelInfo);
                    }
                }

                try
                {
                    //Save settings
                    _settings.SaveToXml();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message, ex);
                    ReplyMessageToCommunicator(
                        communicator,
                        new OperationResultMessage()
                        {
                            Success = false,
                            ResultMessage = "Can not save XML configuration file (MDSSettings.xml)."
                        },
                        controllerMessage
                        );
                    return;
                }

                //Send success message
                ReplyMessageToCommunicator(
                    communicator,
                    new OperationResultMessage()
                    {
                        Success = true,
                        ResultMessage = "Success."
                    },
                    controllerMessage
                    );
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                ReplyMessageToCommunicator(
                    communicator,
                    new OperationResultMessage()
                    {
                        Success = false,
                        ResultMessage = ex.Message
                    },
                    controllerMessage
                    );
                return;
            }
        }
Пример #51
0
 /// <summary>
 /// Sends a message to a spesific communicator as a reply to an incoming message.
 /// </summary>
 /// <param name="communicator">Communicator to send message</param>
 /// <param name="message">Message to send</param>
 /// <param name="incomingMessage">Incoming message which is being replied</param>
 private void ReplyMessageToCommunicator(ICommunicator communicator, ControlMessage message, MDSControllerMessage incomingMessage)
 {
     //Create MDSControllerMessage that includes serialized GetApplicationListResponseMessage message
     var outgoingMessage = new MDSControllerMessage
     {
         ControllerMessageTypeId = message.MessageTypeId,
         MessageData = MDSSerializationHelper.SerializeToByteArray(message),
         RepliedMessageId = incomingMessage.MessageId
     };
     //Send message to communicator that sent to message
     SendMessage(outgoingMessage, communicator);
 }
Пример #52
0
        private void ProcessGetApplicationWebServicesMessage(ICommunicator communicator, GetApplicationWebServicesMessage message, MDSControllerMessage controllerMessage)
        {
            try
            {
                //Find application
                ApplicationInfoItem application = null;
                foreach (var applicationInfoItem in _settings.Applications)
                {
                    if(applicationInfoItem.Name == message.ApplicationName)
                    {
                        application = applicationInfoItem;
                    }
                }

                if(application == null)
                {
                    //Send message
                    ReplyMessageToCommunicator(
                        communicator,
                        new GetApplicationWebServicesResponseMessage
                            {
                                WebServices = null,
                                Success = false,
                                ResultText = "No application found with name '" + message.ApplicationName + "'."
                            },
                        controllerMessage
                        );

                    return;
                }

                var webServiceList = new List<ApplicationWebServiceInfo>();
                foreach (var channel in application.CommunicationChannels)
                {
                    if ("WebService".Equals(channel.CommunicationType, StringComparison.OrdinalIgnoreCase))
                    {
                        webServiceList.Add(new ApplicationWebServiceInfo {Url = channel.CommunicationSettings["Url"]});
                    }
                }

                //Send web service list
                ReplyMessageToCommunicator(
                    communicator,
                    new GetApplicationWebServicesResponseMessage
                        {
                            WebServices = webServiceList.ToArray(),
                            Success = true,
                            ResultText = "Success."
                        },
                    controllerMessage
                    );
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
        }
Пример #53
0
        /// <summary>
        /// Processes UpdateServerGraphMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controlMessage">The message to be processed</param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessUpdateServerGraphMessage(ICommunicator communicator, UpdateServerGraphMessage controlMessage, MDSControllerMessage controllerMessage)
        {
            try
            {
                var newSettings = new MDSSettings(Path.Combine(GeneralHelper.GetCurrentDirectory(), "MDSSettings.xml"));
                var newDesignSettings = new MDSDesignSettings(Path.Combine(GeneralHelper.GetCurrentDirectory(), "MDSSettings.design.xml"));

                //Clear existing server lists
                newSettings.Servers.Clear();
                newDesignSettings.Servers.Clear();

                //Add servers from UpdateServerGraphMessage
                newSettings.ThisServerName = controlMessage.ServerGraph.ThisServerName;
                foreach (var server in controlMessage.ServerGraph.Servers)
                {
                    //Settings
                    newSettings.Servers.Add(
                        new ServerInfoItem
                        {
                            Name = server.Name,
                            IpAddress = server.IpAddress,
                            Port = server.Port,
                            Adjacents = server.Adjacents
                        });
                    //Design settings
                    newDesignSettings.Servers.Add(
                        new ServerDesignItem
                        {
                            Name = server.Name,
                            Location = server.Location
                        });
                }

                //Save settings
                newSettings.SaveToXml();
                newDesignSettings.SaveToXml();
            }
            catch (Exception ex)
            {
                //Send fail message
                ReplyMessageToCommunicator(
                    communicator,
                    new OperationResultMessage {Success = false, ResultMessage = ex.Message},
                    controllerMessage
                    );
                return;
            }

            //Send success message
            ReplyMessageToCommunicator(
                communicator,
                new OperationResultMessage {Success = true, ResultMessage = "Success"},
                controllerMessage
                );
        }
Пример #54
0
        /// <summary>
        /// Processes GetServerGraphMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessGetServerGraphMessage(ICommunicator communicator, MDSControllerMessage controllerMessage)
        {
            //Create response message
            var responseMessage =
                new GetServerGraphResponseMessage
                    {
                        ServerGraph =
                            new ServerGraphInfo
                                {
                                    ThisServerName = _settings.ThisServerName,
                                    Servers = new ServerGraphInfo.ServerOnGraph[_settings.Servers.Count]
                                }
                    };

            //Fill server settings
            for (var i = 0; i < _settings.Servers.Count; i++)
            {
                responseMessage.ServerGraph.Servers[i] = new ServerGraphInfo.ServerOnGraph
                                                             {
                                                                 Name = _settings.Servers[i].Name,
                                                                 IpAddress = _settings.Servers[i].IpAddress,
                                                                 Port = _settings.Servers[i].Port,
                                                                 Adjacents = _settings.Servers[i].Adjacents
                                                             };
            }

            //Fill server design settings
            for (var i = 0; i < responseMessage.ServerGraph.Servers.Length; i++)
            {
                foreach (var serverDesignItem in _designSettings.Servers)
                {
                    if (responseMessage.ServerGraph.Servers[i].Name == serverDesignItem.Name)
                    {
                        responseMessage.ServerGraph.Servers[i].Location = serverDesignItem.Location;
                        break;
                    }
                }
            }

            //Send response message
            ReplyMessageToCommunicator(
                communicator,
                responseMessage,
                controllerMessage
                );
        }
Пример #55
0
        /// <summary>
        /// Processes RemoveApplicationMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controlMessage">The message to be processed</param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessRemoveApplicationMessage(ICommunicator communicator, RemoveApplicationMessage controlMessage, MDSControllerMessage controllerMessage)
        {
            try
            {
                var removedApplication = OrganizationLayer.RemoveApplication(controlMessage.ApplicationName);
                removedApplication.CommunicatorConnected -= ClientApplication_CommunicatorConnected;
                removedApplication.CommunicatorDisconnected -= ClientApplication_CommunicatorDisconnected;

                ReplyMessageToCommunicator(
                    communicator,
                    new RemoveApplicationResponseMessage
                        {
                            ApplicationName = controlMessage.ApplicationName,
                            Removed = true,
                            ResultMessage = "Success."
                        },
                    controllerMessage
                    );

                SendMessageToAllReceivers(
                    new ClientApplicationRemovedEventMessage
                        {
                            ApplicationName = removedApplication.Name
                        });
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                ReplyMessageToCommunicator(
                    communicator,
                    new RemoveApplicationResponseMessage
                        {
                            ApplicationName = controlMessage.ApplicationName,
                            Removed = false,
                            ResultMessage = ex.Message
                        },
                    controllerMessage
                    );
            }
        }
Пример #56
0
        /// <summary>
        /// Processes GetApplicationListMessage.
        /// </summary>
        /// <param name="communicator">Communicator that sent message</param>
        /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
        private void ProcessGetApplicationListMessage(ICommunicator communicator, MDSControllerMessage controllerMessage)
        {
            //Get all client applications
            var applicationList = OrganizationLayer.GetClientApplications();

            //Create ClientApplicationInfo array
            var clientApplications = new GetApplicationListResponseMessage.ClientApplicationInfo[applicationList.Length];
            for (var i = 0; i < applicationList.Length; i++)
            {
                clientApplications[i] = new GetApplicationListResponseMessage.ClientApplicationInfo
                                         {
                                             Name = applicationList[i].Name,
                                             CommunicatorCount = applicationList[i].ConnectedCommunicatorCount,
                                             MessageCount = applicationList[i].GetWaitingMessages(0, applicationList[i].GetMaxWaitingMessageId() +1).Count
                                         };
            }

            //Send response message
            ReplyMessageToCommunicator(
                communicator,
                new GetApplicationListResponseMessage
                    {
                        ClientApplications = clientApplications
                    },
                controllerMessage
                );
        }
Пример #57
0
        /// <summary>
        /// To send a MDSOperationResultMessage to remote application's spesific communicator.
        /// </summary>
        /// <param name="senderApplication">Sender application/server</param>
        /// <param name="communicator">Communicator to send message</param>
        /// <param name="repliedMessage">Replied Message</param>
        /// <param name="success">Operation result</param>
        /// <param name="resultText">Details</param>
        private static void SendOperationResultMessage(MDSRemoteApplication senderApplication, ICommunicator communicator, MDSDataTransferMessage repliedMessage, bool success, string resultText)
        {
            try
            {
                if (success)
                {
                    //Save MessageId of acknowledged message to do not receive same message again
                    senderApplication.LastAcknowledgedMessageId = repliedMessage.MessageId;
                }

                senderApplication.SendMessage(new MDSOperationResultMessage
                {
                    RepliedMessageId = repliedMessage.MessageId,
                    Success = success,
                    ResultText = resultText
                }, communicator);
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
            }
        }
Пример #58
0
 /// <summary>
 /// Adds a TCPCommunicator object to _communicators list.
 /// </summary>
 /// <param name="communicator">TCPCommunicator to be added</param>
 private void AddToCommunicators(ICommunicator communicator)
 {
     lock (_communicators)
     {
         _communicators[communicator.ComminicatorId] = communicator;
     }
 }
Пример #59
0
 /// <summary>
 /// Sends a NGRIDOperationResultMessage message to a communicator.
 /// </summary>
 /// <param name="communicator">Communicator object</param>
 /// <param name="success">Operation result</param>
 /// <param name="resultText">Detailed result/error text</param>
 /// <param name="repliedMessageId">The message id of request message</param>
 private static void SendOperationResultMessage(ICommunicator communicator, bool success, string resultText, string repliedMessageId)
 {
     communicator.SendMessage(
         new NGRIDOperationResultMessage
             {
                 Success = success,
                 ResultText = resultText,
                 RepliedMessageId = repliedMessageId
             });
 }
Пример #60
0
 /// <summary>
 /// This methods checks type of message (MessageTypeId) and calls appropriate method to process message.
 /// </summary>
 /// <param name="communicator">Communicator that sent message</param>
 /// <param name="controllerMessage">MDSControllerMessage object that includes controlMessage</param>
 /// <param name="controlMessage">The message to be processed</param>
 private void ProcessControllerMessage(ICommunicator communicator, MDSControllerMessage controllerMessage , ControlMessage controlMessage)
 {
     switch (controlMessage.MessageTypeId)
     {
         case ControlMessageFactory.MessageTypeIdGetApplicationListMessage:
             ProcessGetApplicationListMessage(communicator, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdGetWaitingMessagesOfApplicationMessage:
             ProcessGetWaitingMessagesOfApplicationMessage(communicator, controlMessage as GetWaitingMessagesOfApplicationMessage, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdAddNewApplicationMessage:
             ProcessAddNewApplicationMessage(controlMessage as AddNewApplicationMessage);
             break;
         case ControlMessageFactory.MessageTypeIdRemoveApplicationMessage:
             ProcessRemoveApplicationMessage(communicator, controlMessage as RemoveApplicationMessage, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdGetServerGraphMessage:
             ProcessGetServerGraphMessage(communicator, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdUpdateServerGraphMessage:
             ProcessUpdateServerGraphMessage(communicator, controlMessage as UpdateServerGraphMessage, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdGetApplicationWebServicesMessage:
             ProcessGetApplicationWebServicesMessage(communicator, controlMessage as GetApplicationWebServicesMessage, controllerMessage);
             break;
         case ControlMessageFactory.MessageTypeIdUpdateApplicationWebServicesMessage:
             ProcessUpdateApplicationWebServicesMessage(communicator, controlMessage as UpdateApplicationWebServicesMessage, controllerMessage);
             break;
         default:
             throw new MDSException("Undefined MessageTypeId for ControlMessage: " + controlMessage.MessageTypeId);
     }
 }