public void TestGetMapNames()
        {
            MapMessage msg = new MapMessage();

            msg.Body.SetBool("boolean", true);
            msg.Body.SetByte("byte", (byte)1);
            msg.Body["bytes1"] = new byte[1];
            msg.Body.SetChar("char", 'a');
            msg.Body.SetDouble("double", 1.5);
            msg.Body.SetFloat("float", 1.5f);
            msg.Body.SetInt("int", 1);
            msg.Body.SetLong("long", 1);
            msg.Body["object"] = "stringObj";
            msg.Body.SetShort("short", (short)1);
            msg.Body.SetString("string", "string");

            msg = (MapMessage)msg.Clone();

            ICollection mapNames = msg.Body.Keys;

            System.Collections.ArrayList mapNamesList = new System.Collections.ArrayList(mapNames);

            Assert.AreEqual(mapNamesList.Count, 11);
            Assert.IsTrue(mapNamesList.Contains("boolean"));
            Assert.IsTrue(mapNamesList.Contains("byte"));
            Assert.IsTrue(mapNamesList.Contains("bytes1"));
            Assert.IsTrue(mapNamesList.Contains("char"));
            Assert.IsTrue(mapNamesList.Contains("double"));
            Assert.IsTrue(mapNamesList.Contains("float"));
            Assert.IsTrue(mapNamesList.Contains("int"));
            Assert.IsTrue(mapNamesList.Contains("long"));
            Assert.IsTrue(mapNamesList.Contains("object"));
            Assert.IsTrue(mapNamesList.Contains("short"));
            Assert.IsTrue(mapNamesList.Contains("string"));
        }
        /// <summary>
        /// Envía un mensaje para el procesamiento asíncrono a una cola de Tibco para
        /// el procesamiento de distribuciones XBRL
        /// </summary>
        /// <param name="idDocumentoInstancia">Identificador del documento de instancia a procesar</param>
        /// <param name="idVersion">Versión del documento de instancia a procesar</param>
        /// <returns>El resultado de la operación de envío a  la cola de TIBCO</returns>
        public ResultadoOperacionDto EnviarSolicitudProcesarXBRL(long idDocumentoInstancia, long idVersion, int reintento = 0)
        {
            var resultado = new ResultadoOperacionDto();

            LogUtil.Info("Enviando mensaje a la cola para procesamiento asíncrono de documento: " + idDocumentoInstancia + ", Version:" + idVersion);
            try
            {
                EmsTemplate.SendWithDelegate(ColaDestino,
                                             delegate(ISession session)
                {
                    MapMessage message = session.CreateMapMessage();
                    message.SetLong(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_DOCUMENTO, idDocumentoInstancia);
                    message.SetLong(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_VERSION, idVersion);
                    message.SetInt(DistribucionDocumentoConstants.PARAM_MENSAJE_REINTENTO, reintento);
                    return(message);
                });
                resultado.Resultado = true;
                LogUtil.Info("Mensaje enviado a la cola para procesamiento asíncrono de documento: " + idDocumentoInstancia + ", Version:" + idVersion);
            }
            catch (Exception ex) {
                LogUtil.Error("Ocurrió un error al enviar mensaje a la cola de mensajes: " + ColaDestino + ": \n\r" + ex.StackTrace);
                resultado.Resultado = false;
                resultado.Mensaje   = "Ocurrió un error al enviar mensaje a la cola de mensajes: " + ColaDestino + ": " + ex.Message;
                resultado.Excepcion = ex.StackTrace;
                LogUtil.Error(resultado);
            }
            return(resultado);
        }
示例#3
0
    private void MessageReceived(IRemoteConnection sender, string message)
    {
        messageCount++;


        if (message.StartsWith(MessagePrefix.MAP))
        {
            MapMessage mapMessage = new MapMessage();
            mapMessage.DeserializeArguments(message.Remove(0, MessagePrefix.MAP.Length));
            MapMessages.Enqueue(mapMessage);
        }
        else if (message.StartsWith(MessagePrefix.BANK))
        {
            BankMessage bankMessage = new BankMessage();
            bankMessage.DeserializeArguments(message.Remove(0, MessagePrefix.BANK.Length));
            BankMessages.Enqueue(bankMessage);
        }
        else if (message.StartsWith(MessagePrefix.CAMERA))
        {
            Debug.Log("received " + message);
            CameraMessage camMessage = new CameraMessage();
            camMessage.DeserializeArguments(message.Remove(0, MessagePrefix.CAMERA.Length));
            CameraMessages.Enqueue(camMessage);
        }
    }
        protected override IMapMessage DoCreateMapMessage()
        {
            MapMessage message = new MapMessage();

            message.Connection = this.connection;
            return(message);
        }
        public void TestWriteOnlyBody()
        {
            MapMessage msg = new MapMessage();

            msg.ReadOnlyBody = false;

            msg.Body.SetBool("boolean", true);
            msg.Body.SetByte("byte", (byte)1);
            msg.Body["bytes"] = new byte[1];
            msg.Body.SetChar("char", 'a');
            msg.Body.SetDouble("double", 1.5);
            msg.Body.SetFloat("float", 1.5f);
            msg.Body.SetInt("int", 1);
            msg.Body.SetLong("long", 1);
            msg.Body["object"] = "stringObj";
            msg.Body.SetShort("short", (short)1);
            msg.Body.SetString("string", "string");

            msg.ReadOnlyBody = true;

            msg.Body.GetBool("boolean");
            msg.Body.GetByte("byte");
            Assert.IsNotNull(msg.Body["bytes"]);
            msg.Body.GetChar("char");
            msg.Body.GetDouble("double");
            msg.Body.GetFloat("float");
            msg.Body.GetInt("int");
            msg.Body.GetLong("long");
            Assert.IsNotNull(msg.Body["object"]);
            msg.Body.GetShort("short");
            msg.Body.GetString("string");
        }
示例#6
0
 public NetOutgoingMessage CreateMapMessage(MapMessage messageType)
 {
     NetOutgoingMessage message = IoCManager.Resolve<ISS13NetServer>().CreateMessage();
     message.Write((byte) NetMessage.MapMessage);
     message.Write((byte) messageType);
     return message;
 }
示例#7
0
        public void TestGetBoolean()
        {
            MapMessage msg = new MapMessage();

            msg.Body.SetBool(name, true);
            msg.ReadOnlyBody = true;
            Assert.IsTrue(msg.Body.GetBool(name));
        }
        public void TestGetByte()
        {
            MapMessage msg = new MapMessage();

            msg.Body.SetByte(this.name, (byte)1);
            msg = (MapMessage)msg.Clone();
            Assert.IsTrue(msg.Body.GetByte(this.name) == (byte)1);
        }
        public NetOutgoingMessage CreateMapMessage(MapMessage messageType)
        {
            NetOutgoingMessage message = IoCManager.Resolve <ISS14NetServer>().CreateMessage();

            message.Write((byte)NetMessage.MapMessage);
            message.Write((byte)messageType);
            return(message);
        }
示例#10
0
 /// <inheritdoc />
 public ElementMap InitializeMap(string name)
 {
     ElementMap = new ElementMap {
         Name = name
     };
     BeginEdit();
     MapMessage.SendWith(MapMessageType.New);
     return(ElementMap);
 }
示例#11
0
 /// <inheritdoc />
 public ElementMap InitializeMap(Dictionary <Guid, string> elementSources, string name)
 {
     ElementMap = new ElementMap(elementSources)
     {
         Name = name
     };
     BeginEdit();
     MapMessage.SendWith(MapMessageType.New);
     return(ElementMap);
 }
示例#12
0
 private void Bot_OnNewMessage(ActivitySet args)
 {
     foreach (var activity in args.activities)
     {
         if (!activity.from.id.Equals(clientId))
         {
             if (activity.text.Length > 0)
             {
                 Device.BeginInvokeOnMainThread(() =>
                 {
                     stack.Children.Insert(0, (new BotTextMessage()
                     {
                         TextMessage = activity.text
                     }));
                 });
             }
             if (activity.attachments.Count > 0)
             {
                 foreach (var att in activity.attachments)
                 {
                     if (att.contentType.Equals("application/vnd.microsoft.card.hero"))
                     {
                         var card = ((JObject)att.content).ToObject <HeroCard>();
                         if ((card.buttons != null) && (card.buttons.Count > 0))
                         {
                             Device.BeginInvokeOnMainThread(() =>
                             {
                                 var message = new ConfirmationMessage()
                                 {
                                     TextMessage = card.text, Buttons = card.buttons
                                 };
                                 message.ButtonClicked += Message_ButtonClicked;
                                 stack.Children.Insert(0, (message));
                             }
                                                            );
                         }
                         else
                         {
                             Device.BeginInvokeOnMainThread(() =>
                             {
                                 var message = new MapMessage()
                                 {
                                     TitleMessage = card.title, SubtitleMessage = card.subtitle, TextMessage = card.text, ImageUrl = card.images[0].url
                                 };
                                 stack.Children.Insert(0, message);
                             }
                                                            );
                         }
                     }
                 }
             }
         }
     }
 }
示例#13
0
        public void TestItemExists()
        {
            MapMessage mapMessage = new MapMessage();

            mapMessage.Body.SetString("exists", "test");

            mapMessage = (MapMessage)mapMessage.Clone();

            Assert.IsTrue(mapMessage.Body.Contains("exists"));
            Assert.IsFalse(mapMessage.Body.Contains("doesntExist"));
        }
示例#14
0
        private void BroadcastMap()
        {
            var map        = World.GetService <DrawerService>().DrawableBytes;
            var mapMessage = new MapMessage {
                DrawableBytes = map
            };

            foreach (var connection in Server.Connections)
            {
                connection.SendViaTcp(mapMessage);
            }
        }
 public void Publish(string ticker, double price)
 {
     emsTemplate.SendWithDelegate("APP.STOCK.MARKETDATA",
                                  delegate(ISession session)
     {
         MapMessage message = session.CreateMapMessage();
         message.SetString("TICKER", ticker);
         message.SetDouble("PRICE", price);
         message.Priority = 5;
         return(message);
     });
 }
        /// <summary> Extract a IDictionary from the given MapMessage.</summary>
        /// <param name="message">the message to convert
        /// </param>
        /// <returns> the resulting Map
        /// </returns>
        /// <throws>EMSException if thrown by EMS methods </throws>
        protected virtual IDictionary ExtractMapFromMessage(MapMessage message)
        {
            IDictionary dictionary = new Hashtable();
            IEnumerator e          = message.MapNames;

            while (e.MoveNext())
            {
                String key = (String)e.Current;
                dictionary.Add(key, message.GetObject(key));
            }

            return(dictionary);
        }
示例#17
0
 protected virtual void OnMapMessage(MapMessage message)
 {
     if (message is ViewChangeMessage)
     {
         var msg = (ViewChangeMessage)message;
         Region = msg.Span;
         if (ViewChanged != null)
         {
             ViewChanged(this, new MapViewChangeEventArgs(msg.Span, msg.ZoomLevel));
         }
         Debug.WriteLine("ViewChangeMessage recieved:\n\tPosition: {0} {1}", msg.Span.Center.Latitude, msg.Span.Center.Longitude);
     }
 }
示例#18
0
文件: MapModule.cs 项目: zril/Coma
        public override void Update(TimeSpan elapsed)
        {
            if (GameModel.Instance.BodyPlayer != null || GameModel.Instance.SoulPlayer != null)
            {
                if (!GameModel.Instance.BodyCamInit && GameModel.Instance.BodyPlayer != null)
                {
                    var camMessage = new CameraMessage(GameModel.Instance.BodyMap.Start.X, GameModel.Instance.BodyMap.Start.Y);
                    GlobalServer.Instance.SendMessage(GameModel.Instance.BodyPlayer.Id, camMessage.ToString());
                    GameModel.Instance.BodyCamInit = true;
                }

                if (!GameModel.Instance.SoulCamInit && GameModel.Instance.SoulPlayer != null)
                {
                    var camMessage = new CameraMessage(GameModel.Instance.SoulMap.Start.X, GameModel.Instance.SoulMap.Start.Y);
                    GlobalServer.Instance.SendMessage(GameModel.Instance.SoulPlayer.Id, camMessage.ToString());
                    GameModel.Instance.SoulCamInit = true;
                }

                ResetTiles(PlayerType.BODY);
                ResetTiles(PlayerType.SOUL);

                UpdateTiles(PlayerType.BODY);
                UpdateTiles(PlayerType.SOUL);

                ResolveDestructions(PlayerType.BODY);
                ResolveDestructions(PlayerType.SOUL);

                if (GameModel.Instance.BodyPlayer != null)
                {
                    MapMessage bodyMessage = new MapMessage(GameModel.Instance.BodyMap.GetTiles());
                    GlobalServer.Instance.SendMessage(GameModel.Instance.BodyPlayer.Id, bodyMessage.ToString());
                }

                if (GameModel.Instance.SoulPlayer != null)
                {
                    MapMessage soulMessage = new MapMessage(GameModel.Instance.SoulMap.GetTiles());
                    GlobalServer.Instance.SendMessage(GameModel.Instance.SoulPlayer.Id, soulMessage.ToString());
                }
            }

            BankMessage bankMessage = new BankMessage(GameModel.Instance.Bank.Cells, GameModel.Instance.Bank.Nutrients, GameModel.Instance.Bank.Thoughts, GameModel.Instance.Bank.Ideas);

            if (GameModel.Instance.BodyPlayer != null)
            {
                GlobalServer.Instance.SendMessage(GameModel.Instance.BodyPlayer.Id, bankMessage.ToString());
            }
            if (GameModel.Instance.SoulPlayer != null)
            {
                GlobalServer.Instance.SendMessage(GameModel.Instance.SoulPlayer.Id, bankMessage.ToString());
            }
        }
        /// <summary>
        /// Método que atiene una solicitud de procesamiento de distribuciones de documentos de instancia  XBRL
        /// Intenta realizar las distribuciones configuradas que no han sido todavía exitosas
        /// </summary>
        /// <param name="message"></param>
        public void OnMessage(Message message)
        {
            messageCount++;
            LogUtil.Info(String.Format("({0})Mensaje recibido para el procemiento de un documento XBRL", messageCount));
            try
            {
                MapMessage mapMessage = message as MapMessage;
                if (mapMessage != null)
                {
                    LogUtil.Info("Map Message (count)  = " + mapMessage.FieldCount);

                    if (mapMessage.ItemExists(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_DOCUMENTO) && mapMessage.ItemExists(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_VERSION))
                    {
                        var idDocumento = mapMessage.GetLong(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_DOCUMENTO);
                        var idVersion   = mapMessage.GetLong(DistribucionDocumentoConstants.PARAM_MENSAJE_ID_VERSION);

                        var resultado = ProcesarDistribucionDocumentoXBRLService.
                                        DistribuirDocumentoInstanciaXBRL(idDocumento, idVersion, new Dictionary <string, object>());
                        //Resultado no exitoso, programar reintento
                        if (!resultado.Resultado)
                        {
                            int reintento     = 0;
                            var numReintentos = Int32.Parse(ParametroSistemaService.ObtenerValorParametroSistema(ConstantsParametrosSistema.NUMERO_REINTENTOS_PROCESAR_XBRL, "0"));
                            //Realizar reintento de procesamiento
                            if (mapMessage.ItemExists(DistribucionDocumentoConstants.PARAM_MENSAJE_REINTENTO))
                            {
                                reintento = mapMessage.GetInt(DistribucionDocumentoConstants.PARAM_MENSAJE_REINTENTO);
                            }
                            LogUtil.Info(String.Format("Distribución no exitosa IdDocumento {0}, reintento: {1}",
                                                       idDocumento, reintento));
                            if (reintento < numReintentos)
                            {
                                reintento++;
                                LogUtil.Info(String.Format("Enviando reintento {1} para el documento {0}", idDocumento, reintento));
                                ProcesarDocumentoXBRLEmsGateway.EnviarSolicitudProcesarXBRL(idDocumento,
                                                                                            idVersion, reintento);
                            }
                        }
                    }
                    else
                    {
                        LogUtil.Error("Error al procesar mensaje: " + message.CorrelationID + ": parámetros incompletos");
                    }
                }
            }
            catch (Exception ex) {
                LogUtil.Info("Error al procesar mensaje: " + message.CorrelationID);
                LogUtil.Error(ex);
            }
        }
示例#20
0
        public void TestGetBoolean()
        {
            MapMessage msg = new MapMessage();

            msg.Body.SetBool(name, true);
            msg.ReadOnlyBody = true;
            Assert.IsTrue(msg.Body.GetBool(name));
            msg.ClearBody();
            msg.Body.SetString(name, "True");

            msg = (MapMessage)msg.Clone();

            Assert.IsTrue(msg.Body.GetBool(name));
        }
示例#21
0
        /// <inheritdoc />
        public async Task <bool> LoadMapAsync(string path)
        {
            var map = await _modelPersistenceService.LoadModelAsync(path);

            if (map != null)
            {
                ElementMap = map;
                BeginEdit();
                MapMessage.SendWith(MapMessageType.New);
                return(true);
            }

            return(false);
        }
示例#22
0
        public void TestGetDouble()
        {
            MapMessage msg = new MapMessage();

            try
            {
                msg.Body.SetDouble(this.name, 1.5);
                msg = (MapMessage)msg.Clone();
                Assert.IsTrue(msg.Body.GetDouble(this.name) == 1.5);
            }
            catch (NMSException)
            {
                Assert.IsTrue(false);
            }
        }
示例#23
0
        public void SendReceiveForeignMapMessageTest(
            [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
            MsgDeliveryMode deliveryMode)
        {
            using (IConnection connection = CreateConnection())
            {
                connection.Start();
                using (ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
                {
                    IDestination destination = CreateDestination(session, DestinationType.Topic);
                    using (IMessageConsumer consumer = session.CreateConsumer(destination))
                        using (IMessageProducer producer = session.CreateProducer(destination))
                        {
                            try
                            {
                                producer.DeliveryMode = deliveryMode;
                                MapMessage request = new MapMessage();
                                request.Properties[propertyName] = propertyValue;
                                request.Body[mapElementName]     = mapElementValue;

                                producer.Send(request);

                                IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage;
                                Assert.IsNotNull(message, "No message returned!");
                                Assert.AreEqual(request.Properties.Count, message.Properties.Count,
                                                "Invalid number of properties.");
                                Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");

                                // Check the body
                                Assert.AreEqual(request.Body.Count, message.Body.Count);
                                Assert.AreEqual(mapElementValue, message.Body[mapElementName],
                                                "MapMessage body was wrong.");

                                // use generic API to access entries
                                Assert.AreEqual(propertyValue, message.Properties[propertyName],
                                                "generic map entry: " + propertyName);

                                // use type safe APIs
                                Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName),
                                                "map entry: " + propertyName);
                            }
                            catch (NotSupportedException)
                            {
                            }
                        }
                }
            }
        }
示例#24
0
        public void TestGetString()
        {
            MapMessage msg = new MapMessage();

            try
            {
                String str = "test";
                msg.Body.SetString(this.name, str);
                msg = (MapMessage)msg.Clone();
                Assert.AreEqual(msg.Body.GetString(this.name), str);
            }
            catch (NMSException)
            {
                Assert.IsTrue(false);
            }
        }
        /// <summary> Create a EMS MapMessage for the given Map.</summary>
        /// <param name="map">the Map to convert
        /// </param>
        /// <param name="session">current EMS session
        /// </param>
        /// <returns> the resulting message
        /// </returns>
        /// <throws>  EMSException if thrown by EMS methods </throws>
        protected virtual MapMessage CreateMessageForMap(IDictionary map, ISession session)
        {
            MapMessage mapMessage = session.CreateMapMessage();

            foreach (DictionaryEntry entry in map)
            {
                if (!(entry.Key is string))
                {
                    throw new MessageConversionException("Cannot convert non-String key of type [" +
                                                         (entry.Key != null ? entry.Key.GetType().FullName : null) +
                                                         "] to MapMessage entry");
                }
                mapMessage.SetObject(entry.Key.ToString(), entry.Value);
            }
            return(mapMessage);
        }
        /// <summary>
        /// set the map control in the view model
        /// </summary>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //TODO: is there a nicer way to send the Control to the ViewModel? --> Could be done via map message
                ((MainViewModel)(this.DataContext)).MapControl = Karte;                                             //set map control

                var message = new MapMessage()
                {
                    MessageType = MapMessageType.Initialized, Boolean = true
                };                                                                                                  //let everyone know that the map control is ready
                Messenger.Default.Send(message);
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#27
0
        public void HandleNetworkMessage(NetIncomingMessage message)
        {
            MapMessage messageType = (MapMessage)message.ReadByte();

            switch (messageType)
            {
            case MapMessage.TurfClick:
                //HandleTurfClick(message);
                break;

            case MapMessage.TurfUpdate:
                HandleTurfUpdate(message);
                break;

            default:
                break;
            }
        }
示例#28
0
        public void MapConversion()
        {
            MapMessage  message = new MapMessage(tibcoSession);
            IDictionary content = new Hashtable();

            content["key1"] = "value1";
            content["key2"] = "value2";

            Expect.Call(session.CreateMapMessage()).Return(message).Repeat.Once();

            mocks.ReplayAll();

            Message msg = converter.ToMessage(content, session);

            Assert.AreEqual(content, converter.FromMessage(msg));

            mocks.VerifyAll();
        }
示例#29
0
        public void TestClearBody()
        {
            MapMessage mapMessage = new MapMessage();

            mapMessage.Body.SetString("String", "String");
            mapMessage.ClearBody();
            Assert.IsFalse(mapMessage.ReadOnlyBody);

            mapMessage.OnSend();
            mapMessage.Content = mapMessage.Content;
            Assert.IsNull(mapMessage.Body.GetString("String"));
            mapMessage.ClearBody();
            mapMessage.Body.SetString("String", "String");

            mapMessage = (MapMessage)mapMessage.Clone();

            mapMessage.Body.GetString("String");
        }
示例#30
0
        public void TestBytesConversion()
        {
            MapMessage msg = new MapMessage();

            msg.Body.SetBool("boolean", true);
            msg.Body.SetByte("byte", (byte)1);
            msg.Body["bytes"] = new byte[1];
            msg.Body.SetChar("char", 'a');
            msg.Body.SetDouble("double", 1.5);
            msg.Body.SetFloat("float", 1.5f);
            msg.Body.SetInt("int", 1);
            msg.Body.SetLong("long", 1);
            msg.Body["object"] = "stringObj";
            msg.Body.SetShort("short", (short)1);
            msg.Body.SetString("string", "string");

            // Test with a 1Meg String
            StringBuilder bigSB = new StringBuilder(1024 * 1024);

            for (int i = 0; i < 1024 * 1024; i++)
            {
                bigSB.Append((char)'a' + i % 26);
            }
            String bigString = bigSB.ToString();

            msg.Body.SetString("bigString", bigString);

            msg = (MapMessage)msg.Clone();

            Assert.AreEqual(msg.Body.GetBool("boolean"), true);
            Assert.AreEqual(msg.Body.GetByte("byte"), (byte)1);
            Assert.AreEqual((msg.Body["bytes"] as byte[]).Length, 1);
            Assert.AreEqual(msg.Body.GetChar("char"), 'a');
            Assert.AreEqual(msg.Body.GetDouble("double"), 1.5, 0);
            Assert.AreEqual(msg.Body.GetFloat("float"), 1.5f, 0);
            Assert.AreEqual(msg.Body.GetInt("int"), 1);
            Assert.AreEqual(msg.Body.GetLong("long"), 1);
            Assert.AreEqual(msg.Body["object"], "stringObj");
            Assert.AreEqual(msg.Body.GetShort("short"), (short)1);
            Assert.AreEqual(msg.Body.GetString("string"), "string");
            Assert.AreEqual(msg.Body.GetString("bigString"), bigString);
        }
示例#31
0
        public void TestGetBytes()
        {
            MapMessage msg = new MapMessage();

            try
            {
                byte[] bytes1 = new byte[3];
                byte[] bytes2 = new byte[2];
                System.Array.Copy(bytes1, 0, bytes2, 0, 2);
                msg.Body[this.name]       = bytes1;
                msg.Body[this.name + "2"] = bytes2;
                msg = (MapMessage)msg.Clone();
                Assert.IsTrue(System.Array.Equals(msg.Body[this.name], bytes1));
                Assert.AreEqual(((byte[])msg.Body[this.name + "2"]).Length, bytes2.Length);
            }
            catch (NMSException)
            {
                Assert.IsTrue(false);
            }
        }
示例#32
0
        static bool createMapMessageFromPort(MapMessage message, PerformanceBase data, TextWriter writer)
        {
            Interface port = _btSystem.GetDevicePort(GetOriginalKey(data));
            if (null == port)
            {
                writer.WriteLine("//找不到端口{0}", data.MOId);
                return false;
            }

            Device dev = port.Device;
            if (null == dev)
            {
                writer.WriteLine("//找不到设备{0}", port.DeviceId);
                return false;
            }

            writer.Write("//IP="); writer.WriteLine(dev.IP);
            writer.Write("//IfIndex="); writer.WriteLine(port.IfIndex);
            bool[] sa;
            if (null != _deviceList && _deviceList.TryGetValue(dev.Id, out sa) && !(sa[0] && sa[1]))
            {
                writer.WriteLine("//对象不在上传列表中");
                return false;
            }

            string type = null;
            if (5 == dev.DeviceType)
            {
                if (!_osTypes.TryGetValue(dev.SystemType, out type))
                    type = "Computersystem";
            }
            else
            {
                _deviceTypes.TryGetValue(dev.DeviceType, out type);
            }

            if (string.IsNullOrEmpty(type))
            {
                writer.WriteLine("//设备{0}的类型不正确,不可识别 - '{1}:{2}'.", dev.Id, dev.DeviceType, dev.SystemType);
                return false;
            }


            PerformanceData performanceData = data as PerformanceData;
            if (null == performanceData)
            {
                writer.WriteLine("//设备{0}的值类型不正确.", dev.Id);
                return false;
            }

            string nanruiKey = string.Concat("OriginalKey=", _manufacturer, _prefixId, "Device-", port.DeviceId);
            message.Body["MAINDATA"] = _encoding.GetBytes(nanruiKey);
            message.Body["SCENE"] = _encoding.GetBytes(_manufacturer);
            message.Body["CLASSNAME"] = _encoding.GetBytes(type);
            writer.Write("MAINDATA="); writer.WriteLine(nanruiKey);
            writer.Write("SCENE="); writer.WriteLine(_manufacturer);
            writer.Write("CLASSNAME="); writer.WriteLine(type);

            string ifKey = string.Concat("OriginalKey=", _manufacturer, _prefixId, "IpInterface-", port.Id);
            switch (data.StatusX)
            {
                case "ifStatus":
                    {
                        string valueKey = string.Concat("IpInterfaceStatus:", ifKey);
                        string tmp = GetIfStatus(data.GetValue()).ToString();
                        message.Body[valueKey] = _encoding.GetBytes(tmp);
                        writer.Write(valueKey); writer.Write("="); writer.WriteLine(tmp);
                        writer.Write("//PKI="); writer.WriteLine("IpInterfaceStatus");
                    }
                    break;
                default:
                    {
                        string key;
                        _performanceMapForPorts.TryGetValue(data.StatusX, out key);
                        if (string.IsNullOrEmpty(key))
                        {
                            writer.WriteLine("//端口{0}的性能参数不正确,不可识别 - '{1}'.", port.Id, data.StatusX);
                            return false;
                        }
                        string valueKey = string.Concat(key, ":", ifKey);
                        writer.Write("//PKI="); writer.WriteLine(valueKey);
                        string performanceValue = GetValue(performanceData.Value);

                        switch (data.StatusX)
                        {
                            case "ifOutOctets":
                                {
                                    performanceValue = GetValue((performanceData.Value / 8));
                                    break;
                                }
                            case "ifInOctets":
                                {
                                    performanceValue = GetValue((performanceData.Value / 8));
                                    break;
                                }
                            case "ifOctets":
                                {
                                    performanceValue = GetValue((performanceData.Value / 8));
                                    break;
                                }
                        }

                        message.Body[valueKey] = _encoding.GetBytes(performanceValue);
                        writer.Write(valueKey); writer.Write("="); writer.WriteLine(performanceValue);

                        break;
                    }
            }
            return true;
        }
示例#33
0
        static MapMessage createMapMessage(Session producer, PerformanceBase data, TextWriter writer)
        {
            MapMessage message = new MapMessage();
            message.Body["TIME"] = _encoding.GetBytes(DateTime.Now.ToString());
            writer.Write("TIME="); writer.WriteLine(DateTime.Now.ToString());
            writer.Write("//rawPKI="); writer.WriteLine(data.StatusX);
            writer.Write("//rawValue="); writer.WriteLine(data.GetValue());

            //CPU/MEM
            if (data.MOType == "Device")
            {
                if (createMapMessageFromDevice(message, data, writer))
                    return message;
            }
            else if (data.MOType == "DevicePort")
            {
                if (createMapMessageFromPort(message, data, writer))
                    return message;
            }
            else if (data.MOType == "TopologyLink")
            {
                if (createMapMessageFromLink(message, data, writer))
                    return message;
            }
            else if (data.MOType == "Service")
            {
                if (createMapMessageFromServer(message, data, writer))
                    return message;
            }
            else
            {
                writer.WriteLine("//无法识别的对象类型");
            }
            return null;
        }
示例#34
0
        static bool createMapMessageFromServer(MapMessage message, PerformanceBase data, TextWriter writer)
        {
            ServiceStaticPropertiesData server = _btSystem.GetService(data.MOId);
            if (null == server)
            {
                writer.WriteLine("//找不到服务{0}", data.MOId);
                return false;
            }

            Device dev = server.Device;
            if (null == dev)
            {
                writer.WriteLine("//找不到服务[{0}:{1}]所在的设备{2}", data.MOId, server.CustomName, server.DeviceId);
                return false;
            }


            writer.Write("//IP="); writer.WriteLine(server.Device.IP);
            writer.Write("//serviceId="); writer.WriteLine(server.Id);
            writer.Write("//serviceType="); writer.WriteLine(server.Type);
            writer.Write("//serviceName="); writer.WriteLine(server.CustomName);
            bool[] sa;
            if (null != _serverList && _serverList.TryGetValue(data.MOId, out sa) && !(sa[0] && sa[1]))
            {
                writer.WriteLine("//对象不在上传列表中");
                return false;
            }

            string type = null;
            _serverTypes.TryGetValue(server.Type, out type);
            if (string.IsNullOrEmpty(type))
            {
                writer.WriteLine("//服务{0}的类型不正确,不可识别 - '{1}'.", server.Id, server.Type);
                return false;
            }

            //string nanruiKey = string.Concat("OriginalKey=", manufacturer, PrefixId, "Device-", dev.Id);
            string nanruiKey = string.Concat("OriginalKey=", _manufacturer, _prefixId, "SERVER-", data.MOId);
            string dataKey = data.StatusX;

            HistoryRule rule = _btSystem.GetHistoryRuleByStoreId(data.StoreId);
            if (null != rule)
            {
                writer.WriteLine("//查询历史记录规则 storeId='{0}',修正指标 old='{1}', new='{2}'.", data.StoreId, dataKey, rule.PKIs);
                dataKey = rule.PKIs;
            }

            Context context = new Context();
            context["serviceType"] = server.Type.ToString();
            context["serviceId"] = server.Id.ToString();
            context["performanceKey"] = dataKey;

            string fieldKey = null;
            string fieldValue = null;
            foreach (IMatcher matcher in _serviceMatchers)
            {
                MatchResult matchResult = matcher.Match(dataKey);
                if (null != matchResult)
                {
                    fieldKey = matchResult.Misc[0].Key;
                    fieldValue = matchResult.Misc[0].Value;
                    context["schema"] = matchResult.Schema;
                    context["objectKey"] = fieldKey;
                    context["objectId"] = fieldValue;
                    context["performanceKey"] = matchResult.PKI;
                    dataKey = matchResult.PKI;

                    writer.WriteLine("//分解PKI, schema='{0}',performanceKey='{1}', '{2}'='{3}'."
                        , matchResult.Schema
                        , matchResult.PKI
                        , fieldKey
                        , fieldValue);
                    break;
                }
            }

            DispatchResult result = _serviceDispatcher.Find(context);
            if (null == result)
            {
                writer.WriteLine("//服务{0}的性能参数不正确,不可识别 - '{1}'.", server.Id, data.StatusX);
                return false;
            }
            if (string.IsNullOrEmpty(result.Alias) || 0 == string.Compare("null", result.Alias, true))
            {
                writer.WriteLine("//服务{0}的性能参数不正确,不可识别,可能不用发送 - '{1}'.", server.Id, data.StatusX);
                return false;
            }

            dataKey = result.Alias;
            string objectKey = null;
            if (!string.IsNullOrEmpty(fieldValue))
            {
                if (string.IsNullOrEmpty(result.Separator))
                {
                    objectKey = string.Concat(nanruiKey, "-", fieldKey, "-", fieldValue);
                    dataKey = string.Concat(result.Alias, ":", objectKey);
                }
                else if ("null" != result.Separator)
                {
                    objectKey = string.Concat(nanruiKey, result.Separator, fieldValue);
                    dataKey = string.Concat(result.Alias, ":", objectKey);
                }
                //else
                //{
                //    objectKey = serviceKey;
                //    dataKey = string.Concat(result.Alias, ":", objectKey);
                //}

                writer.WriteLine("//修正服务的性能参数 - '{0}'.", dataKey);
            }
            //else
            //{
            //    objectKey = serviceKey;
            //    dataKey = string.Concat(result.Alias, ":", objectKey);
            //}

            string performanceValue = GetValue(data.GetValue());

            if (0 == string.Compare("open", performanceValue, true))
            {
                performanceValue = "1";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("close", performanceValue, true))
            {
                performanceValue = "0";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("up", performanceValue, true))
            {
                performanceValue = "1";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("down", performanceValue, true))
            {
                performanceValue = "0";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("running", performanceValue, true))
            {
                performanceValue = "1";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("active", performanceValue, true))
            {
                performanceValue = "1";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("inactive", performanceValue, true))
            {
                performanceValue = "0";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (data.StatusX == "PendingRequestOldestTime")
            {
                try
                {
                    DateTime timeValue;
                    if (!tryParseDateTime(performanceValue, out timeValue))
                    {
                        writer.WriteLine("//日期格式无法分析");
                        return false;
                    }

                    performanceValue = timeValue.ToFileTimeUtc().ToString();
                }
                catch (Exception ex)
                {
                    writer.WriteLine("//" + ex.ToString());
                    return false;
                }
            }

            message.Body["MAINDATA"] = _encoding.GetBytes(nanruiKey);
            message.Body["SCENE"] = _encoding.GetBytes(_manufacturer);
            message.Body["CLASSNAME"] = _encoding.GetBytes(type);
            message.Body[dataKey] = _encoding.GetBytes(performanceValue);


            writer.Write("//PKI="); writer.WriteLine(dataKey);

            writer.Write("MAINDATA="); writer.WriteLine(nanruiKey);
            writer.Write("SCENE="); writer.WriteLine(_manufacturer);
            writer.Write("CLASSNAME="); writer.WriteLine(type);
            writer.Write(dataKey); writer.Write("="); writer.WriteLine(performanceValue);
            return true;
        }
示例#35
0
        static bool createMapMessageFromDevice(MapMessage message, PerformanceBase data, TextWriter writer)
        {
            Device dev = _btSystem.GetDevice(data.MOId);
            if (null == dev)
            {
                writer.WriteLine("//找不到设备{0}", data.MOId);
                return false;
            }

            writer.Write("//IP="); writer.WriteLine(dev.IP);
            bool[] sa;
            if (null != _deviceList && _deviceList.TryGetValue(data.MOId, out sa) && !(sa[0] && sa[1]))
            {
                writer.WriteLine("//对象不在上传列表中");
                return false;
            }

            string type = null;
            if (5 == dev.DeviceType)
            {
                if (!_osTypes.TryGetValue(dev.SystemType, out type))
                    type = "Computersystem";
            }
            else
            {
                _deviceTypes.TryGetValue(dev.DeviceType, out type);
            }

            if (string.IsNullOrEmpty(type))
            {
                writer.WriteLine("//设备{0}的类型不正确,不可识别 - '{1}:{2}'.", dev.Id, dev.DeviceType, dev.SystemType);
                return false;
            }

            string nanruiKey = string.Concat("OriginalKey=", _manufacturer, _prefixId, "Device-", dev.Id);
            string dataKey = data.StatusX;

            HistoryRule rule = _btSystem.GetHistoryRuleByStoreId(data.StoreId);
            if (null != rule)
            {
                writer.WriteLine("//查询历史记录规则 storeId='{0}',修正指标 old='{1}', new='{2}'.", data.StoreId, dataKey, rule.PKIs);
                dataKey = rule.PKIs;
            }

            Context context = new Context();
            context["deviceType"] = dev.DeviceType.ToString();
            context["deviceOS"] = dev.SystemType.ToString();
            context["deviceId"] = dev.Id.ToString();

            context["performanceKey"] = dataKey;

            string fieldKey = null;
            string fieldValue = null;
            foreach (IMatcher matcher in _serviceMatchers)
            {
                MatchResult matchResult = matcher.Match(dataKey);
                if (null != matchResult)
                {
                    fieldKey = matchResult.Misc[0].Key;
                    fieldValue = matchResult.Misc[0].Value;
                    context["schema"] = matchResult.Schema;
                    context["objectKey"] = fieldKey;
                    context["objectId"] = fieldValue;
                    context["performanceKey"] = matchResult.PKI;
                    dataKey = matchResult.PKI;

                    writer.WriteLine("//分解PKI, schema='{0}',performanceKey='{1}', '{2}'='{3}'."
                        , matchResult.Schema
                        , matchResult.PKI
                        , fieldKey
                        , fieldValue);
                    break;
                }
            }

            DispatchResult result = _deviceDispatcher.Find(context);
            if (null == result)
            {
                writer.WriteLine("//设备{0}的性能参数不正确,不可识别 - '{1}'.", dev.Id, data.StatusX);
                return false;
            }
            if (string.IsNullOrEmpty(result.Alias) || 0 == string.Compare("null", result.Alias, true))
            {
                writer.WriteLine("//设备{0}的性能参数不正确,不可识别,可能不用发送 - '{1}'.", dev.Id, data.StatusX);
                return false;
            }

            dataKey = result.Alias;
            string objectKey = null;
            if (!string.IsNullOrEmpty(fieldValue))
            {
                if (string.IsNullOrEmpty(result.Separator))
                {
                    objectKey = string.Concat(nanruiKey, "-", fieldKey, "-", fieldValue);
                    dataKey = string.Concat(result.Alias, ":", objectKey);
                }
                else if ("null" != result.Separator)
                {
                    objectKey = string.Concat(nanruiKey, result.Separator, fieldValue);
                    dataKey = string.Concat(result.Alias, ":", objectKey);
                }
                writer.WriteLine("//修正设备的性能参数 - '{0}'.", dataKey);
            }

            //SCENE	网管厂家	Betasoft(固定是这个)
            message.Body["MAINDATA"] = _encoding.GetBytes(nanruiKey);
            message.Body["SCENE"] = _encoding.GetBytes(_manufacturer);
            message.Body["CLASSNAME"] = _encoding.GetBytes(type);


            writer.Write("MAINDATA="); writer.WriteLine(nanruiKey);
            writer.Write("SCENE="); writer.WriteLine(_manufacturer);
            writer.Write("CLASSNAME="); writer.WriteLine(type);
            object performanceValue = data.GetValue();

            if (data.StatusX == "Memory")
            {
                performanceValue = GetValue(data.GetValue());
                dataKey = "MEMLOAD";
            }
            else if (data.StatusX == "Cpu")
            {
                dataKey = string.Concat("CPULOAD:", nanruiKey, "-CPU1");
                performanceValue = GetValue(data.GetValue());
            }
            else if (data.StatusX == "Used_Per")
            {
                if (result.Alias == "FileSystemUsedRate")
                {
                    performanceValue = GetValue(data.GetValue());
                }
                else if (result.Alias == "DiskFreeRate")
                {
                    performanceValue = GetValue(100 - ((PerformanceData)data).Value);
                    writer.WriteLine("//原值为使用率,需要修正 - oldValue={0}, newValue={1}", data.GetValue(), performanceValue);
                }
            }
            else if (data.StatusX == "upmins")
            {
                if (100 == (long)(((PerformanceData)data).Value))
                {
                    writer.WriteLine("//原值单位为100,可能不正确 - oldValue={0}, Id={1}", data.GetValue(), data.Id);
                    return false;
                }

                performanceValue = ((long)(((PerformanceData)data).Value * 60)).ToString();
                writer.WriteLine("//原值单位为分钟,需要修正 - oldValue={0}, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (result.Alias == "ComputerSystemRunningTime")
            {
                performanceValue = ((long)(((PerformanceData)data).Value * 60)).ToString();
                writer.WriteLine("//原值单位为分钟,需要修正 - oldValue={0}, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("Up", data.GetValue().ToString(), true))
            {
                // 此处将所有的 Up 或 Down这样的值改成 1 或 0
                performanceValue = 1;
                writer.WriteLine("//原值需要修正 - oldValue=Up, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("Down", data.GetValue().ToString(), true))
            {
                // 此处将所有的 Up 或 Down这样的值改成 1 或 0
                performanceValue = 0;
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("active", data.GetValue().ToString(), true))
            {
                performanceValue = "1";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if (0 == string.Compare("inactive", data.GetValue().ToString(), true))
            {
                performanceValue = "0";
                writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
            }
            else if ("ProcessOccupyCPUTime" == result.Alias
                || "ProcessRunningTime" == result.Alias)
            {
                TimeSpan timeSpan;
                if (TimeSpan.TryParse(performanceValue.ToString().Replace('-', '.'), out timeSpan))
                {
                    performanceValue = GetValue(timeSpan.TotalSeconds);
                    writer.WriteLine("//原值需要修正 - oldValue=Down, newValue={1}", data.GetValue(), performanceValue);
                }
            }

            //dataKey = dataKey.Trim();

            message.Body[dataKey] = _encoding.GetBytes(performanceValue.ToString());

            writer.Write("//PKI="); writer.WriteLine(dataKey);
            writer.Write(dataKey); writer.Write("="); writer.WriteLine(performanceValue.ToString());
            return true;
        }
示例#36
0
        static bool createMapMessageFromLink(MapMessage message, PerformanceBase data, TextWriter writer)
        {
            Link link = _btSystem.GetLink(data.MOId);
            if (null == link)
            {
                writer.WriteLine("//找不到链路连接{0}", data.MOId);
                return false;
            }


            PerformanceData performanceData = data as PerformanceData;
            if (null == performanceData)
            {
                writer.WriteLine("//链路连接{0}的值类型不正确.", data.MOId);
                return false;
            }

            writer.Write("//LinkId="); writer.WriteLine(link.Id);
            writer.Write("//LinkName="); writer.WriteLine(link.DisplayName);
            bool[] sa;
            if (null != _linkList && _linkList.TryGetValue(data.MOId, out sa) && !(sa[0] && sa[1]))
            {
                writer.WriteLine("//对象不在上传列表中");
                return false;
            }

            string nanruiKey = string.Concat("OriginalKey=", _manufacturer, _prefixId, "L2Link-", data.MOId);
            message.Body["MAINDATA"] = _encoding.GetBytes(nanruiKey);
            message.Body["SCENE"] = _encoding.GetBytes(_manufacturer);

            string className = link.IsVirtual ? "LogicalLink" : "L2Link";
            message.Body["CLASSNAME"] = _encoding.GetBytes(className);

            writer.Write("MAINDATA="); writer.WriteLine(nanruiKey);
            writer.Write("SCENE="); writer.WriteLine(_manufacturer);
            writer.WriteLine("CLASSNAME=" + className);

            switch (data.StatusX)
            {
                case "ifStatus":
                    message.Body["L2LinkStatus"] = _encoding.GetBytes(GetIfStatus(data.GetValue()));
                    writer.Write("L2LinkStatus="); writer.WriteLine(GetIfStatus(data.GetValue()));
                    writer.Write("//PKI="); writer.WriteLine("L2LinkStatus");
                    break;
                //case "ifOutOctets":
                //    message.Body["L2LinkOutFlow5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifOutNUcastPkts":
                //    message.Body["L2LinkOutBroadcastFlow5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifOutDiscards":
                //    message.Body["L2LinkOutDropPacketNum5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifOutErrors":
                //    message.Body["L2LinkOutErrorPacketNum5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifOutPercent":
                //    message.Body["L2LinkOutBwUsedRate5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifInOctets":
                //    message.Body["L2LinkInFlow5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifInUcastPkts":
                //    message.Body["L2LinkInBroadcastFlow5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifInDiscards":
                //    message.Body["L2LinkInDropPacketNum5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifInErrors":
                //    message.Body["L2LinkInErrorPacketNum5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                //case "ifInPercent":
                //    message.Body["L2LinkInBwUsedRate5MIN"] = _encoding.GetBytes(data.Value.ToString());
                //    break;
                default:
                    {
                        string key;
                        _performanceMapForLinks.TryGetValue(data.StatusX, out key);
                        if (string.IsNullOrEmpty(key))
                        {
                            writer.WriteLine("//线路{0}的性能参数不正确,不可识别 - '{1}'.", data.MOId, data.StatusX);
                            return false;
                        }

                        writer.Write("//PKI="); writer.WriteLine(key);
                        string performanceValue = GetValue(performanceData.Value);

                        switch (data.StatusX)
                        {
                            case "ifOutOctets":
                                {
                                    performanceValue = GetValue(performanceData.Value / 8);
                                    break;
                                }
                            case "ifInOctets":
                                {
                                    performanceValue = GetValue(performanceData.Value / 8);
                                    break;
                                }
                            case "ifOctets":
                                {
                                    performanceValue = GetValue(performanceData.Value / 8);
                                    break;
                                }
                        }

                        message.Body[key] = _encoding.GetBytes(performanceValue);
                        writer.Write(key); writer.Write("="); writer.WriteLine(performanceValue);
                        break;
                    }
            }

            return true;
        }