public void HandleCameraCommand( CommandMessage msg )
        {
            if ( !Enabled )
            {
                return;
            }
            switch ( ( TrackCameraCommands )msg.CommandId )
            {
                case TrackCameraCommands.Zoom:
                    {
                        ( ( SphereCamera )Parent ).Zoom = ( ( ScalarCommandMessage )msg ).Value;
                        break;
                    }

                case TrackCameraCommands.Rotate:
                    {
                        CursorCommandMessage cursorMsg = ( CursorCommandMessage )msg;
                        float deltaX = cursorMsg.X - cursorMsg.LastX;
                        float deltaY = cursorMsg.Y - cursorMsg.LastY;

                        SphereCamera camera = ( ( SphereCamera )Parent );
                        m_SOffset -= deltaX * 0.01f;
                        camera.T -= deltaY * 0.01f;

                        break;
                    }
            }
        }
Exemple #2
0
        public static void sendMessage(CommandMessage command, Object data)
        {
            if (offlineMode)
            {
                switch (command)
                {
                    case (CommandMessage.StopReturn):
                        stopReturn(null);
                        break;
                    case (CommandMessage.StartSnap):
                        snapTake(null);
                        break;
                    case (CommandMessage.GoHome):
                        goHome(null);
                        break;
                    default:
                        break;
                }
                return;
            }

            if (!IsConnected) return;
            TransMessage tm = new TransMessage(command, data, CurrentStructureId);
            debugMessage("SENDING MESSAGE - " + tm.ToString());
            saclient.SendObject(tm, false);
        }
Exemple #3
0
        internal Task<MqttCommand> WaitForCommand(CommandMessage message, MessageId messageId, TimeSpan timeout)
        {
            lock (_desireLock)
            {
                var maybeLoved =
                    _unlovedCommands.FirstOrDefault(c => c.MessageId == messageId && c.CommandMessage == message);

                if (maybeLoved != null)
                {
                    var tcs = new TaskCompletionSource<MqttCommand>();
                    tcs.SetResult(maybeLoved);
                    return tcs.Task;
                }

                MqttCommand result = null;
                var wait = new ManualResetEvent(false);

                var d = new Desire(message, messageId, cmd =>
                    {
                        result = cmd;
                        wait.Set();
                    });

                _desireCache.AddAndRemoveDuplicates(d);

                return Task<MqttCommand>.Factory.StartNew(() =>
                    {
                        wait.WaitOne(timeout);
                        return result;
                    });
            }
        }
        public Task Consumed(CommandMessage last)
        {
            if (last == null)
                return TplHelper.Empty;

            using(_messagesLock.BeginUpgradeableReadLock())
            {
                var messages = _clientMessages[last.ClientId];
                var node = messages.Last;
                while (node != null && node.Value != last)
                    node = node.Previous;

                using (_messagesLock.BeginWriteLock())
                {
                    while (node != null)
                    {
                        var previousNode = node.Previous;
                        while (previousNode != null && previousNode.Value.ClientId != node.Value.ClientId)
                            previousNode = previousNode.Previous;

                        node.List.Remove(node);
                        node = previousNode;
                    }
                }
            }

            return TplHelper.Empty;
        }
        public MessageRecipientResult OnCommand( CommandMessage msg )
        {
            float speed = m_Speed;
            float rotateSpeed = 0.1f;

            //	TODO: AP: Query entity frame instead?
            Entity3d entity = ( Entity3d )Parent;
            switch ( ( TestCommands )msg.CommandId )
            {
                case TestCommands.Forward		: SendMovement( entity, entity.Ahead * speed ); break;
                case TestCommands.Back			: SendMovement( entity, entity.Back * speed ); break;
                case TestCommands.Left			: SendMovement( entity, entity.Left * speed ); break;
                case TestCommands.Right			: SendMovement( entity, entity.Right * speed ); break;
                case TestCommands.RotateRight	: SendRotation( entity, rotateSpeed ); break;
                case TestCommands.RotateLeft	: SendRotation( entity, -rotateSpeed ); break;
                case TestCommands.Jump			: entity.HandleMessage( new JumpRequest( null ) ); break;
                case TestCommands.LookAt		:
                    PickCommandMessage pickMsg = ( PickCommandMessage )msg;
                    if ( pickMsg.Intersection != null )
                    {
                        SendLookAt( entity, pickMsg.Intersection.IntersectionPosition );
                    }
                    break;
            }
            return MessageRecipientResult.DeliverToNext;
        }
        public CommandVersioningHandlerModule(IEventPublisher publisher)
        {
            For<CommandMessage<CreateTShirtV2>>()
                .Handle((_, __) => { throw new NotSupportedException(); });

            For<CommandMessage<CreateTShirtV3>>()
                .Handle((commandMessage, ct) =>
                {
                    var command = new CreateTShirtV4
                    {
                        Name = commandMessage.Command.Name,
                        Sizes = commandMessage.Command.Sizes,
                        Colors = commandMessage.Command.Colors,
                        BlankType = "Round"
                    };
                    var upconvertedCommand = new CommandMessage<CreateTShirtV4>(
                        commandMessage.CommandId,
                        commandMessage.RequestUser, 
                        command);
                    return this.DispatchSingle(upconvertedCommand, ct);
                });

            For<CommandMessage<CreateTShirtV4>>()
                .Handle((commandMessage, ct) =>
                {
                    publisher.Publish(new TShirtCreatedV4
                    {
                        BlankType = commandMessage.Command.BlankType,
                        Name = commandMessage.Command.Name,
                        Colors = commandMessage.Command.Colors,
                        Sizes = commandMessage.Command.Sizes
                    });
                    return Task.FromResult(true);
                });
        }
 public static void SendCommandToServer(string command, long targetOid)
 {
     CommandMessage commandMessage = new CommandMessage();
     commandMessage.ObjectId = targetOid;
     commandMessage.Command = command;
     NetworkHelper.Instance.SendMessage(commandMessage);
     UnityEngine.Debug.Log("Sending command to server");
 }
Exemple #8
0
 public static void SendCommandToServer(string command, long targetOid)
 {
     CommandMessage commandMessage = new CommandMessage();
     commandMessage.ObjectId = targetOid;
     commandMessage.Command = command;
     AtavismNetworkHelper.Instance.SendMessage(commandMessage);
     AtavismLogger.LogDebugMessage("Sending command to server");
 }
Exemple #9
0
        public Desire(CommandMessage msg, MessageId id, Action<MqttCommand> fulfilled)
        {
            if (fulfilled == null)
            {
                throw new ArgumentNullException("fulfilled", "The fulfilled action cannot be null");
            }

            Message = msg;
            MessageId = id;
            _fulfilled = fulfilled;
        }
Exemple #10
0
        internal bool TryGetAndRemove(CommandMessage commandMessage, MessageId messageId, out Desire desire)
        {
            int key = GetKeyFrom(commandMessage, messageId);
            if (_desires.TryGetValue(key, out desire))
            {
                _desires.Remove(key);
                return true;
            }

            return false;
        }
Exemple #11
0
        public string CommandString(CommandMessage cmd)
        {
            switch (cmd)
            {
                case CommandMessage.StartSnap:
                    return "StartSnap";

                case CommandMessage.GoHome:
                    return "GoHome";

                case CommandMessage.StopReturn:
                    return "StopReturn";

                default:
                    return "null";

            }
        }
        public void HandleCameraCommand( CommandMessage msg )
        {
            if ( !Enabled )
            {
                return;
            }
            switch ( ( Commands )msg.CommandId )
            {
                case Commands.Zoom :
                {
                    ( ( SphereCamera )Camera ).Zoom = ( ( ScalarCommandMessage )msg ).Value;
                    break;
                }
                case Commands.Pan :
                {
                    CursorCommandMessage cursorMsg = ( CursorCommandMessage )msg;
                    float deltaX = cursorMsg.X - cursorMsg.LastX;
                    float deltaY = cursorMsg.Y - cursorMsg.LastY;

                    SphereCamera camera = ( ( SphereCamera )Camera );

                    Point3 newLookAt = camera.LookAt;

                    newLookAt += camera.Frame.XAxis * deltaX;
                    newLookAt += camera.Frame.YAxis * deltaY;

                    camera.LookAt = newLookAt;
                    break;
                }
                case Commands.Rotate :
                {
                    CursorCommandMessage cursorMsg = ( CursorCommandMessage )msg;
                    float deltaX = cursorMsg.X - cursorMsg.LastX;
                    float deltaY = cursorMsg.Y - cursorMsg.LastY;

                    SphereCamera camera = ( ( SphereCamera )Camera );

                    camera.S += deltaX * 0.01f;
                    camera.T -= deltaY * 0.01f;

                    break;
                }
            }
        }
        public void HandleCameraCommand( CommandMessage msg )
        {
            switch ( ( Commands )msg.CommandId )
            {
                case Commands.Zoom :
                    {
                        m_Camera.Zoom = ( ( ScalarCommandMessage )msg ).Value;
                        break;
                    }
                case Commands.Rotate :
                    {
                        CursorCommandMessage cursorMsg = ( CursorCommandMessage )msg;
                        float deltaX = cursorMsg.X - cursorMsg.LastX;
                        float deltaY = cursorMsg.Y - cursorMsg.LastY;

                        m_Camera.S += deltaX * 0.01f;
                        m_Camera.T -= deltaY * 0.01f;

                        break;
                    }
            }
        }
Exemple #14
0
        private void GenerateCommandMessages()
        {
            commandTimer = new System.Threading.Timer((st) =>
            {
                var commandCorrId = CombGuid.Generate();

                var cmd = new CommandMessage
                {
                    CorrelationId = commandCorrId,
                    IssuingPrincipal = "CMon",
                    MessageVersion = 1,
                    TargetNodeApplication = "",
                    TargetNodeId = "",
                    Command = "Increase power",
                    Parameters = "All units"
                };
                Console.WriteLine("Sending command: " + cmd.ToString());

                Bus.Publish(cmd, x => x.SetResponseAddress(Bus.Endpoint.Address.Uri.ToString()));

            }, null, 15000, 3000);
        }
Exemple #15
0
        protected Task WaitFor(NamedConnection connection, ushort messageId, CommandMessage mustBeType)
        {
            ManualResetEvent available = new ManualResetEvent(false);

            Action<MqttCommand> ready = (cmd) =>
                {
                    if (cmd.CommandMessage != mustBeType)
                    {
                        throw new ProtocolException(
                            string.Format("ERROR: Expected {0} for message ID {1} but received {2}",
                            mustBeType, messageId, cmd.CommandMessage));
                    }

                    available.Set();
                };

            return Task.Factory.StartNew(() =>
                {
                    connection.Desire(messageId, ready);
                    available.WaitOne();
                }, TaskCreationOptions.LongRunning);
        }
Exemple #16
0
        public virtual Task Consumed(CommandMessage last)
        {
            var msg = last as SqlCommandMessage;
            if(msg == null)
                return TplHelper.Empty;

            const string sql = "delete SheepJaxMessages where ClientId=@clientId and timestamp<@timestamp";
            var dbTask =_connectionFactory().WithinTransaction(tx =>
                TplHelper.Using(new SqlCommand(sql, tx.Connection, tx)
                {
                    Parameters = {
                                    new SqlParameter("clientId", msg.ClientId),
                                    new SqlParameter("timestamp", msg.Timestamp)}
                }
                , cmd=> cmd.ExecuteNonQueryAsync().Finally(_=> tx.Commit())
                )
            ).Catch(_logger);

            using (_cacheLock.BeginUpgradeableReadLock())
            {
                var node = _cache.Last;
                while (node != null && node.Value != last)
                    node = node.Previous;

                using (_cacheLock.BeginWriteLock())
                {
                    while (node != null)
                    {
                        var previousNode = node.Previous;
                        while (previousNode != null && previousNode.Value.ClientId != node.Value.ClientId)
                            previousNode = previousNode.Previous;

                        node.List.Remove(node);
                        node = previousNode;
                    }
                }
            }
            return dbTask;
        }
        public CommandModule()
        {
            For<CreateTShirtV1>()
                .Handle((_, __) => { throw new NotSupportedException(); }); // 2. No longer support V1

            var createTShirtV3Handler = For<CreateTShirtV3>() // 3. Here we keep a reference to the V3 handler...
                .Handle((commandMessage, ct) => Task.FromResult(0));

            For<CreateTShirtV2>() 
                .Handle((commandMessage, ct) =>
                {
                    var command = new CreateTShirtV3
                    {
                        Name = commandMessage.Command.Name,
                        Sizes = commandMessage.Command.Sizes,
                        Colors = new []{ "Black" }
                    };
                    var upconvertedCommand = new CommandMessage<CreateTShirtV3>(
                        commandMessage.CommandId,
                        command,
                        commandMessage.Metadata);
                    return createTShirtV3Handler(upconvertedCommand, ct); // 4. ... and invoke it here
                });
        }
Exemple #18
0
        public async Task ImportHouseNumberStatusFromCrab(Func <IAddresses> getAddresses, CommandMessage <ImportHouseNumberStatusFromCrab> message, CancellationToken ct)
        {
            var addresses = getAddresses();
            var addressId = AddressId.CreateFor(message.Command.HouseNumberId);
            var address   = await addresses.GetAsync(addressId, ct);

            ImportHouseNumberStatusFromCrab(address, message.Command);
        }
Exemple #19
0
 public FixedHeader(CommandMessage message)
 {
     Message = message;
 }
Exemple #20
0
 /// <summary>
 /// M_Menu_Video_f
 /// </summary>
 private void Menu_Video_f(CommandMessage msg)
 {
     MenuBase.VideoMenuInstance.Show(this.Host);
 }
Exemple #21
0
 public TransMessage(CommandMessage command, Object data, int structureId)
 {
     this.Command = command;
     this.Data = data;
     this.StructureId = structureId;
 }
 public bool notEquals(CommandMessage value)
 {
     return !this.isEqual(value);
 }
 public void Send(CommandMessage message, string path)
 {
     Send(message, Encoding.Unicode.GetBytes(path + '\0'));
 }
Exemple #24
0
        public void CommandMessageCallsCommandTest()
        {
            // listen
            NetworkServer.Listen(1);
            Assert.That(NetworkServer.connections.Count, Is.EqualTo(0));

            // add connection
            LocalConnectionToClient connection = new LocalConnectionToClient();

            connection.connectionToServer = new LocalConnectionToServer();
            NetworkServer.AddConnection(connection);

            // set as authenticated, otherwise removeplayer is rejected
            connection.isAuthenticated = true;

            // add an identity with two networkbehaviour components
            GameObject      go       = new GameObject();
            NetworkIdentity identity = go.AddComponent <NetworkIdentity>();

            identity.netId = 42;
            // for authority check
            identity.connectionToClient = connection;
            CommandTestNetworkBehaviour comp0 = go.AddComponent <CommandTestNetworkBehaviour>();

            Assert.That(comp0.called, Is.EqualTo(0));
            CommandTestNetworkBehaviour comp1 = go.AddComponent <CommandTestNetworkBehaviour>();

            Assert.That(comp1.called, Is.EqualTo(0));
            connection.identity = identity;

            // register the command delegate, otherwise it's not found
            int registeredHash = RemoteCallHelper.RegisterDelegate(typeof(CommandTestNetworkBehaviour),
                                                                   nameof(CommandTestNetworkBehaviour.CommandGenerated),
                                                                   MirrorInvokeType.Command,
                                                                   CommandTestNetworkBehaviour.CommandGenerated,
                                                                   true);

            // identity needs to be in spawned dict, otherwise command handler
            // won't find it
            NetworkIdentity.spawned[identity.netId] = identity;

            // serialize a removeplayer message into an arraysegment
            CommandMessage message = new CommandMessage
            {
                componentIndex = 0,
                functionHash   = RemoteCallHelper.GetMethodHash(typeof(CommandTestNetworkBehaviour), nameof(CommandTestNetworkBehaviour.CommandGenerated)),
                netId          = identity.netId,
                payload        = new ArraySegment <byte>(new byte[0])
            };
            NetworkWriter writer = new NetworkWriter();

            MessagePacking.Pack(message, writer);
            ArraySegment <byte> segment = writer.ToArraySegment();

            // call transport.OnDataReceived with the message
            // -> calls NetworkServer.OnRemovePlayerMessage
            //    -> destroys conn.identity and sets it to null
            transport.OnServerDataReceived.Invoke(0, segment, 0);

            // was the command called in the first component, not in the second one?
            Assert.That(comp0.called, Is.EqualTo(1));
            Assert.That(comp1.called, Is.EqualTo(0));

            //  send another command for the second component
            comp0.called           = 0;
            message.componentIndex = 1;
            writer = new NetworkWriter();
            MessagePacking.Pack(message, writer);
            segment = writer.ToArraySegment();
            transport.OnServerDataReceived.Invoke(0, segment, 0);

            // was the command called in the second component, not in the first one?
            Assert.That(comp0.called, Is.EqualTo(0));
            Assert.That(comp1.called, Is.EqualTo(1));

            // sending a command without authority should fail
            // (= if connectionToClient is not what we received the data on)
            // set wrong authority
            identity.connectionToClient = new LocalConnectionToClient();
            comp0.called = 0;
            comp1.called = 0;
            transport.OnServerDataReceived.Invoke(0, segment, 0);
            Assert.That(comp0.called, Is.EqualTo(0));
            Assert.That(comp1.called, Is.EqualTo(0));
            // restore authority
            identity.connectionToClient = connection;

            // sending a component with wrong netId should fail
            // wrong netid
            message.netId += 1;
            writer         = new NetworkWriter();
            // need to serialize the message again with wrong netid
            MessagePacking.Pack(message, writer);
            ArraySegment <byte> segmentWrongNetId = writer.ToArraySegment();

            comp0.called = 0;
            comp1.called = 0;
            transport.OnServerDataReceived.Invoke(0, segmentWrongNetId, 0);
            Assert.That(comp0.called, Is.EqualTo(0));
            Assert.That(comp1.called, Is.EqualTo(0));

            // clean up
            NetworkIdentity.spawned.Clear();
            RemoteCallHelper.RemoveDelegate(registeredHash);
            NetworkServer.Shutdown();
            // destroy the test gameobject AFTER server was stopped.
            // otherwise isServer is true in OnDestroy, which means it would try
            // to call Destroy(go). but we need to use DestroyImmediate in
            // Editor
            GameObject.DestroyImmediate(go);
        }
 public void setCommandMessage(CommandMessage value)
 {
     m_CommandMessage = value;
     setParentPresenceVector();
 }
        public static void AddTranslationEntry(CommandMessage commandMessage,
                                               Message replyMessage)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId ==
                                 commandMessage.Message.From.Id &&
                                 x.Level == Models.Operator.Levels.Super) == null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                Manager.BotClient.SendTextMessageAsync(
                    chatId: CacheData.ControlChatId,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "User *{0}:{1}* tried to use command AddTranslationEntry.",
                        replyMessage.From.Id,
                        replyMessage.From.Username)
                    );
                return;
            }

            string[] parameters = commandMessage.Value.Split('|');
            if (parameters.Length != 2)
            {
                CommandQueueManager.DenqueueMessage(commandMessage);
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_invalid_parameters"),
                    ReplyMarkup      = new ReplyKeyboardRemove()
                    {
                        Selective = true
                    }
                });
            }
            string languageId = parameters[0];
            string keyId      = parameters[1];

            BusinessLogic.TranslationLogic translationLogic = new BusinessLogic.TranslationLogic();
            Entry translationEntry = translationLogic.AddEntry(
                languageId, keyId,
                replyMessage.Text, replyMessage.From.Id);

            if (translationEntry == null)
            {
                CommandQueueManager.DenqueueMessage(commandMessage);
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    ParseMode        = ParseMode.Markdown,
                    Text             = "*Error* adding translation entry.\nCheck internal logs.",
                    ReplyMarkup      = new ReplyKeyboardRemove()
                    {
                        Selective = true
                    }
                });
                return;
            }

            CommandQueueManager.DenqueueMessage(commandMessage);
            MessageQueueManager.EnqueueMessage(
                new Models.ChatMessage()
            {
                Timestamp        = DateTime.UtcNow,
                Chat             = replyMessage.Chat,
                ReplyToMessageId = replyMessage.MessageId,
                ParseMode        = ParseMode.Markdown,
                Text             = "*OK!*\nTranslation added successfully!\nRemember to reload them manually!",
                ReplyMarkup      = new ReplyKeyboardRemove()
                {
                    Selective = true
                }
            });
        }
        public void Execute(CallbackQuery callbackQuery)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId == callbackQuery.From.Id &&
                                 x.Level == Models.Operator.Levels.Super) == null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = callbackQuery.Message.Chat,
                    ReplyToMessageId = callbackQuery.Message.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                Manager.BotClient.SendTextMessageAsync(
                    chatId: CacheData.ControlChatId,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "*[Report]*\n" +
                        "⚠️ Non operator tried to use /addtranslation\n" +
                        "\n*Chat:* {0}" +
                        "\n*ChatId:* {1}" +
                        "\n*UserId:* {2}" +
                        "\n\n*hash_code:* #UB{3}-{4}",
                        callbackQuery.Message.Chat.Title,
                        callbackQuery.Message.Chat.Id,
                        callbackQuery.From.Id,
                        callbackQuery.Message.Chat.Id.ToString().Replace("-", ""),
                        Guid.NewGuid())
                    );
                return;
            }

            string data    = callbackQuery.Data.Replace("/AddTranslation ", "");
            string command = data.Split(':')[0];
            string value   = data.Split(':')[1];

            if (command == "language")
            {
                Manager.BotClient.DeleteMessageAsync(
                    callbackQuery.Message.Chat,
                    callbackQuery.Message.MessageId);
                CommandMessage commandMessage = new CommandMessage()
                {
                    Command   = "AddTranslationKey",
                    Value     = value,
                    Message   = callbackQuery.Message,
                    Timestamp = DateTime.UtcNow
                };
                CommandQueueManager.EnqueueMessage(commandMessage);

                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = callbackQuery.Message.Chat,
                    ReplyToMessageId = callbackQuery.Message.ReplyToMessage.MessageId,
                    ParseMode        = ParseMode.Markdown,
                    Text             = $"*[ADMIN] [r:{callbackQuery.Message.MessageId}]*\nDeclare KeyId:",
                    ReplyMarkup      = new ForceReplyMarkup()
                    {
                        Selective = true
                    }
                });
            }
        }
        public static void AddTranslationKey(CommandMessage commandMessage,
                                             Message replyMessage)
        {
            if (CacheData.Operators
                .SingleOrDefault(x => x.TelegramUserId ==
                                 commandMessage.Message.ReplyToMessage.From.Id &&
                                 x.Level == Models.Operator.Levels.Super) == null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    Text             = CacheData.GetTranslation("en", "error_not_auth_command")
                });
                Manager.BotClient.SendTextMessageAsync(
                    chatId: CacheData.ControlChatId,
                    parseMode: ParseMode.Markdown,
                    text: String.Format(
                        "User *{0}:{1}* tried to use command AddTranslationKey.",
                        replyMessage.From.Id,
                        replyMessage.From.Username),
                    replyMarkup: new ReplyKeyboardRemove()
                {
                    Selective = true
                }
                    );
                return;
            }

            CommandQueueManager.DenqueueMessage(commandMessage);

            var regexItem = new Regex("^[a-zA-Z0-9_]*$");

            if (!regexItem.IsMatch(replyMessage.Text.Trim()))
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    ParseMode        = ParseMode.Markdown,
                    Text             = "Error: translation key cannot contain space and/or special chars.\n"
                                       + "Start again the process.",
                    ReplyMarkup = new ReplyKeyboardRemove()
                    {
                        Selective = true
                    }
                });
                return;
            }

            BusinessLogic.TranslationLogic translationLogic = new BusinessLogic.TranslationLogic();
            Key translationKey = translationLogic.GetKeyById(replyMessage.Text.Trim());

            if (translationKey == null)
            {
                translationKey = translationLogic.AddKey(
                    replyMessage.Text.Trim(),
                    replyMessage.From.Id);
            }

            if (translationKey == null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    ParseMode        = ParseMode.Markdown,
                    Text             = "*Error* adding translation key.\nCheck internal logs.",
                    ReplyMarkup      = new ReplyKeyboardRemove()
                    {
                        Selective = true
                    }
                });
                return;
            }

            Entry entryExists = translationLogic.GetEntryById(commandMessage.Value, translationKey.KeyId);

            if (entryExists != null)
            {
                MessageQueueManager.EnqueueMessage(
                    new Models.ChatMessage()
                {
                    Timestamp        = DateTime.UtcNow,
                    Chat             = replyMessage.Chat,
                    ReplyToMessageId = replyMessage.MessageId,
                    ParseMode        = ParseMode.Markdown,
                    Text             = $"*Error*\n {commandMessage.Value} translation for key `{translationKey.KeyId}` already exists!",
                    ReplyMarkup      = new ReplyKeyboardRemove()
                    {
                        Selective = true
                    }
                });
                return;
            }

            CommandMessage newCommandMessage = new CommandMessage()
            {
                Command   = "AddTranslationEntry",
                Value     = commandMessage.Value + "|" + translationKey.KeyId,
                Message   = replyMessage,
                Timestamp = DateTime.UtcNow
            };

            CommandQueueManager.EnqueueMessage(newCommandMessage);

            MessageQueueManager.EnqueueMessage(
                new Models.ChatMessage()
            {
                Timestamp        = DateTime.UtcNow,
                Chat             = replyMessage.Chat,
                ReplyToMessageId = replyMessage.MessageId,
                ParseMode        = ParseMode.Markdown,
                Text             = $"*[ADMIN] [r:{replyMessage.MessageId}]*\nType translation for " +
                                   $"`{translationKey.KeyId}` in `{CacheData.Languages[commandMessage.Value].Name}`:",
                ReplyMarkup = new ForceReplyMarkup()
                {
                    Selective = true
                }
            });
        }
Exemple #29
0
        public async Task <AcknowledgeMessageExt> InvokeAckAsync(int invokeId, string method, CommandMessage arg)
        {
            //TODO: this is very bad
            //this.invokeId = invokeId;

            var invoke = new InvokeAmf0
            {
                MethodCall = new Method(method, new object[] { arg }),
                InvokeId   = invokeId
            };

            return(await QueueCommandAsTask(invoke, 3, 0));
        }
Exemple #30
0
        public override object ServiceMessage(IMessage message)
        {
            CommandMessage commandMessage = message as CommandMessage;

            if (commandMessage != null)
            {
                //Sub/unsub handled by base class
                return(base.ServiceMessage(commandMessage));
            }
            else
            {
                AsyncMessage responseMessage = null;
                DataMessage  dataMessage     = message as DataMessage;

                DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination;
                if (dataDestination.SubscriptionManager.GetSubscriber(dataMessage.clientId as string) == null)
                {
                    //Subscribe here as DS doesn't send a separate subscribe command
                    CommandMessage commandMessageSubscribe = new CommandMessage();
                    commandMessageSubscribe.destination = dataDestination.Id;
                    commandMessageSubscribe.operation   = CommandMessage.SubscribeOperation;
                    commandMessageSubscribe.clientId    = dataMessage.clientId as string;
                    string endpointId = dataMessage.GetHeader(MessageBase.EndpointHeader) as string;
                    commandMessageSubscribe.headers[MessageBase.EndpointHeader] = endpointId;
                    string flexClientIdHeader = dataMessage.GetHeader(MessageBase.FlexClientIdHeader) as string;
                    if (flexClientIdHeader != null)
                    {
                        commandMessageSubscribe.headers[MessageBase.FlexClientIdHeader] = flexClientIdHeader;
                    }
                    IEndpoint endpoint = GetMessageBroker().GetEndpoint(endpointId);
                    endpoint.ServiceMessage(commandMessageSubscribe);//route through the endpoint again
                    //base.ServiceMessage(commandMessageSubscribe);
                }

                switch (dataMessage.operation)
                {
                case DataMessage.FillOperation:
                    responseMessage = ExecuteFillOperation(message);
                    break;

                case DataMessage.GetOperation:
                    responseMessage = ExecuteGetOperation(message);
                    break;

                case DataMessage.BatchedOperation:
                case DataMessage.MultiBatchOperation:
                case DataMessage.TransactedOperation:
                    responseMessage = ExecuteMultiBatchOperation(message);
                    break;

                case DataMessage.PageItemsOperation:
                    responseMessage = ExecutePageItemsOperation(message);
                    break;

                case DataMessage.PageOperation:
                    responseMessage = ExecutePageOperation(message);
                    break;

                case DataMessage.ReleaseCollectionOperation:
                    responseMessage = ExecuteReleaseCollectionOperation(message);
                    break;

                case DataMessage.GetSequenceIdOperation:
                    responseMessage = ExecuteGetSequenceIdOperation(message);
                    break;

                case DataMessage.ReleaseItemOperation:
                    responseMessage = ExecuteReleaseItemOperation(message);
                    break;

                default:
                    if (log.IsErrorEnabled)
                    {
                        log.Error(__Res.GetString(__Res.DataService_Unknown, dataMessage.operation));
                    }

                    responseMessage = new AcknowledgeMessage();
                    break;
                }
                responseMessage.clientId      = message.clientId;
                responseMessage.correlationId = message.messageId;
                //Dump();
                return(responseMessage);
            }
        }
Exemple #31
0
        public async Task ImportSubaddressMailCantonFromCrab(Func <IAddresses> getAddresses, CommandMessage <ImportSubaddressMailCantonFromCrab> message, CancellationToken ct)
        {
            var addresses = getAddresses();
            var addressId = AddressId.CreateFor(message.Command.SubaddressId);
            var address   = await addresses.GetAsync(addressId, ct);

            ImportSubaddressMailCantonFromCrab(address, message.Command);
        }
Exemple #32
0
        // CL_PlayDemo_f
        //
        // play [demoname]
        private void PlayDemo_f(CommandMessage msg)
        {
            if (msg.Source != CommandSource.Command)
            {
                return;
            }

            var c = msg.Parameters != null ? msg.Parameters.Length : 0;

            if (c != 1)
            {
                Host.Console.Print("play <demoname> : plays a demo\n");
                return;
            }

            //
            // disconnect from server
            //
            Disconnect( );

            //
            // open the demo file
            //
            var name = Path.ChangeExtension(msg.Parameters[0], ".dem");

            Host.Console.Print("Playing demo from {0}.\n", name);
            if (cls.demofile != null)
            {
                cls.demofile.Dispose( );
            }
            DisposableWrapper <BinaryReader> reader;

            FileSystem.FOpenFile(name, out reader);
            cls.demofile = reader;
            if (cls.demofile == null)
            {
                Host.Console.Print("ERROR: couldn't open.\n");
                cls.demonum = -1;               // stop demo loop
                return;
            }

            cls.demoplayback = true;
            cls.state        = cactive_t.ca_connected;
            cls.forcetrack   = 0;

            var s = reader.Object;

            c = 0;
            var neg = false;

            while (true)
            {
                c = s.ReadByte( );
                if (c == '\n')
                {
                    break;
                }

                if (c == '-')
                {
                    neg = true;
                }
                else
                {
                    cls.forcetrack = cls.forcetrack * 10 + (c - '0');
                }
            }

            if (neg)
            {
                cls.forcetrack = -cls.forcetrack;
            }
            // ZOID, fscanf is evil
            //	fscanf (cls.demofile, "%i\n", &cls.forcetrack);
        }
 public CreateEventRec()
 {
     m_parent = null;
     m_RequestID = 0;
     m_MaximumAllowedDuration = 0;
     m_CommandMessage = new CommandMessage();
     m_CommandMessage.setParent(this);
 }
Exemple #34
0
        /// <summary>
        /// CL_Record_f
        /// record <demoname> <map> [cd track]
        /// </summary>
        private void Record_f(CommandMessage msg)
        {
            if (msg.Source != CommandSource.Command)
            {
                return;
            }

            var c = msg.Parameters != null ? msg.Parameters.Length : 0;

            if (c != 1 && c != 2 && c != 3)
            {
                Host.Console.Print("record <demoname> [<map> [cd track]]\n");
                return;
            }

            if (msg.Parameters[0].Contains(".."))
            {
                Host.Console.Print("Relative pathnames are not allowed.\n");
                return;
            }

            if (c == 2 && cls.state == cactive_t.ca_connected)
            {
                Host.Console.Print("Can not record - already connected to server\nClient demo recording must be started before connecting\n");
                return;
            }

            // write the forced cd track number, or -1
            Int32 track;

            if (c == 3)
            {
                track = MathLib.atoi(msg.Parameters[2]);
                Host.Console.Print("Forcing CD track to {0}\n", track);
            }
            else
            {
                track = -1;
            }

            var name = Path.Combine(FileSystem.GameDir, msg.Parameters[0]);

            //
            // start the map up
            //
            if (c > 1)
            {
                Host.Commands.ExecuteString(String.Format("map {0}", msg.Parameters[1]), CommandSource.Command);
            }

            //
            // open the demo file
            //
            name = Path.ChangeExtension(name, ".dem");

            Host.Console.Print("recording to {0}.\n", name);
            var fs = FileSystem.OpenWrite(name, true);

            if (fs == null)
            {
                Host.Console.Print("ERROR: couldn't open.\n");
                return;
            }
            var writer = new BinaryWriter(fs, Encoding.ASCII);

            cls.demofile   = new DisposableWrapper <BinaryWriter>(writer, true);
            cls.forcetrack = track;
            var tmp = Encoding.ASCII.GetBytes(cls.forcetrack.ToString( ));

            writer.Write(tmp);
            writer.Write('\n');
            cls.demorecording = true;
        }
                    public CreateCommandEvent.Body.CreateEventRec.CommandMessage setCommandMessage(CommandMessage value)
                    {
                        this.m_Length = value.m_Length;

                        m_Data = null;

                        if (m_Length > 0)
                        {
                        m_Data = new byte[(int)m_Length];
                        this.m_Data = value.m_Data;
                        }

                        return this;
                    }
        object ProcessMessage(AMFMessage amfMessage)
        {
            // Apply AMF-based operation selector

            /*
             * Dictionary<string, string> operationNameDictionary = new Dictionary<string, string>();
             * foreach (OperationDescription operation in _endpoint.Contract.Operations)
             * {
             *  try
             *  {
             *      operationNameDictionary.Add(operation.Name.ToLower(), operation.Name);
             *  }
             *  catch (ArgumentException)
             *  {
             *      throw new Exception(String.Format("The specified contract cannot be used with case insensitive URI dispatch because there is more than one operation named {0}", operation.Name));
             *  }
             * }
             */

            //SessionMode, CallbackContract, ProtectionLevel

            AMFMessage output = new AMFMessage(amfMessage.Version);

            for (int i = 0; i < amfMessage.BodyCount; i++)
            {
                AMFBody amfBody = amfMessage.GetBodyAt(i);
                object  content = amfBody.Content;
                if (content is IList)
                {
                    content = (content as IList)[0];
                }
                IMessage message = content as IMessage;
                if (message != null)
                {
                    //WCF should not assign client id for Flex...
                    if (message.clientId == null)
                    {
                        message.clientId = Guid.NewGuid().ToString("D");
                    }

                    //IMessage resultMessage = _endpoint.ServiceMessage(message);
                    IMessage       responseMessage = null;
                    CommandMessage commandMessage  = message as CommandMessage;
                    if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation)
                    {
                        responseMessage      = new AcknowledgeMessage();
                        responseMessage.body = true;
                    }
                    else
                    {
                        RemotingMessage remotingMessage = message as RemotingMessage;
                        string          operation       = remotingMessage.operation;
                        //TODO: you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute
                        string source            = remotingMessage.source;
                        Type   serviceType       = TypeHelper.Locate(source);
                        Type   contractInterface = serviceType.GetInterface(_endpoint.Contract.ContractType.FullName);
                        //WCF also lets you apply the ServiceContract attribute directly on the service class. Avoid using it.
                        //ServiceContractAttribute serviceContractAttribute = ReflectionUtils.GetAttribute(typeof(ServiceContractAttribute), type, true) as ServiceContractAttribute;
                        if (contractInterface != null)
                        {
                            object     instance      = Activator.CreateInstance(serviceType);
                            IList      parameterList = remotingMessage.body as IList;
                            MethodInfo mi            = MethodHandler.GetMethod(contractInterface, operation, parameterList, false, false);
                            if (mi != null)
                            {
                                //TODO OperationContract attribute to alias it to a different publicly exposed name
                                OperationContractAttribute operationContractAttribute = ReflectionUtils.GetAttribute(typeof(OperationContractAttribute), mi, true) as OperationContractAttribute;
                                if (operationContractAttribute != null)
                                {
                                    ParameterInfo[] parameterInfos = mi.GetParameters();
                                    object[]        args           = new object[parameterInfos.Length];
                                    parameterList.CopyTo(args, 0);
                                    TypeHelper.NarrowValues(args, parameterInfos);
                                    try
                                    {
                                        object result = mi.Invoke(instance, args);
                                        if (!(result is IMessage))
                                        {
                                            responseMessage      = new AcknowledgeMessage();
                                            responseMessage.body = result;
                                        }
                                        else
                                        {
                                            responseMessage = result as IMessage;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        // Lets FluorineFx return ErrorMessages in case the method invocation fails with an exception
                                        responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, e.InnerException);
                                    }
                                }
                                else
                                {
                                    responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of a service contract"));
                                }
                            }
                            else
                            {
                                responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of a service contract"));
                            }
                        }
                        else
                        {
                            responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException(String.Format("The specified contract {0} cannot be used with the source named {1} and operation named {2}", _endpoint.Contract.ContractType.Name, source, operation)));
                        }
                    }

                    if (responseMessage is AsyncMessage)
                    {
                        ((AsyncMessage)responseMessage).correlationId = message.messageId;
                    }
                    responseMessage.destination = message.destination;
                    responseMessage.clientId    = message.clientId;

                    ResponseBody responseBody = new ResponseBody(amfBody, responseMessage);
                    output.AddBody(responseBody);
                }
            }
            return(output);
        }
Exemple #37
0
 protected Task<MqttCommand> WaitFor(CommandMessage message, MessageId messageId, TimeSpan timeout)
 {
     return _manager.WaitForCommand(message, messageId, timeout).Await();
 }
Exemple #38
0
        public override void ParseCommand(CommandMessage command)
        {
            Command foundCommand = Commands.Find(c => c.Triggers.Contains(command.Command));

            switch (foundCommand.Name)
            {
            // Privilege Mode Commands
            case "Founder":
                ModifyUserPrivilege(true, command, ChannelMode.q);
                break;

            case "Remove Founder":
                ModifyUserPrivilege(false, command, ChannelMode.q);
                break;

            case "SOP":
                ModifyUserPrivilege(true, command, ChannelMode.a);
                break;

            case "Remove SOP":
                ModifyUserPrivilege(false, command, ChannelMode.a);
                break;

            case "OP":
                ModifyUserPrivilege(true, command, ChannelMode.o);
                break;

            case "Remove OP":
                ModifyUserPrivilege(false, command, ChannelMode.o);
                break;

            case "HOP":
                ModifyUserPrivilege(true, command, ChannelMode.h);
                break;

            case "Remove HOP":
                ModifyUserPrivilege(false, command, ChannelMode.h);
                break;

            case "Voice":
                ModifyUserPrivilege(true, command, ChannelMode.v);
                break;

            case "Remove Voice":
                ModifyUserPrivilege(false, command, ChannelMode.v);
                break;

            // Auto Privilege Management
            case "ASOP":
                ModifyAutoUserPrivilege("SOP", command, ChannelMode.a);
                break;

            case "AOP":
                ModifyAutoUserPrivilege("AOP", command, ChannelMode.o);
                break;

            case "AHOP":
                ModifyAutoUserPrivilege("HOP", command, ChannelMode.h);
                break;

            case "AVoice":
                ModifyAutoUserPrivilege("VOP", command, ChannelMode.v);
                break;

            // Channel Moderation
            case "Mode":
                ModifyChannelModes(foundCommand, command);
                break;

            case "Topic":
                ModifyChannelTopic(foundCommand, command);
                break;

            case "Invite":
                InviteNick(foundCommand, command);
                break;

            case "Auto Ban":
                AutoBan(foundCommand, command);
                break;

            case "Ban":
                BanNick(true, foundCommand, command);
                break;

            case "UnBan":
                BanNick(false, foundCommand, command);
                break;

            case "Kick Ban":
                BanNick(true, foundCommand, command);
                KickNick(foundCommand, command);
                break;

            case "Timed Ban":
                TimedBan(foundCommand, command);
                break;

            case "Timed Kick Ban":
                TimedBan(foundCommand, command);
                KickNick(foundCommand, command);
                break;

            case "Kick":
                KickNick(foundCommand, command);
                break;

            case "Kick Self":
                KickSelf(command);
                break;

            case "Clear":
                ClearChannel(foundCommand, command);
                break;

            case "Roll Call":
                string  channel      = command.Arguments.ContainsKey("Channel") ? command.Arguments["Channel"] : command.Location;
                Channel foundChannel = Bot.IRC.Channels.Find(chan => chan.Name == channel);
                if (foundChannel != null)
                {
                    string rollCall = string.Join(", ", foundChannel.Nicks.Select(nick => nick.Nickname));
                    Bot.IRC.Command.SendPrivateMessage(channel, "It's time for a Roll Call!");
                    Bot.IRC.Command.SendPrivateMessage(channel, rollCall);
                }
                else
                {
                    SendResponse(command.MessageType, command.Location, command.Nick.Nickname, string.Format("I am not in \u0002{0}\u0002", channel));
                }
                break;
            }
        }
Exemple #39
0
 /// <summary>
 /// M_Menu_Keys_f
 /// </summary>
 private void Menu_Keys_f(CommandMessage msg)
 {
     MenuBase.KeysMenuInstance.Show(this.Host);
 }
Exemple #40
0
        private void BanNick(bool set, Command curCommand, CommandMessage command)
        {
            string channel = command.Arguments.ContainsKey("Channel") ? command.Arguments["Channel"] : command.Location;

            if (Bot.CheckChannelAccess(channel, command.Nick.Nickname, curCommand.AllowedAccess) && Bot.CheckNickAccess(channel, command.Nick.Nickname, command.Arguments["Nickname"]))
            {
                string banMask = command.Arguments["Nickname"];
                if (!banMask.Contains("@") || !banMask.Contains("!"))
                {
                    string search = "SELECT `nickinfo`.`username`, `nickinfo`.`host`, `nicks`.`nickname` FROM `nickinfo` " +
                                    "INNER JOIN `nicks` " +
                                    "ON `nickinfo`.`nick_id` = `nicks`.`id` " +
                                    "INNER JOIN `servers` " +
                                    "ON `nicks`.`server_id` = `servers`.`id` " +
                                    "WHERE `servers`.`name` = {0} AND `nicks`.`nickname` = {1}";
                    List <Dictionary <string, object> > results = Bot.Database.Query(search, new object[] { Bot.ServerConfig.Name, banMask });

                    if (results.Any())
                    {
                        List <string> banMasks = new List <string>();
                        foreach (Dictionary <string, object> result in results)
                        {
                            var nickname = result["nickname"].ToString();
                            var host     = result["host"].ToString();
                            var username = result["username"].ToString();
                            if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(username))
                            {
                                banMask = string.Format("*!*{0}@{1}", username, host);
                            }
                            else if (!string.IsNullOrEmpty(host))
                            {
                                banMask = string.Format("*!*@{0}", host);
                            }
                            else if (!string.IsNullOrEmpty(username))
                            {
                                banMask = string.Format("{0}!*{1}@*", nickname, username);
                            }
                            else
                            {
                                banMask = string.Format("{0}!*@*", nickname);
                            }
                            banMasks.Add(banMask);
                        }
                        SetMode(set, channel, ChannelMode.b, banMasks);
                    }
                    else
                    {
                        SetMode(set, channel, ChannelMode.b, string.Format("{0}!*@*", banMask));
                    }
                }
                else
                {
                    SetMode(set, channel, ChannelMode.b, banMask);
                }
            }
            else
            {
                string banMessage = "ban";
                if (!set)
                {
                    banMessage = "unban";
                }
                string noAccessMessage = string.Format("You do not have access to {0} \u0002{1}\u000F on \u0002{2}\u000F.", banMessage, command.Arguments["Nickname"], channel);
                SendResponse(command.MessageType, command.Location, command.Nick.Nickname, noAccessMessage, true);
            }
        }
Exemple #41
0
        public async Task RequestPersistentLocalIdForCrabSubaddressId(Func <IAddresses> getAddresses, CommandMessage <RequestPersistentLocalIdForCrabSubaddressId> message, CancellationToken ct)
        {
            var addressId = AddressId.CreateFor(message.Command.SubaddressId);
            var address   = await getAddresses().GetAsync(addressId, ct);

            address.RequestPersistentLocalId(_persistentLocalIdGenerator);
        }
Exemple #42
0
        public async Task AssignPersistentLocalIdToAddress(Func <IAddresses> getAddresses, CommandMessage <AssignPersistentLocalIdToAddress> message, CancellationToken ct)
        {
            var addresses = getAddresses();
            var address   = await addresses.GetAsync(message.Command.AddressId, ct);

            address.AssignPersistentLocalId(
                message.Command.PersistentLocalId,
                new PersistentLocalIdAssignmentDate(Instant.FromDateTimeOffset(DateTimeOffset.Now)));
        }
Exemple #43
0
        public async Task AssignPersistentLocalIdForCrabSubaddressId(Func <IAddresses> getAddresses, CommandMessage <AssignPersistentLocalIdForCrabSubaddressId> message, CancellationToken ct)
        {
            var addressId = AddressId.CreateFor(message.Command.SubaddressId);
            var address   = await getAddresses().GetAsync(addressId, ct);

            address.AssignPersistentLocalId(
                message.Command.PersistentLocalId,
                message.Command.AssignmentDate);
        }
Exemple #44
0
 public ProtocolException(CommandMessage cmd, string message)
     : base(string.Format("Protocol Exception parsing command: {0}.  {1}", cmd.ToString(), message))
 {
 }
Exemple #45
0
        public async Task ImportHouseNumberSubaddressFromCrab(Func <IAddresses> getAddresses, CommandMessage <ImportHouseNumberSubaddressFromCrab> message, CancellationToken ct)
        {
            var addresses    = getAddresses();
            var addressId    = AddressId.CreateFor(message.Command.SubaddressId);
            var streetNameId = StreetNameId.CreateFor(message.Command.StreetNameId);
            var address      = await GetOrRegisterAddress(addresses, addressId, streetNameId, message.Command.HouseNumber, ct);

            if (!address.HasValue)
            {
                address = new Optional <Address>(
                    Address.Register(
                        new AddressId(addressId),
                        new StreetNameId(streetNameId),
                        message.Command.HouseNumber));

                addresses.Add(addressId, address.Value);
            }

            ImportHouseNumberSubaddressFromCrab(address.Value, message.Command);
        }
Exemple #46
0
 public ProtocolException(CommandMessage cmd)
     : base(string.Format("Protocol Exception parsing command: {0}", cmd.ToString()))
 {
 }
Exemple #47
0
       /// <summary>
       /// 开始接收后,取消接收
       /// </summary>
        private void CancelReceive()
        {
            ///处理取消接收后,界面的情况
            CompletReceive(TransferState.CanceledByMyself);

            ///通知发送方
            CommandMessage cm = new CommandMessage();
            cm.from = DataUtil.Member;
            cm.to = this.fm.to;
            cm.CommandType = MyCommandType.CanceledSendFile;
            cm.Guid = fm.Guid;
            DataUtil.Client.SendMesg(cm);
        }
Exemple #48
0
 /// <summary>
 /// M_Menu_Main_f
 /// </summary>
 private void Menu_Main_f(CommandMessage msg)
 {
     MenuBase.MainMenuInstance.Show(this.Host);
 }
Exemple #49
0
 public static void SendTargetedCommand(long objectId, string text)
 {
     CommandMessage message = new CommandMessage();
     message.ObjectId = objectId;
     message.Command = text;
     Client.Instance.NetworkHelper.SendMessage(message);
 }
Exemple #50
0
 /// <summary>
 /// M_Menu_Load_f
 /// </summary>
 /// <param name="msg"></param>
 private void Menu_Load_f(CommandMessage msg)
 {
     MenuBase.LoadMenuInstance.Show(this.Host);
 }
                public CreateEventRec(CreateEventRec value)
                {
                    /// Initiliaze the protected variables
                    m_parent = null;
                    m_RequestID = 0;
                    m_MaximumAllowedDuration = 0;
                    m_CommandMessage = new CommandMessage();
                    m_CommandMessage.setParent(this);

                    /// Copy the values
                    m_RequestID = value.m_RequestID;
                    m_MaximumAllowedDuration = value.m_MaximumAllowedDuration;
                    m_CommandMessage = value.getCommandMessage();
                }
Exemple #52
0
 /// <summary>
 /// M_Menu_Save_f
 /// </summary>
 /// <param name="msg"></param>
 private void Menu_Save_f(CommandMessage msg)
 {
     MenuBase.SaveMenuInstance.Show(this.Host);
 }
                public CreateCommandEvent.Body.CreateEventRec setCreateEventRec(CreateEventRec value)
                {
                    m_RequestID = value.m_RequestID;
                    m_MaximumAllowedDuration = value.m_MaximumAllowedDuration;
                    m_CommandMessage = value.getCommandMessage();

                    return this;
                }
Exemple #54
0
 /// <summary>
 /// M_Menu_MultiPlayer_f
 /// </summary>
 /// <param name="msg"></param>
 private void Menu_MultiPlayer_f(CommandMessage msg)
 {
     MenuBase.MultiPlayerMenuInstance.Show(this.Host);
 }
                    public bool isEqual(CommandMessage value)
                    {
                        if (this.m_Length != value.m_Length)
                        {
                        return false;
                        }

                        if ((this.m_Data != null) && (value.m_Data!= null))
                        {
                        for(int i = 0; i < value.m_Length; i++)
                        {
                            if (this.m_Data[i] != value.m_Data[i])
                            {
                                return false;
                            }
                        }
                        }
                        // This case should never be true since it should not be possible
                        // for the two variables to have equal lengths but one has no data.
                        // This check is placed here as a secondary check.
                        else if ((this.m_Data != null) || (value.m_Data != null))
                        {
                        return false;
                        }

                        return true;
                    }
Exemple #56
0
 /// <summary>
 /// M_Menu_Setup_f
 /// </summary>
 /// <param name="msg"></param>
 private void Menu_Setup_f(CommandMessage msg)
 {
     MenuBase.SetupMenuInstance.Show(this.Host);
 }
                    public CommandMessage(CommandMessage value)
                    {
                        /// Initiliaze the protected variables
                        m_parent = null;
                        m_Length = 0;
                        m_Data = null;

                        /// Copy the values
                        this.m_Length = value.m_Length;

                        m_Data = null;

                        if (m_Length > 0)
                        {
                        m_Data = new byte[(int)m_Length];
                        this.m_Data = value.m_Data;
                        }
                    }
Exemple #58
0
 /// <summary>
 /// M_Menu_Options_f
 /// </summary>
 /// <param name="msg"></param>
 private void Menu_Options_f(CommandMessage msg)
 {
     MenuBase.OptionsMenuInstance.Show(this.Host);
 }
        /// <summary>
        /// Call this method in order to send a message from your code into the message routing system.
        /// The message is routed to a service that is defined to handle messages of this type.
        /// Once the service is identified, the destination property of the message is used to find a destination configured for that service.
        /// The adapter defined for that destination is used to handle the message.
        /// </summary>
        /// <param name="message">The message to be routed to a service.</param>
        /// <param name="endpoint">This can identify the endpoint that is sending the message but it is currently not used so you may pass in null.</param>
        /// <returns>The result of the message routing.</returns>
        internal IMessage RouteMessage(IMessage message, IEndpoint endpoint)
        {
            IService service         = null;
            object   result          = null;
            IMessage responseMessage = null;

            if (log.IsDebugEnabled)
            {
                log.Debug(__Res.GetString(__Res.MessageBroker_RoutingMessage, message.ToString()));
            }

            CommandMessage commandMessage = message as CommandMessage;

            if (commandMessage != null && (commandMessage.operation == CommandMessage.LoginOperation || commandMessage.operation == CommandMessage.LogoutOperation))             //Login, Logout
            {
                try
                {
                    service         = GetService(AuthenticationService.ServiceId);
                    result          = service.ServiceMessage(commandMessage);
                    responseMessage = result as IMessage;
                }
                catch (UnauthorizedAccessException uae)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(uae.Message);
                    }
                    responseMessage = ErrorMessage.GetErrorMessage(message, uae);
                }
                catch (SecurityException exception)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug(exception.Message);
                    }
                    responseMessage = ErrorMessage.GetErrorMessage(message, exception);
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error(__Res.GetString(__Res.MessageBroker_RoutingError), exception);
                    }
                    responseMessage = ErrorMessage.GetErrorMessage(message, exception);
                }
            }
            else if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation)
            {
                responseMessage      = new AcknowledgeMessage();
                responseMessage.body = true;
            }
            else
            {
                //The only case when context is not set should be when one starts a new thread in the backend
                //if( FluorineContext.Current != null )
                //    FluorineContext.Current.RestorePrincipal(this.LoginCommand);
                _loginManager.RestorePrincipal();
                service = GetService(message);
                if (service != null)
                {
                    try
                    {
                        service.CheckSecurity(message);
                        result = service.ServiceMessage(message);
                    }
                    catch (UnauthorizedAccessException uae)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug(uae.Message);
                        }
                        result = ErrorMessage.GetErrorMessage(message, uae);
                    }
                    catch (SecurityException exception)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug(exception.Message);
                        }
                        result = ErrorMessage.GetErrorMessage(message, exception);
                    }
                    catch (ServiceException exception)
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.Debug(exception.Message);
                        }
                        result = ErrorMessage.GetErrorMessage(message, exception);
                    }
                    catch (Exception exception)
                    {
                        if (log.IsErrorEnabled)
                        {
                            log.Error(exception.Message, exception);
                        }
                        result = ErrorMessage.GetErrorMessage(message, exception);
                    }
                }
                else
                {
                    string msg = __Res.GetString(__Res.Destination_NotFound, message.destination);
                    if (log.IsErrorEnabled)
                    {
                        log.Error(msg);
                    }
                    result = ErrorMessage.GetErrorMessage(message, new FluorineException(msg));
                }
                if (!(result is IMessage))
                {
                    responseMessage      = new AcknowledgeMessage();
                    responseMessage.body = result;
                }
                else
                {
                    responseMessage = result as IMessage;
                }
            }

            if (responseMessage is AsyncMessage)
            {
                ((AsyncMessage)responseMessage).correlationId = message.messageId;
            }
            responseMessage.destination = message.destination;
            responseMessage.clientId    = message.clientId;

            //Debug
            if (message.HeaderExists(AMFHeader.DebugHeader))
            {
                log.Debug("MessageBroker processing debug header");
                ArrayList traceStack = NetDebug.GetTraceStack();
                responseMessage.SetHeader(AMFHeader.DebugHeader, traceStack.ToArray(typeof(object)) as object[]);
                NetDebug.Clear();
            }
            //The only case when we do not have context should be when the server side initiates a push
            if (FluorineContext.Current != null && FluorineContext.Current.Client != null)
            {
                responseMessage.SetHeader(MessageBase.FlexClientIdHeader, FluorineContext.Current.Client.Id);
            }

            if (log.IsDebugEnabled)
            {
                log.Debug(__Res.GetString(__Res.MessageBroker_Response, responseMessage.ToString()));
            }

            return(responseMessage);
        }
 /// <summary>
 /// Send a command asynchronously
 /// </summary>
 public virtual Task <CommandMessage> SendCommandAsync(CommandMessage request) =>
 Task.Run(() =>
 {