Esempio n. 1
0
 public override void onMessage(DataMessage msg)
 {
     String str = msg.getSender();
     String val1 = msg.getString("val1");
     double val2 = msg.getDouble("val2");
     double val3 = msg.getDouble("val3");
     count++;
 }
Esempio n. 2
0
        public void MessageFactory_CreateResponseTest()
        {
            var messageFactory = new MessageFactory();
            var response = DateTime.Now;
            var responseMessage = new DataMessage<DateTime>(response);

            Assert.AreEqual(response, messageFactory.CreateResponse<DateTime>(response).MessageObject);
            Assert.AreEqual(responseMessage, messageFactory.CreateResponse<Message>(responseMessage));
        }
Esempio n. 3
0
        public void RequestTask_ConstructorTest()
        {
            var message = new DataMessage<DateTime>(DateTime.Now);
            Action<Message> responseAction = m => { };

            var requestMessage = new RequestTask(message, responseAction);
            AssertException.Throws<ArgumentNullException>(() => new RequestTask(null, responseAction));
            AssertException.Throws<ArgumentNullException>(() => new RequestTask(message, null));
        }
Esempio n. 4
0
 public void addMessageToSend(DataMessage message)
 {
     if (connection != null && connection.Connected)
     {
         lock (messagesToSend)
         {
             messagesToSend.Push(message);
         }
     }
 }
Esempio n. 5
0
        public void MessageFactory_ExtractResponse()
        {
            var messageFactory = new MessageFactory();
            var response = DateTime.Now;
            var responseMessage = new DataMessage<DateTime>(response);

            Assert.AreEqual(response, messageFactory.ExtractResponse<DateTime>(responseMessage));
            Assert.AreEqual(responseMessage, messageFactory.ExtractResponse<DataMessage<DateTime>>(responseMessage));
            AssertException.Throws<InvalidCastException>(() => messageFactory.ExtractResponse<Guid>(responseMessage));
        }
 public HttpResponseMessage PutReset([FromBody] SystemUser systemUser)
 {
     try
     {
         DbLibrary     dbLibrary    = new DbLibrary();
         BO_SystemUser boSystemUser = new BO_SystemUser(dbLibrary);
         DataMessage   dataMessage  = new DataMessage(boSystemUser.ResetPassword(systemUser));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en el cambio de password del usuario: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
Esempio n. 7
0
 public HttpResponseMessage Put([FromBody] Document document)
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Document boDocument  = new BO_Document(dbLibrary);
         DataMessage dataMessage = new DataMessage(boDocument.Update(document));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la actualización del registro: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 private void SendMessage(DataMessage msgToSend)
 {
     dataSend = new byte[2048];
     try
     {
         dataSend = msgToSend.ToByte();
         clientSocket.BeginSendTo(dataSend, 0, dataSend.Length, SocketFlags.None,
                                  serverEndPoint, new AsyncCallback(OnSend), null);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message, "Client Sending",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Sends a DataMessage to all ocnnected clients
        /// </summary>
        /// <param name="routeKey">The route to send too</param>
        /// <param name="dataMessage">The message to send</param>
        public void Emit(string routeKey, DataMessage dataMessage = null)
        {
            if (dataMessage == null)
            {
                dataMessage = new DataMessage();
            }

            lock (_lock)
            {
                foreach (KeyValuePair <string, ClientSocket> client in _clientSockets)
                {
                    client.Value.Emit(routeKey, dataMessage);
                }
            }
        }
 public HttpResponseMessage PostLogin(User user)
 {
     try
     {
         DbLibrary     dbLibrary    = new DbLibrary();
         BO_SystemUser boSystemUser = new BO_SystemUser(dbLibrary);
         DataMessage   dataMessage  = new DataMessage(boSystemUser.GetLogin(user.username, user.password));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del listado de usuarios: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage PutStateRolePermission(string PermissionId, string RoleId, bool State)
 {
     try
     {
         DbLibrary dbLibrary = new DbLibrary();
         BO_SystemRolePermission boSystemRolePermission = new BO_SystemRolePermission(dbLibrary);
         DataMessage             dataMessage            = new DataMessage(boSystemRolePermission.ChangeState(PermissionId, RoleId, State));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en el cambio de estado del permiso role: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage GetUserRoles()
 {
     try
     {
         DbLibrary        dbLibrary       = new DbLibrary();
         BO_SystemUserRol boSystemUserRol = new BO_SystemUserRol(dbLibrary);
         DataMessage      dataMessage     = new DataMessage(boSystemUserRol.GetAll());
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del listado de usuarios y roles: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage Put([FromBody] SystemPermissions systemPermissions)
 {
     try
     {
         DbLibrary            dbLibrary           = new DbLibrary();
         BO_SystemPermissions boSystemPermissions = new BO_SystemPermissions(dbLibrary);
         DataMessage          dataMessage         = new DataMessage(boSystemPermissions.Update(systemPermissions));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la actualización del Permissions: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
Esempio n. 14
0
 public HttpResponseMessage GetDocument(int DocumentId)
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Document boDocument  = new BO_Document(dbLibrary);
         DataMessage dataMessage = new DataMessage(boDocument.GetId(DocumentId));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del Id: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage Post([FromBody] SystemRolePermission systemRolePermission)
 {
     try
     {
         DbLibrary dbLibrary = new DbLibrary();
         BO_SystemRolePermission boSystemRolePermission = new BO_SystemRolePermission(dbLibrary);
         DataMessage             dataMessage            = new DataMessage(boSystemRolePermission.Create(systemRolePermission));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la creación del permiso role: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage GetValidator(string UserId, string Password)
 {
     try
     {
         DbLibrary     dbLibrary    = new DbLibrary();
         BO_SystemUser boSystemUser = new BO_SystemUser(dbLibrary);
         DataMessage   dataMessage  = new DataMessage(boSystemUser.GetValidator(UserId, Password));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del usuario: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage GetPermissionRoles(string RoleId)
 {
     try
     {
         DbLibrary dbLibrary = new DbLibrary();
         BO_SystemRolePermission boSystemRolePermission = new BO_SystemRolePermission(dbLibrary);
         DataMessage             dataMessage            = new DataMessage(boSystemRolePermission.GetrolId(RoleId));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del roles users: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
Esempio n. 18
0
        private AcknowledgeMessage ExecuteGetOperation(IMessage message)
        {
            DataMessage     message2    = message as DataMessage;
            DataDestination destination = base.GetDestination(message2) as DataDestination;
            object          obj2        = destination.ServiceAdapter.Invoke(message);

            if (obj2 == null)
            {
                return(new AcknowledgeMessage());
            }
            ArrayList items = new ArrayList(1);

            items.Add(obj2);
            return(destination.SequenceManager.ManageSequence(message2, items));
        }
 public HttpResponseMessage GetCountryId(string CountryId)
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Author   boAuthor    = new BO_Author(dbLibrary);
         DataMessage dataMessage = new DataMessage(boAuthor.GetCountryId(CountryId));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del Id: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage Post([FromBody] Language language)
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Language boLanguage  = new BO_Language(dbLibrary);
         DataMessage dataMessage = new DataMessage(boLanguage.Create(language));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la creación del registro: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage PutState(int AuthorId, bool State)
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Author   boAuthor    = new BO_Author(dbLibrary);
         DataMessage dataMessage = new DataMessage(boAuthor.ChangeState(AuthorId, State));
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en el cambio de estado del registro: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
 public HttpResponseMessage GetAll()
 {
     try
     {
         DbLibrary   dbLibrary   = new DbLibrary();
         BO_Language boLanguage  = new BO_Language(dbLibrary);
         DataMessage dataMessage = new DataMessage(boLanguage.GetAll());
         return(Request.CreateResponse(HttpStatusCode.OK, dataMessage));
     }
     catch (Exception e)
     {
         ErrorMessage mensaje = new ErrorMessage("2.1", "Excepción en la obtención del listado: " + e.GetBaseException().Message, e.ToString());
         return(Request.CreateResponse(HttpStatusCode.BadRequest, mensaje));
     }
 }
Esempio n. 23
0
        public void ReleaseCollectionOperation(DataMessage dataMessage)
        {
            lock (_objLock)
            {
                int sequenceId = (int)dataMessage.headers[DataMessage.SequenceIdHeader];
                if (log != null && log.IsDebugEnabled)
                {
                    log.Debug(__Res.GetString(__Res.SequenceManager_ReleaseCollection, sequenceId, dataMessage.clientId));
                }

                Sequence sequence   = GetSequence(sequenceId);
                IList    parameters = dataMessage.body as IList;
                RemoveSubscriberFromSequence(dataMessage.clientId as string, sequence);
            }
        }
Esempio n. 24
0
        public PagedMessage GetPage(DataMessage dataMessage)
        {
            int      sequenceId = (int)dataMessage.headers[DataMessage.SequenceIdHeader];
            Sequence sequence   = GetSequence(sequenceId);

            if (sequence != null)
            {
                return(GetPagedMessage(dataMessage, sequence));
            }
            else
            {
                DataServiceException dse = new DataServiceException(string.Format("Sequence {0} in destination {1} was not found", sequenceId, dataMessage.destination));
                throw dse;
            }
        }
Esempio n. 25
0
 private void tablelistView_SelectedIndexChanged(object sender, EventArgs e)
 {
     headers = new List <TableHeader>();
     foreach (ListViewItem item in tablelistView.SelectedItems)
     {
         if (item.Text == GlobalData.GlobalLanguage.call_message)
         {
             headers.Add(new TableHeader {
                 oldheader = DataMessage.Displaytime()
             });
             headers.Add(new TableHeader {
                 oldheader = DataMessage.DisplaycallerNum()
             });
             headers.Add(new TableHeader {
                 oldheader = DataMessage.DisplayemployeeNum()
             });
             headers.Add(new TableHeader {
                 oldheader = DataMessage.Displaytype()
             });
             headers.Add(new TableHeader {
                 oldheader = DataMessage.Displaystatus()
             });
             headers.Add(new TableHeader {
                 oldheader = DataMessage.DisplaycallZone()
             });
         }
         else if (item.Text == GlobalData.GlobalLanguage.employ_info)
         {
             headers.Add(new TableHeader {
                 oldheader = Employee.DisplayemployeeNum()
             });
             headers.Add(new TableHeader {
                 oldheader = Employee.Displayname()
             });
             headers.Add(new TableHeader {
                 oldheader = Employee.Displayphonenum()
             });
             headers.Add(new TableHeader {
                 oldheader = Employee.Displayremarks()
             });
             headers.Add(new TableHeader {
                 oldheader = Employee.Displaysex()
             });
         }
         dataGridView.DataSource = headers;
         dataGridView.Refresh();
     }
 }
Esempio n. 26
0
        public void TestGarlicCreate()
        {
            var ls = new I2PDate(DateTime.Now + TimeSpan.FromMinutes(5));

            var origmessage = new DeliveryStatusMessage(I2NPMessage.GenerateMessageId());
            var bigmessage  = new DataMessage(new BufLen(BufUtils.RandomBytes(14 * 1024)));

            var garlic = new Garlic(
                new GarlicClove(
                    new GarlicCloveDeliveryLocal(origmessage),
                    ls),
                new GarlicClove(
                    new GarlicCloveDeliveryLocal(bigmessage),
                    ls)
                );

            var egmsg = Garlic.EGEncryptGarlic(
                garlic,
                Public,
                new I2PSessionKey(),
                null);

            var origegdata  = I2NPMessage.Clone(egmsg);
            var origegdata2 = I2NPMessage.Clone(egmsg);

            // Decrypt

            var(aesblock, sessionkey1) = Garlic.EGDecryptGarlic(origegdata, Private);

            var newgarlic = new Garlic((BufRefLen)aesblock.Payload);

            var g1 = new BufLen(garlic.ToByteArray());
            var g2 = new BufLen(newgarlic.ToByteArray());

            Assert.IsTrue(g1 == g2);

            // Retrieve

            var(aesblock2, sessionkey2) = Garlic.RetrieveAESBlock(origegdata2, Private, null);

            newgarlic = new Garlic((BufRefLen)aesblock2.Payload);

            g1 = new BufLen(garlic.ToByteArray());
            g2 = new BufLen(newgarlic.ToByteArray());

            Assert.IsTrue(g1 == g2);
            Assert.IsTrue(sessionkey1 == sessionkey2);
        }
        /// <summary>
        /// Decrypt a received <see cref="SignalServiceEnvelope"/>
        /// </summary>
        /// <param name="envelope">The received SignalServiceEnvelope</param>
        /// <returns>a decrypted SignalServiceContent</returns>
        public SignalServiceContent decrypt(SignalServiceEnvelope envelope)
        {
            try
            {
                SignalServiceContent content = new SignalServiceContent();

                if (envelope.hasLegacyMessage())
                {
                    DataMessage message = DataMessage.Parser.ParseFrom(decrypt(envelope, envelope.getLegacyMessage()));
                    content = new SignalServiceContent()
                    {
                        Message = createSignalServiceMessage(envelope, message)
                    };
                }
                else if (envelope.hasContent())
                {
                    Content message = Content.Parser.ParseFrom(decrypt(envelope, envelope.getContent()));

                    if (message.DataMessageOneofCase == Content.DataMessageOneofOneofCase.DataMessage)
                    {
                        content = new SignalServiceContent()
                        {
                            Message = createSignalServiceMessage(envelope, message.DataMessage)
                        };
                    }
                    else if (message.SyncMessageOneofCase == Content.SyncMessageOneofOneofCase.SyncMessage && localAddress.getNumber().Equals(envelope.getSource()))
                    {
                        content = new SignalServiceContent()
                        {
                            SynchronizeMessage = createSynchronizeMessage(envelope, message.SyncMessage)
                        };
                    }
                    else if (message.CallMessageOneofCase == Content.CallMessageOneofOneofCase.CallMessage)
                    {
                        content = new SignalServiceContent()
                        {
                            CallMessage = createCallMessage(message.CallMessage)
                        };
                    }
                }

                return(content);
            }
            catch (InvalidProtocolBufferException e)
            {
                throw new InvalidMessageException(e);
            }
        }
Esempio n. 28
0
        public List <DateTime> CheckIfCalculationsRequired(DataMessage dataMessage)
        {
            List <DateTime> hoursToCalculateAverages = new List <DateTime>();

            foreach (PerSecondStat second in dataMessage.RealTimeStats)
            {
                // Create this function in the Helper Sevices DateTimeTools class.
                // Regular Expression that checks if the PerSecondStat is the last second of that hour.
                if (MySqlDateTimeTools.IsLastSecondOfHour(second.DateTime))
                {
                    hoursToCalculateAverages.Add(MySqlDateTimeConverter.ToDateTime(second.DateTime).GetHourBeginning());
                }
            }

            return(hoursToCalculateAverages);
        }
Esempio n. 29
0
        public void CreateStuctures()
        {
            FutOrderMessage  = m_publisher.NewMessage(MessageKeyType.KeyName, "FutAddOrder");
            FutOrderInstance = (DataMessage)FutOrderMessage;


            FutOrderInstance["broker_code"].set(m_plaza2Connector.Broker_code);
            // smsg["isin"].set(ao.Isin);
            FutOrderInstance["client_code"].set(m_plaza2Connector.Client_code);
            FutOrderInstance["type"].set((int)OrderTypes.Part);
            //smsg["dir"].set((int)ao.Dir);  //1 -buy 2 -sell
            //smsg["amount"].set(ao.Amount);
            //smsg["price"].set(ao.Price);
            //smsg["ext_id"].set(ao.Ext_id);
            //smsg["date_exp"].set(dtExp.ToString("yyyyMMdd"));
        }
Esempio n. 30
0
        private IMessage Create(DataMessage dataMessage)
        {
            IAssembler assembler = this.GetAssembler();

            if (assembler != null)
            {
                if ((log != null) && log.get_IsDebugEnabled())
                {
                    log.Debug(assembler.GetType().FullName + " CreateItem");
                }
                assembler.CreateItem(dataMessage.body);
                Identity identity = Identity.GetIdentity(dataMessage.body, base.Destination as DataDestination);
                dataMessage.identity = identity;
            }
            return(dataMessage);
        }
Esempio n. 31
0
 public DataMessage getDataMessage(TLV tlv)
 {
     try
     {
         if (tlv.type != TLV.Type.Data)
         {
             return(null);
         }
         DataMessage dm = new DataMessage();
         dm.sender = Utils.ToUInt64(tlv.body, 0);
         dm.nonce  = Utils.ToUInt32(tlv.body, 8);
         dm.msg    = Encoding.UTF8.GetString(tlv.body, 12, tlv.body.Length - 12);
         return(dm);
     }
     catch { return(null); }
 }
Esempio n. 32
0
        private object GetItem(DataMessage dataMessage)
        {
            object     result    = null;
            IAssembler assembler = GetAssembler();

            if (assembler != null)
            {
                if (log != null && log.IsDebugEnabled)
                {
                    log.Debug(assembler.GetType().FullName + " GetItem");
                }
                result = assembler.GetItem(dataMessage.identity);
                return(result);
            }
            return(null);
        }
Esempio n. 33
0
        static ObjectApi()
        {
            EmptyNode = new DagNode(new byte[0]);
            var _ = EmptyNode.Id;

            var dm = new DataMessage {
                Type = DataType.Directory
            };

            using (var pb = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize <DataMessage>(pb, dm);
                EmptyDirectory = new DagNode(pb.ToArray());
            }
            _ = EmptyDirectory.Id;
        }
Esempio n. 34
0
        public Sequence RefreshSequence(Sequence sequence, DataMessage dataMessage, object item, DataServiceTransaction dataServiceTransaction)
        {
            if (sequence.Parameters != null)
            {
                DotNetAdapter serviceAdapter = this._dataDestination.ServiceAdapter as DotNetAdapter;
                if (serviceAdapter != null)
                {
                    Identity identity;
                    bool     isCreate = (dataMessage.operation == 0) || (dataMessage.operation == 11);
                    switch (serviceAdapter.RefreshFill(sequence.Parameters, item, isCreate))
                    {
                    case 0:
                        return(sequence);

                    case 1:
                    {
                        IList       parameters = sequence.Parameters;
                        DataMessage message    = new DataMessage {
                            clientId  = dataMessage.clientId,
                            operation = 1,
                            body      = (parameters != null) ? ((object)parameters) : ((object)new object[0])
                        };
                        IList result = this._dataDestination.ServiceAdapter.Invoke(message) as IList;
                        return(this.CreateSequence(dataMessage.clientId as string, result, parameters, dataServiceTransaction));
                    }

                    case 2:
                        identity = Identity.GetIdentity(item, this._dataDestination);
                        if (!sequence.Contains(identity))
                        {
                            this.AddIdentityToSequence(sequence, identity, dataServiceTransaction);
                        }
                        this._itemIdToItemHash[identity] = new ItemWrapper(item);
                        return(sequence);

                    case 3:
                        identity = Identity.GetIdentity(item, this._dataDestination);
                        if (sequence.Contains(identity))
                        {
                            this.RemoveIdentityFromSequence(sequence, identity, dataServiceTransaction);
                        }
                        return(sequence);
                    }
                }
            }
            return(sequence);
        }
Esempio n. 35
0
        public async Task Unary_MultipleLargeMessages_ExceedChannelMaxBufferSize()
        {
            // Arrange
            var sp1     = new SyncPoint(runContinuationsAsynchronously: true);
            var sp2     = new SyncPoint(runContinuationsAsynchronously: true);
            var sp3     = new SyncPoint(runContinuationsAsynchronously: true);
            var channel = CreateChannel(
                serviceConfig: ServiceConfigHelpers.CreateRetryServiceConfig(),
                maxRetryBufferSize: 200,
                maxRetryBufferPerCallSize: 100);

            var request = new DataMessage {
                Data = ByteString.CopyFrom(new byte[90])
            };

            // Act
            var call1Task = MakeCall(Fixture, channel, request, sp1);
            await sp1.WaitForSyncPoint();

            var call2Task = MakeCall(Fixture, channel, request, sp2);
            await sp2.WaitForSyncPoint();

            // Will exceed channel buffer limit and won't retry
            var call3Task = MakeCall(Fixture, channel, request, sp3);
            await sp3.WaitForSyncPoint();

            // Assert
            Assert.AreEqual(194, channel.CurrentRetryBufferSize);

            sp1.Continue();
            sp2.Continue();
            sp3.Continue();

            var response = await call1Task.DefaultTimeout();

            Assert.AreEqual(90, response.Data.Length);

            response = await call2Task.DefaultTimeout();

            Assert.AreEqual(90, response.Data.Length);

            // Can't retry because buffer size exceeded.
            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(() => call3Task).DefaultTimeout();

            Assert.AreEqual(StatusCode.Unavailable, ex.StatusCode);

            Assert.AreEqual(0, channel.CurrentRetryBufferSize);
Esempio n. 36
0
        static void Main(string[] args)
        {
            Service1Client prx = new Service1Client();
            // Para poder usar o TCP Viewer pode intanciar o proxy com outro porto
            //Service1Client prx = new Service1Client("BasicHttpBinding_IService1", "http://localhost:6525/Service1.svc");
            Console.WriteLine("Call Message OneWay=false ");
            Console.WriteLine("Before: "+System.DateTime.Now.ToLongTimeString());
            DataMessage m = new DataMessage();
            m.TextContent="Text"; m.ImageData=new byte[]{1,2,3,4,5};

            prx.DoWork(m.TextContent, m.ImageData);
            Console.WriteLine("After: "+System.DateTime.Now.ToLongTimeString());
            Console.WriteLine("Call OneWay Message");
            Console.WriteLine("Before: "+System.DateTime.Now.ToLongTimeString());
            prx.DoWorkAsOneWay("Luis");
            Console.WriteLine("After: "+System.DateTime.Now.ToLongTimeString());
        }
        private TextSecureGroup createGroupInfo(TextSecureEnvelope envelope, DataMessage content)
        {
            if (!content.HasGroup) return null;

            TextSecureGroup.Type type;

            switch (content.Group.Type)
            {
                case GroupContext.Types.Type.DELIVER: type = TextSecureGroup.Type.DELIVER; break;
                case GroupContext.Types.Type.UPDATE: type = TextSecureGroup.Type.UPDATE; break;
                case GroupContext.Types.Type.QUIT: type = TextSecureGroup.Type.QUIT; break;
                default: type = TextSecureGroup.Type.UNKNOWN; break;
            }

            if (content.Group.Type != GroupContext.Types.Type.DELIVER)
            {
                String name = null;
                IList<String> members = null;
                TextSecureAttachmentPointer avatar = null;

                if (content.Group.HasName)
                {
                    name = content.Group.Name;
                }

                if (content.Group.MembersCount > 0)
                {
                    members = content.Group.MembersList;
                }

                if (content.Group.HasAvatar)
                {
                    avatar = new TextSecureAttachmentPointer(content.Group.Avatar.Id,
                                                             content.Group.Avatar.ContentType,
                                                             content.Group.Avatar.Key.ToByteArray(),
                                                             envelope.getRelay());
                }

                return new TextSecureGroup(type, content.Group.Id.ToByteArray(), name, members, avatar);
            }

            return new TextSecureGroup(content.Group.Id.ToByteArray());
        }
    private bool onReceiveMessage(DataMessage message)
    {
        message.createReader();
        int userId = message.readInt32();
        string userMessage = message.readString();
        message.closeReader();

        ChatUser user = getUser(userId);
        if (user == null)
        {
            user = new ChatUser();
            user.setUnknown(userId);
            users.Add(userId, user);
            requestUserInfo(userId);
        }

        ChatDialogMessage dialogMessage = new ChatDialogMessage(userMessage, user.userId, -1);
        if (dialogs.ContainsKey(userId))
        {
            dialogs[userId].messages.Add(dialogMessage);
        }
        else
        {
            ChatDialogWithUser dialog = new ChatDialogWithUser();
            dialog.withUser = user;
            dialog.messages.Add(dialogMessage);
            dialogs.Add(userId, dialog);
        }
        postUpdate(UiUpdates.ReceivedMessage, dialogMessage);
        return false;
    }
        private TextSecureDataMessage createTextSecureMessage(TextSecureEnvelope envelope, DataMessage content)
        {
            TextSecureGroup groupInfo = createGroupInfo(envelope, content);
            LinkedList<TextSecureAttachment> attachments = new LinkedList<TextSecureAttachment>();
            bool endSession = ((content.Flags & (uint)DataMessage.Types.Flags.END_SESSION) != 0);

            foreach (AttachmentPointer pointer in content.AttachmentsList)
            {
                attachments.AddLast(new TextSecureAttachmentPointer(pointer.Id,
                                                                pointer.ContentType,
                                                                pointer.Key.ToByteArray(),
                                                                envelope.getRelay(),
                                                                pointer.HasSize ? new May<uint>(pointer.Size) : May<uint>.NoValue,
                                                                pointer.HasThumbnail ? new May<byte[]>(pointer.Thumbnail.ToByteArray()) : May<byte[]>.NoValue));
            }

            return new TextSecureDataMessage(envelope.getTimestamp(), groupInfo, attachments,
                                             content.Body, endSession);
        }
 private void requestUserInfo(int userId)
 {
     DataMessage message = new DataMessage(Ids.Services.GAMES, Ids.Actions.SimpleChat.REQUEST_USER_INFO, systemController.getUserInfo().session);
     message.createWriter().writerInt32(GameId).writerInt32(userId).writerInt32(myCallback).closeWriter();
     connection.addMessageToSend(message);
 }
Esempio n. 41
0
    private bool onGameStarted(DataMessage message)
    {
        if (state != SystemControllerStates.WaitGameStart)
            throw new InvalidOperationException("Invalid SystemController state, waiting WaitGameStart, but have : " + state);

        userInfo.session = message.Session;

        if (message !=null && message.Data != null)
        {
            message.createReader();
            int gameId = message.readInt32();
            message.closeReader();

            currentGame.GameId = gameId;
            state = SystemControllerStates.InGame;
            currentGame.startGame();
        }
        return true;
    }
Esempio n. 42
0
            public Data(BinaryReader reader, UInt32 dataSize)
            {
                Waypoints = new List<FITWaypoint>();
                Laps = new List<FITLap>();
                var bytes = reader.ReadBytes((int)dataSize);
                using (var stream = new MemoryStream(bytes))
                {
                  using (var dataReader = new BinaryReader(stream))
                  {
                var recordHeader = new RecordHeader(dataReader);

                if (!recordHeader.IsDefinitionMessage)
                {
                  throw new Exception("First record is not a definition message.");
                }
                var def = new DefinitionMessage(dataReader);
                if (def.GlobalMessageNumber != (ushort) MesgNum.file_id)
                  throw new Exception("First record's global message number is not file_id.");
                recordHeader = new RecordHeader(dataReader);
                if (recordHeader.IsDefinitionMessage)
                  throw new Exception("Encountered a definition message, but expected a data message.");
                var d = new DataMessage(dataReader, def);
                var fileType = d.GetByte(0);
                if (fileType != 4) throw new Exception("Not a FIT activity file.");

                var messageTypeTranslator = new Dictionary<byte, DefinitionMessage>();
                UInt32 lastTimestamp = 0;

                while (dataReader.BaseStream.Position < dataReader.BaseStream.Length)
                {
                  recordHeader = new RecordHeader(dataReader);
                  if (recordHeader.IsDefinitionMessage)
                  {
                def = new DefinitionMessage(dataReader);
                FITUtil.AddOrReplace(messageTypeTranslator, recordHeader.LocalMessageType, def);
                  }
                  else
                  {
                var currentDef = messageTypeTranslator[recordHeader.LocalMessageType];
                d = new DataMessage(dataReader, currentDef);

                var timestamp = d.GetUInt32(253);
                if (timestamp == null) timestamp = FITUtil.AddCompressedTimestamp(lastTimestamp, recordHeader.TimeOffset);
                var time = FITUtil.ToDateTime(timestamp.Value);

                var gmn = currentDef.GlobalMessageNumber;
                if (gmn == (byte) MesgNum.record)
                {
                  var lat = d.GetInt32(0);
                  var lng = d.GetInt32(1);
                  var alt = d.GetUInt16(2);
                  var hr = d.GetByte(3);
                  var cadence = d.GetByte(4);
                  var power = d.GetUInt16(7);
                  if (lng != null && lng != invalidInt32 && lat != null && lat != invalidInt32)
                  {
                    Waypoints.Add(new FITWaypoint()
                                    {
                                      Time = time,
                                      Latitude = positionFactor * lat.Value,
                                      Longitude = positionFactor * lng.Value,
                                      Altitude = alt == null || alt == invalidUInt16 ? (double?)null : (double)alt.Value / 5 - 500,
                                      HeartRate = hr == null || hr == invalidByte ? null : hr,
                                      Cadence = cadence == null || cadence == invalidByte ? null : cadence,
                                      Power = power == null || power == invalidUInt16 ? null : power
                                    });
                  }
                }
                else if (gmn == (byte)MesgNum.lap)
                {
                  Laps.Add(new FITLap() { Time = time });
                }
                else if (gmn == 22)
                {

                }
                lastTimestamp = timestamp.Value;
                  }
                }
                  }
                }
            }
Esempio n. 43
0
 private DataMessage readMessage()
 {
     DataMessage result = null;
     try
     {
         int avalable = connection.Available;
         if (currentMessage == null)
         {
             if (avalable >= minHeaderSize)
             {
                 currentMessage = new DataMessage();
                 currentLenght = reader.ReadInt32();
             }
             else
             {
                 return null;
             }
         }
         if (currentMessage != null)
         {
             if (avalable >= currentLenght)
             {
                 currentMessage.Service = reader.ReadInt32();
                 currentMessage.Action = reader.ReadInt32();
                 int sessionLenght = reader.ReadInt32();
                 if (sessionLenght > 0)
                 {
                     byte[] session = reader.ReadBytes(sessionLenght);
                     currentMessage.Session = Encoding.UTF8.GetString(session);
                 }
                 int dataLenght = reader.ReadInt32();
                 if (dataLenght > 0)
                 {
                     currentMessage.Data = reader.ReadBytes(dataLenght);
                 }
                 result = currentMessage;
                 currentMessage = null;
             }
         }
     }
     catch (Exception ex)
     {
         Debug.LogError("Fail to receive message , error : " + ex);
         fireErrorHandlers(ConnectionErrors.RECEIVE_MESSAGE, "Receive message error", ex);
         result = null;
     }
     return result;
 }
    private bool onReceiveUserInfo(DataMessage message)
    {
        message.createReader();
        int callback = message.readInt32();
        int result = message.readInt32();

        switch(result) {
            case Ids.SystemResults.SUCCESS:
                {
                    int requestedUsedId = message.readInt32();
                    Dictionary<string, object> json = message.readJson();
                    message.closeReader();

                    ChatUser user;
                    if (users.ContainsKey(requestedUsedId))
                    {
                        user = users[requestedUsedId];
                    }
                    else
                    {
                        user = new ChatUser();
                        users.Add(requestedUsedId, user);
                    }
                    if (!user.fromJson(json))
                    {
                        Debug.LogError("ReceiveUserInfo : fail to parse user data for "+requestedUsedId.ToString());
                        user.setUnknown(requestedUsedId);
                    }
                    postUpdate(UiUpdates.UserUpdated, user);
                }
                break;
            case Ids.Actions.SimpleChat.RESULT_NO_USER_WITH_SUCH_ID:
                {
                    int requestedUsedId = message.readInt32();
                    message.closeReader();
                    Debug.LogError("ReceiveUserInfo : requested User not found id: " + requestedUsedId.ToString());
                }
                break;
            case Ids.SystemResults.INVALID_SESSION:
                message.closeReader();
                Debug.LogError("ReceiveUserInfo : Internal error - Invalid session");
                break;
            case Ids.SystemResults.INVALID_DATA:
                message.closeReader();
                Debug.LogError("ReceiveUserInfo : Internal error - Invalid data");
                break;
            case Ids.SystemResults.NO_GAME_WITH_SUCH_ID:
                message.closeReader();
                Debug.LogError("ReceiveUserInfo : Internal error - no game with such id");
                break;
        }

        return false;
    }
 public void sendUserReady()
 {
     DataMessage message = new DataMessage(Ids.Services.GAMES, Ids.Actions.SimpleChat.NEW_USER, systemController.getUserInfo().session);
     message.createWriter().writerInt32(GameId).closeWriter();
     connection.addMessageToSend(message);
 }
    private bool onUserEnter(DataMessage message)
    {
        message.createReader();
        Dictionary<string, object> json = message.readJson();
        message.closeReader();

        ChatUser u = new ChatUser();
        if (u.fromJson(json))
        {
            if (u.userId == systemController.getUserInfo().userId)
            {
                postUpdate(UiUpdates.GameIsReady, null);
            }
            else
            {
                if (!users.ContainsKey(u.userId))
                {
                    users.Add(u.userId, u);
                }
                postUpdate(UiUpdates.NewUser, u);
            }
        }

        return false;
    }
Esempio n. 47
0
 private void notifyAction(DataMessage message)
 {
     if (message != null)
     {
         bool handled = false;
         lock (dataListeners)
         {
             Dictionary<int, DataHandledDelegate> serviceHandlers;
             if (dataListeners.TryGetValue(message.Service, out serviceHandlers))
             {
                 DataHandledDelegate actionHandler;
                 if (serviceHandlers.TryGetValue(message.Action, out actionHandler))
                 {
                     Handler.getInstance().postAction(handleMessage, new KeyValuePair<DataMessage, DataHandledDelegate>(message, actionHandler));
                     handled = true;
                 }
             }
         }
         if (!handled)
         {
             Debug.LogWarning("Connection: unsupported message. Service : " + message.Service.ToString() + ", Action : " + message.Action.ToString());
         }
     }
 }
    public void sendMessage(ChatUser toUser, String textMessage)
    {
        ChatDialogMessage dialogMessage = new ChatDialogMessage(textMessage, systemController.getUserInfo().userId, -1);
        if (dialogs.ContainsKey(toUser.userId))
        {
            dialogs[toUser.userId].messages.Add(dialogMessage);
        }
        else
        {
            ChatDialogWithUser dialog = new ChatDialogWithUser();
            dialog.withUser = toUser;
            dialog.messages.Add(dialogMessage);
            dialogs.Add(toUser.userId, dialog);
        }

        DataMessage message = new DataMessage(Ids.Services.GAMES, Ids.Actions.SimpleChat.SEND_MESSAGE, systemController.getUserInfo().session);
        message.createWriter()
            .writerInt32(GameId)
            .writerInt32(toUser.userId)
            .writerInt32(myCallback)
            .writerString(textMessage)
            .closeWriter();

        connection.addMessageToSend(message);
    }
 public void requestUsersList()
 {
     connection.registerDataListener(Ids.Services.GAMES, Ids.Actions.SimpleChat.REQUEST_USERS_LIST, errorsHandler);
     DataMessage message = new DataMessage(Ids.Services.GAMES, Ids.Actions.SimpleChat.REQUEST_USERS_LIST, systemController.getUserInfo().session);
     message.createWriter().writerInt32(GameId).writerInt32(myCallback).closeWriter();
     connection.addMessageToSend(message);
 }
 public void notifyIAmEnter()
 {
     DataMessage message = new DataMessage(Ids.Services.GAMES, Ids.Actions.SimpleChat.NEW_USER, systemController.getUserInfo().session);
     connection.addMessageToSend(message);
 }
    private bool onMessageSenedResult(DataMessage message)
    {
        message.createReader();
        int result = message.readInt32();
        int callback = message.readInt32();
        message.closeReader();

        if (result != Ids.SystemResults.SUCCESS)
        {
            Debug.LogError("Fail to send message for callback : " + callback.ToString());
        }
        else
        {
            if (callback != myCallback)
            {
                Debug.LogError("receive send message result, but invalid Callback");
            }
        }
        postUpdate(UiUpdates.MessageSended, callback);
        return false;
    }
Esempio n. 52
0
    private bool onRegistrationComplete(DataMessage message)
    {
        RunnableDelegate runnable;

        if (callbacks.TryGetValue(SystemCallbacks.Registration,out runnable) &&
            message!=null && message.Data != null)
        {
            callbacks.Remove(SystemCallbacks.Registration);

            message.createReader();
            int result = message.readInt32();
            message.closeReader();
            switch (result)
            {
                case Ids.UserManagerResults.INVALID_DATA:
                    Handler.getInstance().postAction(runnable, RegistrationResults.InvalidData);
                    break;
                case Ids.UserManagerResults.REGISTER_SUCH_USER_EXIST:
                    Handler.getInstance().postAction(runnable, RegistrationResults.UserExist);
                    break;
                case Ids.UserManagerResults.SUCCESS:
                    Handler.getInstance().postAction(runnable, RegistrationResults.Success);
                    break;
                case Ids.UserManagerResults.REGISTER_UNKNOWN_TYPE:
                case Ids.UserManagerResults.INTERNAL_ERROR:
                    Handler.getInstance().postAction(runnable, RegistrationResults.IntentalServerError);
                    break;
                default:
                    Handler.getInstance().postAction(runnable, RegistrationResults.IntentalServerError);
                    break;
            }
            state = SystemControllerStates.Default;

        }
        return true;
    }
Esempio n. 53
0
    private bool onGameRequestComplete(DataMessage message)
    {
        RunnableDelegate runnable;
        if (callbacks.TryGetValue(SystemCallbacks.RequestGame, out runnable) &&
            message != null && message.Data != null)
        {
            message.createReader();
            int result = message.readInt32();
            message.closeReader();
            callbacks.Remove(SystemCallbacks.RequestGame);

            switch (result)
            {
                case Ids.SystemResults.SUCCESS:
                    currentGame.prepareGame();
                    Handler.getInstance().postAction(runnable, RequestGameResults.Success);
                    state = SystemControllerStates.WaitGameStart;

                    break;
                case Ids.SystemResults.GAME_IS_UNAVALABLE_NOW:
                    Handler.getInstance().postAction(runnable, RequestGameResults.GameIsUnavalble);
                    state = SystemControllerStates.Default;
                    break;
                case Ids.SystemResults.INVALID_DATA:
                case Ids.SystemResults.INVALID_SESSION:
                    Handler.getInstance().postAction(runnable, RequestGameResults.InvalidData);
                    state = SystemControllerStates.Default;
                    break;
                case Ids.SystemResults.INTERNAL_ERROR:
                    Handler.getInstance().postAction(runnable, RequestGameResults.IntentalServerError);
                    state = SystemControllerStates.Default;
                    break;
                default:
                    Handler.getInstance().postAction(runnable, RequestGameResults.IntentalServerError);
                    state = SystemControllerStates.Default;
                    break;
            }
        }
        else
        {
            UnityEngine.Debug.LogError(GetType().Name + ", onGameRequestComplete : can`t get callback or empty message = " + message);
        }
        return true;
    }
    private bool onReceivePlayersList(DataMessage message)
    {
        message.createReader();
        int callback = message.readInt32();

        if (callback != myCallback)
        {
            Debug.LogError("receive users list, but invalid Callback");
        }

        Dictionary<string, object> json = message.readJson();
        message.closeReader();
        object[] usersJson = (object[])json["users"];
        for (int i = 0; i < usersJson.Length; i++)
        {
            ChatUser u = new ChatUser();
            if (u.fromJson((Dictionary<string, object>)usersJson[i]))
            {
                users[u.userId] = u;
            }
        }
        postUpdate(UiUpdates.UpdateUsersList, null);
        sendUserReady();
        return false;
    }
Esempio n. 55
0
    private bool onGameFinished(DataMessage message)
    {
        if (state != SystemControllerStates.InGame)
            throw new InvalidOperationException("Invalid SystemController state, waiting InGame), but have : " + state);

        if (message != null && message.Data != null)
        {
            message.createReader();
            int gameId = message.readInt32();
            int result = message.readInt32();
            Dictionary<string, object> data = message.readJson();
            message.closeReader();

            if (gameId == currentGame.GameId)
            {
                state = SystemControllerStates.Default;
                currentGame.finishGame(result, data);
            }
            else
            {

            }
        }
        return true;
    }
Esempio n. 56
0
    private bool onLoginComplete(DataMessage message)
    {
        RunnableDelegate runnable;
        if (callbacks.TryGetValue(SystemCallbacks.Authorization, out runnable) &&
            message != null && message.Data != null)
        {
            message.createReader();
            int result = message.readInt32();

            callbacks.Remove(SystemCallbacks.Authorization);

            switch (result)
            {
                case Ids.UserManagerResults.INVALID_DATA:
                    message.closeReader();
                    Handler.getInstance().postAction(runnable, LoginResults.InvalidData);
                    break;
                case Ids.UserManagerResults.LOGIN_OR_PASSWORD_INVALID:
                    message.closeReader();
                    Handler.getInstance().postAction(runnable, LoginResults.InvalidLoginOrPassword);
                    break;
                case Ids.UserManagerResults.SUCCESS:
                    {
                        int clientId = message.readInt32();
                        string session = message.Session;
                        message.closeReader();
                        userInfo.session = session;
                        userInfo.userId = clientId;
                        Handler.getInstance().postAction(runnable, LoginResults.Success);
                    }
                    break;
                case Ids.UserManagerResults.REGISTER_UNKNOWN_TYPE:
                case Ids.UserManagerResults.INTERNAL_ERROR:
                    message.closeReader();
                    Handler.getInstance().postAction(runnable, LoginResults.IntentalServerError);
                    break;
                default:
                    message.closeReader();
                    Handler.getInstance().postAction(runnable, LoginResults.IntentalServerError);
                    break;
            }
            state = SystemControllerStates.Default;

        }
        else
        {
            UnityEngine.Debug.LogError(GetType().Name + ", onLoginComplete : can`t get callback or empty message = " + message);
        }
        return true;
    }
Esempio n. 57
0
 public void registerDataListener(DataMessage forMessage, DataHandledDelegate handler)
 {
     registerDataListener(forMessage.Service, forMessage.Action, handler);
 }
    private bool onUserExit(DataMessage message)
    {
        message.createReader();
        int userId = message.readInt32();
        message.closeReader();

        users.Remove(userId);
        dialogs.Remove(userId);
        postUpdate(UiUpdates.UserRemoved, userId);
        return false;
    }
    private bool errorsHandler(DataMessage message)
    {
        message.createReader();
        int result = message.readInt32();
        message.closeReader();

        if (!checkErrorResult(result))
        {
            uiController.getMessageBox().showMessage("Internal error!");
        }

        return true;
    }
Esempio n. 60
0
 private void sendHeartBeat(object param)
 {
     DataMessage message = new DataMessage(Ids.Services.CLIENTS, Ids.Actions.HEART_BEAT_ACTION, null);
     addMessageToSend(message);
 }