Beispiel #1
0
        //
        //
        // Main.
        //
        //
        static void Main(string[] args)
        {
            ArchiverApp app   = new ArchiverApp();
            ServerAgent agent = AppUtils.ConnectToServer(app, "Archiver.am");

            if (agent != null)
            {
                //
                // Open logfile.
                //
                try
                {
                    LogFile = new StreamWriter(new FileStream("IM.log", FileMode.Create, FileAccess.Write));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create IM.log: " + e.Message);
                    return;
                }

                //
                // Event dispatch loop.
                //
                Console.WriteLine("Archiver sample started.  Press Control-C to quit.");
                while (true)
                {
                    agent.WaitHandle.WaitOne();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(agent.ProcessEvent));
                }
            }
        }
Beispiel #2
0
        private async Task UpdateAgent(ServerAgent agent, MessageClient messageClient, CancellationToken token)
        {
            var message = new AgentUpdateRequest {
                Filename = UpdateFilename,
            };

            try {
                await messageClient.Send(message)
                .GetResponseAsync(token);

                await messageClient.DisconnectAsync();
            }
            finally {
                messageClient?.Dispose();
            }

            await Task.Delay(3000, token);

            // TODO: Verify update was successful by polling for server and checking version
            messageClient = null;

            try {
                messageClient = await Reconnect(agent, TimeSpan.FromMinutes(2));
            }
            finally {
                messageClient?.Dispose();
            }
        }
        /// <summary>
        /// Disconnect from the Live Communications Server, cleanup
        /// </summary>
        /// <remarks> If we are connected to the server,
        /// to disconnect and cleanup is to dispose the
        /// server agent object.
        /// </remarks>
        protected void InternalDisconnect()
        {
            if (serverAgent == null)
            {
                return; ///already gone
            }
            if (eventManagerThread != null)
            {
                ///first stop our event manager thread
                eventManagerQuit.Set();
                eventManagerThread.Join(1000 /* upto a second */);
                eventManagerThread = null;
            }

            if (serverAgent != null)
            {
                ///remove the connection to server
                ServerAgent serverAgentToDispose = serverAgent;
                serverAgent = null;
                serverAgentToDispose.Dispose();
            }

            applicationManifest = null;

            return;
        }
        /// <summary>
        /// Disconnect from the Server and cleanup
        /// </summary>
        /// <remarks> In order to disconnect we need to dispose the ServerAgent object.
        /// Derived classes should always call base.InternalDisconnect from their overrides.
        /// </remarks>
        protected virtual void InternalDisconnect(ConnectionDroppedEventArgs cde)
        {
            ServerAgent serverAgentToDispose = serverAgent;

            if (serverAgentToDispose != null)
            {
                serverAgent         = null;
                applicationManifest = null;

                //
                // Stop event manager.
                //

                quitHandle.Set();
                eventManager.Join(1000 /* upto a second */);
                eventManager = null;

                try {
                    //
                    // Disconnect from server.
                    //

                    serverAgentToDispose.Dispose();
                }
                catch (Exception e) {
                    Debug.Write(e.Message);
                }
            }

            return;
        }
        /// <summary>
        /// Load and compile the application manifest, and try
        /// to connect to the Live Communications Server.
        /// </summary>
        /// <exception cref="System.Exception">If unable to
        /// connect. The exception string contains the details
        /// </exception>
        /// <param name="manifestFile">file name of the SPL manifest.
        /// This file must be present in the working directory of the
        /// executable
        /// </param>
        /// <param name="applicationName">A friendly name for use while
        /// registering with WMI. Use a null value if you dont want
        /// the function to do registration
        /// </param>
        /// <param name="appGuid">Guid for use during WMI registration.
        /// If a null guid is specified but applicationName is not
        /// null, a new guid will be generated, used, and returned.
        /// </param>
        /// <seealso cref="Microsoft.Rtc.Sip.CompilerErrorException"/>
        /// <seealso cref="Microsoft.Rtc.Sip.ServerAgent"/>
        public void ConnectToServer(string manifestFile, string applicationName, ref string appGuid)
        {
            ///load and compile the application manifest
            applicationManifest = ApplicationManifest.CreateFromFile(manifestFile);
            if (applicationManifest == null)
            {
                throw new Exception(
                          String.Format("The manifest file {0} was not found", manifestFile));
            }

            try {
                applicationManifest.Compile();

                ///try to connect to server
                serverAgent = new ServerAgent(this, applicationManifest);
            }
            catch (CompilerErrorException cee) {
                ///collapse all compiler errors into one, and return it
                StringBuilder sb = new StringBuilder(1024, 1024);
                foreach (string errorMessage in cee.ErrorMessages)
                {
                    if (errorMessage.Length + sb.Length + 2 < sb.MaxCapacity)
                    {
                        sb.Append(errorMessage);
                        sb.Append("\r\n");
                    }
                    else
                    {
                        ///compiler returns really large error message
                        ///so just return what we can accomodate
                        sb.Append(errorMessage.Substring(0, sb.MaxCapacity - sb.Length - 1));
                        break;
                    }
                }

                throw new Exception(sb.ToString());
            }
            catch (Exception e) {
                if (applicationManifest != null)
                {
                    applicationManifest = null;
                }

                //ServerNotFoundException || UnauthorizedException
                throw e;
            }


            ///hook the connection dropped event handler
            serverAgent.ConnectionDropped += new ConnectionDroppedEventHandler(this.ConnectionDroppedHandler);  //ConnectionDroppedEventHandler

            ///start the eventManager thread after making sure one is
            ///not already running
            eventManagerQuit.Reset();
            eventManagerThread = new Thread(new ThreadStart(EventManagerHandler));
            eventManagerThread.Start();

            return;
        }
Beispiel #6
0
        private DomainAgentSessionClient ConnectionFactory_OnConnectionRequest(ServerAgent agent)
        {
            var host = OnCreateHost(agent);

            hostList[host.SessionClientId] = host;

            return(host.SessionClient);
        }
Beispiel #7
0
 private void checkState(ServerAgent agent, int cnnID)
 {
     if (updateRequred || Mathf.Abs(agent.storedX - agent.avatar.GetComponent <character_behavior> ().lokacja.x) > updateInterval || Mathf.Abs(agent.storedY - agent.avatar.GetComponent <character_behavior> ().lokacja.y) > updateInterval ||
         Mathf.Abs(agent.sAimX - agent.avatar.GetComponent <character_behavior> ().aim.x) > updateInterval || Mathf.Abs(agent.sAimY - agent.avatar.GetComponent <character_behavior> ().aim.y) > updateInterval)
     {
         updateRequred = true;
     }
 }
Beispiel #8
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                Output.Append("Connecting to agent ", ConsoleColor.DarkCyan)
                .Append(agent.Name, ConsoleColor.Cyan)
                .AppendLine("...", ConsoleColor.DarkCyan);

                try {
                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    var handshakeRequest = new HandshakeRequest {
                        Key           = Guid.NewGuid().ToString(),
                        ServerVersion = Configuration.Version,
                    };

                    var timeout           = TimeSpan.FromSeconds(HandshakeTimeoutSec);
                    var handshakeResponse = await messageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, TokenSource.Token);

                    if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                    {
                        throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                    }

                    if (!handshakeResponse.PasswordMatch)
                    {
                        throw new ApplicationException("Handshake Failed! Unauthorized.");
                    }
                }
                catch (Exception error) {
                    Output.Append("Failed to connect to agent ", ConsoleColor.DarkRed)
                    .Append(agent.Name, ConsoleColor.Red)
                    .AppendLine("!", ConsoleColor.DarkRed)
                    .AppendLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);

                    return;
                }

                Output.AppendLine("Agent connected.", ConsoleColor.DarkGreen);

                Output.Append("Updating Agent ", ConsoleColor.DarkCyan)
                .Append(agent.Name, ConsoleColor.Cyan)
                .AppendLine("...", ConsoleColor.DarkCyan);

                try {
                    await UpdateAgent(agent, messageClient, TokenSource.Token);

                    Output.Append("Agent ", ConsoleColor.DarkGreen)
                    .Append(agent.Name, ConsoleColor.Green)
                    .AppendLine(" updated successfully.", ConsoleColor.DarkGreen);
                }
                catch (Exception error) {
                    Output.Append("Failed to update agent ", ConsoleColor.DarkRed)
                    .Append(agent.Name, ConsoleColor.Red)
                    .AppendLine("!", ConsoleColor.DarkRed)
                    .AppendLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);
                }
            }
        }
Beispiel #9
0
        private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout)
        {
            var client = new MessageClient(PhotonServer.Instance.MessageRegistry);

            client.ThreadException += (o, e) => {
                var error = (Exception)e.ExceptionObject;
                Output.AppendLine("An error occurred while messaging the client!", ConsoleColor.DarkRed)
                .AppendLine(error.UnfoldMessages());

                Log.Error("Message Client error after update!", error);
            };

            var tokenSource = new CancellationTokenSource(timeout);

            var token = tokenSource.Token;

            while (true)
            {
                token.ThrowIfCancellationRequested();

                try {
                    await client.ConnectAsync(agent.TcpHost, agent.TcpPort, tokenSource.Token);

                    var handshakeRequest = new HandshakeRequest {
                        Key           = Guid.NewGuid().ToString(),
                        ServerVersion = Configuration.Version,
                    };

                    var handshakeTimeout  = TimeSpan.FromSeconds(HandshakeTimeoutSec);
                    var handshakeResponse = await client.Handshake <HandshakeResponse>(handshakeRequest, handshakeTimeout, TokenSource.Token);

                    if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                    {
                        throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                    }

                    if (!handshakeResponse.PasswordMatch)
                    {
                        throw new ApplicationException("Handshake Failed! Unauthorized.");
                    }

                    var versionRequest = new AgentGetVersionRequest();

                    var versionResponse = await client.Send(versionRequest)
                                          .GetResponseAsync <AgentGetVersionResponse>(token);

                    if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion))
                    {
                        break;
                    }
                }
                catch (SocketException) {
                    await Task.Delay(1000, tokenSource.Token);
                }
            }

            return(client);
        }
Beispiel #10
0
    void Shoot()
    {
        if (player.gun != null)
        {
            player.SetUpperAniState(Player.StateNameHash.shoot);
            Ray        ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
            Vector3    targetPoint;
            RaycastHit hitInfo;
            if (Physics.Raycast(ray, out hitInfo, 100f, player.hitLayer))
            {
                targetPoint = hitInfo.point;
            }
            else
            {
                targetPoint = Camera.main.transform.position + ray.direction * 100f;
            }

            if (player.gun.Shoot(targetPoint, player.hitLayer, out hitInfo))
            {
                LevelManager lm       = UnityHelper.GetLevelManager();
                Collider     collider = hitInfo.collider;
                if (collider.gameObject.layer == LayerMask.NameToLayer(StringAssets.bodyLayerName))
                {
                    Player p = UnityHelper.FindObjectUpward <Player>(collider.transform);
                    if (p != null)
                    {
                        if (lm != null)
                        {
                            lm.CreateParticleEffect(LevelManager.ParticleEffectType.HitPlayer, hitInfo.point, hitInfo.normal);
                        }
                        controller.HitOtherPlayer(p, hitInfo.point, 100f);
                    }
                    else
                    {
                        Debug.LogError("AimState.Shoot >> hit body, but can't find Player component");
                    }
                }
                else if (collider.gameObject.layer == LayerMask.NameToLayer(StringAssets.groundLayerName))
                {
                    if (lm != null)
                    {
                        lm.CreateParticleEffect(LevelManager.ParticleEffectType.HitGround, hitInfo.point, hitInfo.normal);
                    }
                }
            }

            if (GlobalVariables.hostType == HostType.Server)
            {
                ServerAgent sa = UnityHelper.GetServerAgent();
                sa.SendShoot(player.id, targetPoint);
            }
            else if (GlobalVariables.hostType == HostType.Client)
            {
                ClientAgent ca = UnityHelper.GetClientAgent();
                ca.SendShoot(player.id, targetPoint);
            }
        }
    }
        static ServerAgent ConnectToServer(object app, string amFile)
        {
            try
            {
                ServerAgent.WaitForServerAvailable(3);      // 3 Attempts
            }
            catch (Exception e1)
            {
                Console.WriteLine("ERROR: Server unavailable - {0}", e1.Message);
                if (e1 is UnauthorizedException)
                {
                    Console.WriteLine("must be running under an account that is a member of the \"RTC Server Applications\" local group");
                }
                return(null);
            }


            ApplicationManifest am = ApplicationManifest.CreateFromFile(amFile);

            if (am == null)
            {
                Console.WriteLine("ERROR: {0} application manifest file not found.", amFile);
                return(null);
            }

            try
            {
                am.Compile();
            }
            catch (CompilerErrorException e2)
            {
                Console.WriteLine("ERROR: {0} application manifest file contained errors:", amFile);
                foreach (string message in e2.ErrorMessages)
                {
                    Console.WriteLine(message);
                }
                return(null);
            }

            try
            {
                ServerAgent agent = new ServerAgent(app, am);
                Console.WriteLine("ServerAgent instantiated successfully with Role={0}", agent.Role.ToString());
                return(agent);
            }
            catch (Exception e3)
            {
                Console.WriteLine("ERROR: Unable insnatiate ServerAgent and to connect to server - {0}", e3.Message);
                Console.WriteLine("ERROR: type - {0}", e3.GetType().ToString());
                Console.WriteLine("ERROR: stacktrace: {0}", e3.StackTrace);
                if (e3.InnerException != null)
                {
                    Console.WriteLine("ERROR: inner exception: {0} ", e3.InnerException.Message);
                }
                return(null);
            }
        }
Beispiel #12
0
        private void Document_OnUpdate(JObject document, ServerAgent agent, string prevId)
        {
            if (!(document.SelectToken("agents") is JArray agentArray))
            {
                agentArray = new JArray();
                document.Add("agents", agentArray);

                var token = JObject.FromObject(agent);
                agentArray.Add(token);
            }
        public void when_starting_an_already_started_agent_nothing_happens()
        {
            var pollers = new List <FakeEventLogPoller> {
                new FakeEventLogPoller(), new FakeEventLogPoller()
            };

            var sut = new ServerAgent(pollers);

            sut.Start();
            sut.Start();
        }
Beispiel #14
0
 void OnClearAIClick()
 {
     if (GlobalVariables.hostType == HostType.Server)
     {
         ServerAgent sa = UnityHelper.GetServerAgent();
         if (sa)
         {
             sa.ClearAI();
         }
     }
 }
Beispiel #15
0
 void OnDestroy()
 {
     if (GlobalVariables.hostType == HostType.Server)
     {
         ServerAgent sm = GetComponent <ServerAgent>();
         sm.enabled = false;
     }
     else if (GlobalVariables.hostType == HostType.Client)
     {
         ClientAgent cm = GetComponent <ClientAgent>();
         cm.enabled = false;
     }
 }
        static private void ProcessPresence()
        {
            try
            {
                // Connect this Lync Server API application to the server. If successful,
                // a compiled instance of the application manifest will be loaded to the
                // server and the embedded script ready to dispatch events to the
                // OnSubscribe event handler.
                PresenceSubInterceptorForBot app = new PresenceSubInterceptorForBot();
                ServerAgent agent = ConnectToServer(app, "PresenceSubInterceptorForBot.am");
                if (agent != null)
                {
                    // Event dispatch loop.
                    Console.WriteLine("ServerAgent for PresenceSubInterceptorForBot sample started.");
                    Console.WriteLine("Press Control-C to quit.");
                    ManualResetEvent resetEvent  = new ManualResetEvent(false);
                    WaitHandle[]     handleArray = new WaitHandle[] { agent.WaitHandle, resetEvent };

                    WaitCallback waitCallback = new WaitCallback(agent.ProcessEvent);
                    while (true)
                    {
                        int signaledEvent = WaitHandle.WaitAny(handleArray);
                        if (signaledEvent == 0)
                        {
                            try
                            {
                                if (!ThreadPool.QueueUserWorkItem(waitCallback))
                                {
                                    Console.WriteLine("QueueUserWorkItem failed, quitting.");
                                    return;
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to invoke ThreadPool.QueueUserWorkItem: {0}", ex.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Quit signaled, worker will quit.");
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while running ProcessPresence: {0}", ex.Message);
            }
        }
        public void when_starting_all_event_log_pollers_are_started()
        {
            var pollers = new List <FakeEventLogPoller> {
                new FakeEventLogPoller(), new FakeEventLogPoller()
            };

            var sut = new ServerAgent(pollers);

            sut.Start();

            foreach (var p in pollers)
            {
                Assert.True(p.Started, "the event log poller should have been started");
            }
        }
Beispiel #18
0
    // Use this for initialization
    void Start()
    {
        Physics.gravity = new Vector3(0f, -9.8f, 0f) * gravityScale; //设置重力
        Time.timeScale  = timeScale;

        if (GlobalVariables.hostType == HostType.Server)
        {
            ServerAgent sm = GetComponent <ServerAgent>();
            sm.enabled = true;
        }
        else if (GlobalVariables.hostType == HostType.Client)
        {
            ClientAgent cm = GetComponent <ClientAgent>();
            cm.enabled = true;
        }
    }
Beispiel #19
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                Output.WriteBlock(block => block
                                  .Write("Connecting to agent ", ConsoleColor.DarkCyan)
                                  .Write(agent.Name, ConsoleColor.Cyan)
                                  .WriteLine("...", ConsoleColor.DarkCyan));

                try {
                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    await ClientHandshake.Verify(messageClient, TokenSource.Token);
                }
                catch (Exception error) {
                    Output.WriteBlock(block => block
                                      .Write("Failed to connect to agent ", ConsoleColor.DarkRed)
                                      .Write(agent.Name, ConsoleColor.Red)
                                      .WriteLine("!", ConsoleColor.DarkRed)
                                      .WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow));

                    return;
                }

                Output.WriteLine("Agent connected.", ConsoleColor.DarkGreen);

                Output.WriteBlock(block => block
                                  .Write("Updating Agent ", ConsoleColor.DarkCyan)
                                  .Write(agent.Name, ConsoleColor.Cyan)
                                  .WriteLine("...", ConsoleColor.DarkCyan));

                try {
                    await UpdateAgent(agent, messageClient, TokenSource.Token);

                    Output.WriteBlock(block => block
                                      .Write("Agent ", ConsoleColor.DarkGreen)
                                      .Write(agent.Name, ConsoleColor.Green)
                                      .WriteLine(" updated successfully.", ConsoleColor.DarkGreen));
                }
                catch (Exception error) {
                    Output.WriteBlock(block => block
                                      .Write("Failed to update agent ", ConsoleColor.DarkRed)
                                      .Write(agent.Name, ConsoleColor.Red)
                                      .WriteLine("!", ConsoleColor.DarkRed)
                                      .WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow));
                }
            }
        }
Beispiel #20
0
        public static void SettingServer()
        {
            ServerAgent   server  = new ServerAgent();
            ServerSetting setting = new ServerSetting();

            setting.LengthDncoad   = LengthEncoding.Dncoad;
            setting.LengthEncoad   = LengthEncoding.Encoad;
            setting.MessageEncoad  = MessageEncoding.Encoad;
            setting.MessageDncoad  = MessageEncoding.Dncoad;
            setting.MessageEncrypt = DEncrypt.Encrypt;
            setting.MessageDecrypt = DEncrypt.Decrypt;
            setting.CompressEncode = CompressEncoding.Encode;
            setting.CompressDecode = CompressEncoding.Decode;
            setting.Center         = new HandlerCenter();
            UserToken.Setting      = setting;
            server.StartServer(setting);
        }
Beispiel #21
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                try {
                    Output.WriteLine($"[{agent.Name}] Connecting...'", ConsoleColor.White);

                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    await ClientHandshake.Verify(messageClient, TokenSource.Token);

                    Output.WriteLine($"[{agent.Name}] Connected.", ConsoleColor.DarkCyan);
                }
                catch (Exception error) {
                    using (var block = Output.WriteBlock()) {
                        block.WriteLine($"[{agent.Name}] Connection Failed!", ConsoleColor.DarkRed);
                        block.WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);
                    }

                    return;
                }

                var userMgr        = PhotonServer.Instance.UserMgr;
                var securityConfig = PhotonServer.Instance.ServerConfiguration.Value.Security;

                var message = new SecurityPublishRequest {
                    Users                 = userMgr.AllUsers.ToArray(),
                    UserGroups            = userMgr.AllGroups.ToArray(),
                    SecurityEnabled       = securityConfig.Enabled,
                    SecurityDomainEnabled = securityConfig.DomainEnabled,
                };

                Output.WriteLine($"[{agent.Name}] Publishing security configuration...", ConsoleColor.White);

                await messageClient.Send(message)
                .GetResponseAsync();

                Output.WriteLine($"[{agent.Name}] security configuration published.", ConsoleColor.DarkGreen);

                try {
                    Output.WriteLine($"[{agent.Name}] Disconnecting...", ConsoleColor.White);

                    messageClient.Disconnect();
                }
                catch {}
            }
        }
Beispiel #22
0
        private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout, CancellationToken token)
        {
            using (var timeoutTokenSource = new CancellationTokenSource(timeout))
                using (var mergedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutTokenSource.Token, token)) {
                    while (true)
                    {
                        mergedTokenSource.Token.ThrowIfCancellationRequested();

                        var client = new MessageClient(PhotonServer.Instance.MessageRegistry);

                        try {
                            using (var connectionTimeoutTokenSource = new CancellationTokenSource(20_000))
                                using (var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(mergedTokenSource.Token, connectionTimeoutTokenSource.Token)) {
                                    await client.ConnectAsync(agent.TcpHost, agent.TcpPort, connectTokenSource.Token);

                                    await ClientHandshake.Verify(client, connectTokenSource.Token);

                                    var versionRequest = new AgentGetVersionRequest();

                                    var versionResponse = await client.Send(versionRequest)
                                                          .GetResponseAsync <AgentGetVersionResponse>(connectTokenSource.Token);

                                    if (string.IsNullOrEmpty(versionResponse.Version))
                                    {
                                        Log.Warn("An empty version response was received!");
                                        continue;
                                    }

                                    if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion))
                                    {
                                        return(client);
                                    }
                                }
                        }
                        catch (SocketException) {}
                        catch (OperationCanceledException) {}
                        catch (Exception error) {
                            Log.Warn("An unhandled exception occurred while attempting to reconnect to an updating agent.", error);
                        }

                        client.Dispose();

                        await Task.Delay(3_000, mergedTokenSource.Token);
                    }
                }
        }
        protected DomainAgentSessionHostBase(IServerSession sessionBase, ServerAgent agent, CancellationToken token)
        {
            this.Agent = agent;
            this.Token = token;

            Tasks = new TaskRunnerManager();

            SessionClient = new DomainAgentSessionClient();
            SessionClient.OnSessionBegin   += SessionClient_OnSessionBegin;
            SessionClient.OnSessionRelease += SessionClient_OnSessionRelease;
            SessionClient.OnSessionRunTask += SessionClient_OnSessionRunTask;

            MessageClient = new MessageClient(PhotonServer.Instance.MessageRegistry);
            MessageClient.Transceiver.Context = sessionBase;

            MessageClient.ThreadException += MessageClient_OnThreadException;
        }
Beispiel #24
0
        //
        //
        //
        //      Main.
        //
        //
        //
        static void Main(string[] args)
        {
            LoggingNoticeApp app   = new LoggingNoticeApp();
            ServerAgent      agent = AppUtils.ConnectToServer(app, "LoggingNotice.am");

            if (agent != null)
            {
                //
                // Main loop.
                //
                Console.WriteLine("LoggingNotice sample is running.  Press Control-C to quit.");
                while (true)
                {
                    agent.WaitHandle.WaitOne();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(agent.ProcessEvent));
                }
            }
        }
Beispiel #25
0
        public void SaveAgent(ServerAgent agent, string prevId = null)
        {
            if (prevId != null)
            {
                agentCollection.TryRemove(prevId, out var _);
            }

            agentCollection.AddOrUpdate(agent.Id, agent, (k, a) => {
                a.Id      = agent.Id;
                a.Name    = agent.Name;
                a.TcpHost = agent.TcpHost;
                a.TcpPort = agent.TcpPort;
                a.Roles   = agent.Roles;
                return(a);
            });

            agentsDocument.Update(d => Document_OnUpdate(d, agent, prevId));
        }
Beispiel #26
0
        public void SelectedEntitiesAreUpdatedWhenSettingAProperty()
        {
            var sa = new ServerAgent(new TestWorkspace(), null);

            // add entity and select it
            var originalEntity  = new Location(new Point(1.0, 1.0, 1.0));
            var untouchedEntity = new Location(new Point(2.0, 2.0, 2.0));

            sa.Workspace.Add(sa.Workspace.Drawing.GetLayers().Single(), originalEntity);
            sa.Workspace.Add(sa.Workspace.Drawing.GetLayers().Single(), untouchedEntity);
            sa.Workspace.SelectedEntities.Add(originalEntity); // selected=(1,1,1), unselected=(2,2,2)

            // update the entity
            sa.SetPropertyPaneValue(new ClientPropertyPaneValue("x", "displayName", "9"));

            // verify that the new entity is selected and unselected entity is still selected
            Assert.Equal(new Point(9.0, 1.0, 1.0), ((Location)sa.Workspace.SelectedEntities.Single()).Point);
        }
Beispiel #27
0
        //
        // Static function to connect to Server
        //
        public static ServerAgent ConnectToServer(object app, string amFile)
        {
            try {
                ServerAgent.WaitForServerAvailable(3);      // 3 Attempts
            }
            catch (Exception e1) {
                Console.WriteLine("ERROR: Server unavailable - {0}", e1.Message);
                if (e1 is UnauthorizedException)
                {
                    Console.WriteLine("must be running under an account that is a member of the \"RTC Server Applications\" local group");
                }
                return(null);
            }


            ApplicationManifest am = ApplicationManifest.CreateFromFile(amFile);

            if (am == null)
            {
                Console.WriteLine("ERROR: {0} application manifest file not found.", amFile);
                return(null);
            }

            try {
                am.Compile();
            }
            catch (CompilerErrorException e2) {
                Console.WriteLine("ERROR: {0} application manifest file contained errors:", amFile);
                foreach (string message in e2.ErrorMessages)
                {
                    Console.WriteLine(message);
                }
                return(null);
            }

            try {
                ServerAgent agent = new ServerAgent(app, am);
                return(agent);
            }
            catch (Exception e3) {
                Console.WriteLine("ERROR: Unable to connect to server - {0}", e3.Message);
                return(null);
            }
        }
Beispiel #28
0
        private async Task UpdateAgent(ServerAgent agent, MessageClient messageClient, CancellationToken token)
        {
            var message = new AgentUpdateRequest {
                Filename = UpdateFilename,
            };

            try {
                await messageClient.Send(message)
                .GetResponseAsync(token);

                try {
                    messageClient.Disconnect();
                }
                catch {}
            }
            finally {
                messageClient?.Dispose();
                messageClient = null;
            }

            Output.WriteBlock(block => block
                              .Write("Agent update started on ", ConsoleColor.DarkCyan)
                              .Write(agent.Name, ConsoleColor.Cyan)
                              .WriteLine("...", ConsoleColor.DarkCyan));

            await Task.Delay(6_000, token);


            var reconnectTimeout = TimeSpan.FromMinutes(2);

            try {
                messageClient = await Reconnect(agent, reconnectTimeout, token);
            }
            catch (OperationCanceledException) {
                throw new ApplicationException($"A timeout occurred after {reconnectTimeout} while waiting for the update to complete.");
            }
            finally {
                if (messageClient != null)
                {
                    messageClient.Disconnect();
                    messageClient.Dispose();
                }
            }
        }
Beispiel #29
0
        public void Save()
        {
            var agent = new ServerAgent {
                Id      = AgentId,
                Name    = AgentName,
                TcpHost = AgentHost,
                TcpPort = AgentPort.To <int>(),
            };

            agent.Roles.AddRange(AgentRoles);

            string prevId = null;

            if (!string.Equals(AgentId_Source, AgentId, StringComparison.Ordinal))
            {
                prevId = AgentId_Source;
            }

            PhotonServer.Instance.Agents.Save(agent, prevId);
        }
Beispiel #30
0
 internal void OnServerChangeStatus(ServerAgent server, bool available)
 {
     if (ServerStatusChanged != null)
     {
         try
         {
             Events.EventServerStatusChangeArgs e = new EventServerStatusChangeArgs();
             e.Server    = server;
             e.Gateway   = this;
             e.Available = available;
             ServerStatusChanged(this, e);
         }
         catch (Exception e_)
         {
             if (HttpServer.EnableLog(LogType.Error))
             {
                 HttpServer.Log(LogType.Error, $"Gateway server change status event error {e_.Message}@{e_.StackTrace} ");
             }
         }
     }
 }