Пример #1
0
        public static List <T> unwrapResults <T>(QueryResponse resp) where T : IMessage <T>
        {
            List <T> result = new List <T>();

            if (resp.ProjectionSize > 0)
            {  // Query has select
                return(result);
            }
            for (int i = 0; i < resp.NumResults; i++)
            {
                WrappedMessage wm = resp.Results.ElementAt(i);

                if (wm.WrappedBytes != null)
                {
                    WrappedMessage wmr = WrappedMessage.Parser.ParseFrom(wm.WrappedBytes);
                    if (wmr.WrappedMessageBytes != null)
                    {
                        System.Reflection.PropertyInfo pi = typeof(T).GetProperty("Parser");

                        MessageParser <T> p = (MessageParser <T>)pi.GetValue(null);
                        T u = p.ParseFrom(wmr.WrappedMessageBytes);
                        result.Add(u);
                    }
                }
            }
            return(result);
        }
Пример #2
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (wMsg.Host == "robot.freelance.ru")
            {
                wMsg.Move("Freelance // Freelance.Ru", new List <string> {
                    "Freelance", "Freelance.Ru"
                });
                return;
            }

            if (wMsg.Host == "free-lance.ru" || wMsg.Host.Contains("fl.ru"))
            {
                wMsg.Move("Freelance // FL.ru", new List <string> {
                    "Freelance", "FL.ru"
                });
                return;
            }

            if (wMsg.Host == "headz.io")
            {
                wMsg.Move("Freelance // headz.io", new List <string> {
                    "Freelance", "headz.io"
                });
                return;
            }

            if (wMsg.Host.Contains("upwork.com"))
            {
                wMsg.Move("Freelance // Upwork", new List <string> {
                    "Freelance", "Upwork"
                });
                return;
            }
        }
Пример #3
0
        public static void AliExpress(WrappedMessage wMsg)
        {
            switch (wMsg.SenderAddress)
            {
            case "*****@*****.**":
                wMsg.Move("store // AliExpress // Promo", new List <string> {
                    "stores", "AliExpress", "Promo"
                });
                return;

            case "*****@*****.**":
                wMsg.Move("store // AliExpress // Transaction", new List <string> {
                    "stores", "AliExpress", "Transaction"
                });
                return;
            }

            if (!string.IsNullOrEmpty(wMsg.Message.Subject))
            {
                if (wMsg.Message.Subject.ToLower().Contains("items you liked") ||
                    wMsg.Message.Subject.ToLower().Contains("item you wanted") ||
                    wMsg.Message.Subject.ToLower().Contains("users are interested") ||
                    wMsg.Message.Subject.ToLower().Contains("we miss you") ||
                    wMsg.Message.Subject.ToLower().Contains("being missed") ||
                    wMsg.SenderAddress.Equals("*****@*****.**"))
                {
                    wMsg.Delete();
                }
            }
        }
Пример #4
0
        public void TestFiles(string fileName)
        {
            string filePath = Path.Combine("Mail\\TestFiles", fileName);
            string mailtext = File.ReadAllText(filePath);

            Message message = null;

            Assert.DoesNotThrow(() => message = Message.Load(mailtext));

            if (SMIMEStandard.IsContentMultipartSignature(message.ParsedContentType))
            {
                SignedEntity signedEntity = null;

                Assert.DoesNotThrow(() => signedEntity = SignedEntity.Load(message));
                message.Headers = message.Headers.SelectNonMimeHeaders();
                message.UpdateBody(signedEntity.Content); // this will merge in content + content specific mime headers
            }

            Message extracted = null;

            Assert.DoesNotThrow(() => extracted = WrappedMessage.ExtractInner(message));

            Header to = null;

            Assert.DoesNotThrow(() => to = extracted.To);

            MailAddressCollection addresses = null;

            Assert.DoesNotThrow(() => addresses = MailParser.ParseAddressCollection(to));
            Assert.True(addresses.Count > 0);

            Assert.DoesNotThrow(() => MailParser.ParseMailAddress(extracted.From));
        }
Пример #5
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (!wMsg.Host.EndsWith("mail.ru"))
            {
                return;
            }

            switch (wMsg.SenderName)
            {
            case "Certification":
                wMsg.Move("Mail.ru // Certification", new List <string> {
                    "Mail.ru", "Certification"
                });
                break;

            case "Облако Mail.ru":
                wMsg.Move("Mail.ru // Облако", new List <string> {
                    "Mail.ru", "Облако"
                });
                break;

            case "Ответы@Mail.Ru":
                wMsg.Move("Mail.ru // Ответы", new List <string> {
                    "Mail.ru", "Ответы"
                });
                break;

            case "Почта Mail.ru":
                wMsg.Move("Mail.ru // Почта", new List <string> {
                    "Mail.ru", "Почта"
                });
                break;
            }
        }
        protected override Task ExecuteAsync(CancellationToken cancellationToken)
        {
            if (!cancellationToken.IsCancellationRequested)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var consumer = new AsyncEventingBasicConsumer(Channel);
                consumer.Received += async(ch, ea) =>
                {
                    var message         = WrappedMessage.ToJson(ea.Body);
                    var executionResult = await ProcessMessageDictionary.Execute(message);

                    if (executionResult.Processed)
                    {
                        // If it's invoked as an RPC, enqueue the response to the specified queue
                        if (!string.IsNullOrWhiteSpace(ea.BasicProperties?.ReplyTo))
                        {
                            var messageProperties = Channel.CreateBasicProperties();
                            messageProperties.CorrelationId = ea.BasicProperties.CorrelationId;

                            Channel.BasicPublish(exchange: DefaultExchange.ExchangeName, routingKey: ea.BasicProperties.ReplyTo, basicProperties: messageProperties, body: executionResult.Result);
                        }

                        // Acknowledge the message was processed
                        Channel.BasicAck(ea.DeliveryTag, false);
                    }
                };

                Channel.BasicConsume(MainQueue.QueueName, false, consumer);
            }

            return(Task.CompletedTask);
        }
Пример #7
0
        public static void Politics(WrappedMessage wMsg)
        {
            if (wMsg.Host.EndsWith("change.org"))
            {
                wMsg.Move("News // pol // Change.org", new List <string> {
                    "News", "pol", "Change.org"
                });
                return;
            }

            switch (wMsg.Host)
            {
            case "gorod.io":
                wMsg.Move("News // pol // Горожанин", new List <string> {
                    "News", "pol", "Горожанин"
                });
                return;

            case "5steps.vote":
            case "navalny.com":
            case "rus.vote":
                wMsg.Move("20!8", new List <string> {
                    "News", "pol", "n2018"
                });
                return;
            }
        }
Пример #8
0
        public byte[] ObjectToByteBuffer(object obj)
        {
            if (obj.GetType() == typeof(String))
            {
                return(StringToByteBuffer((String)obj));
            }
            if (obj.GetType() == typeof(int))
            {
                return(IntToByteBuffer((int)obj));
            }
            if (obj.GetType() == typeof(Person))
            {
                Person u = (Person)obj;

                int               size  = u.CalculateSize();
                byte[]            bytes = new byte[size];
                CodedOutputStream cos   = new CodedOutputStream(bytes);
                u.WriteTo(cos);
                cos.Flush();
                WrappedMessage wm = new WrappedMessage();
                wm.WrappedMessageBytes = ByteString.CopyFrom(bytes);
                wm.WrappedDescriptorId = 42;


                byte[]            msgBytes = new byte[wm.CalculateSize()];
                CodedOutputStream msgCos   = new CodedOutputStream(msgBytes);
                wm.WriteTo(msgCos);
                msgCos.Flush();
                return(msgBytes);
            }


            throw new NotImplementedException();
        }
Пример #9
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (wMsg.Host.EndsWith("bspb.ru"))
            {
                wMsg.Move("Banks // Bank SPB", new List <string> {
                    "Banks", "Bank SPB"
                });
            }
            else if (wMsg.Host.EndsWith("raiffeisen.ru"))
            {
                wMsg.Move("Banks // Райффайзенбанк", new List <string> {
                    "Banks", "Райффайзенбанк"
                });
            }

            else if (wMsg.Host.EndsWith("tinkoff.ru"))
            {
                if (wMsg.Message.Subject.Contains("Выписка по дебетовой карте"))
                {
                    wMsg.Move("Banks // Tinkoff // Выписка", new List <string> {
                        "Banks", "Tinkoff", "Выписка"
                    });
                }
                else
                {
                    wMsg.Move("Banks // Tinkoff", new List <string> {
                        "Banks", "Tinkoff"
                    });
                }
            }
        }
Пример #10
0
        void ProcessMessage(OutgoingMessage message)
        {
            if (!WrappedMessage.IsWrapped(message.Message))
            {
                message.Message = message.HasRawMessage ? this.WrapMessage(message.RawMessage) : this.WrapMessage(message.Message);
            }

            if (message.Sender == null)
            {
                throw new OutgoingAgentException(AgentError.NoSender);
            }
            if (!message.HasRecipients)
            {
                throw new OutgoingAgentException(AgentError.NoRecipients);
            }
            //
            // Ensure we support this sender's domain
            //
            if (!m_managedDomains.IsManaged(message.Sender))
            {
                throw new OutgoingAgentException(AgentError.UntrustedSender);
            }
            //
            // Categorize recipients as local/external
            //
            message.EnsureRecipientsCategorizedByDomain(m_managedDomains);
            //
            //
            //
            message.EnsureSenderClassified(m_managedDomains);
            //
            // Bind addresses to Certs etc
            //
            this.BindAddresses(message);
            if (!message.HasRecipients)
            {
                throw new OutgoingAgentException(AgentError.MissingTo);
            }
            //
            // Enforce the trust model.
            //
            m_trustModel.Enforce(message);
            //
            // Remove any non-trusted recipients
            //
            message.CategorizeRecipientsByTrust(m_minTrustRequirement);
            if (!message.HasRecipients)
            {
                throw new OutgoingAgentException(AgentError.NoTrustedRecipients);
            }
            //
            // And update routing headers to remove any recipients we had yanked
            //
            message.UpdateRoutingHeaders();
            //
            // Finally, sign and encrypt the message
            //
            this.SignAndEncryptMessage(message);
        }
Пример #11
0
        Message WrapMessage(string messageText)
        {
            if (!m_wrappingEnabled)
            {
                return(MimeSerializer.Default.Deserialize <Message>(messageText));
            }

            return(WrappedMessage.Create(messageText, DirectStandard.MailHeadersUsed));
        }
Пример #12
0
 public static void Beeline(WrappedMessage wMsg)
 {
     if (wMsg.SenderAddress == "*****@*****.**")
     {
         wMsg.Move("Beeline", new List <string> {
             "beeline"
         });
         return;
     }
 }
Пример #13
0
 public static void Filter(WrappedMessage wMsg)
 {
     if (wMsg.SenderAddress.EndsWith("gosuslugi.ru") ||
         wMsg.SenderAddress.EndsWith("service-nalog.ru"))
     {
         wMsg.Move("GosUslugi", new List <string> {
             "ГосУслуги"
         });
     }
 }
Пример #14
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (wMsg.SenderAddress != "*****@*****.**")
            {
                return;
            }

            wMsg.Move("Work // Trilimes", new List <string> {
                "Work", "Trilimes"
            });
        }
Пример #15
0
 public static void Filter(WrappedMessage wMsg)
 {
     switch (wMsg.SenderAddress)
     {
     case "*****@*****.**":
         wMsg.Move("Tmp", new List <string> {
             "tmp"
         });
         break;
     }
 }
Пример #16
0
        public override void OnMessage(WrappedMessage message, int from)
        {
            short msgType = message.messageType;

            if (msgType == MsgType.EndTurn)
            {
                OnEndTurnMessage();
            }
            else
            {
                base.OnMessage(message, from);
            }
        }
        private async Task <byte[]> Work(ExampleMessage1 message)
        {
            Logger.LogInformation($"Work1: {message.SentMessage} / {message.Date} - @{DateTime.Now}");

            var result = new ExampleResponse1()
            {
                ProcessedDate    = DateTime.Now,
                ProcessedMessage = message
            };

            var resultBody = WrappedMessage.Wrap(ExampleResponse1.TypeID, result).ToBytes();

            return(await Task.FromResult(resultBody));
        }
Пример #18
0
        Message WrapMessage(Message message)
        {
            if (!m_wrappingEnabled)
            {
                return(message);
            }

            if (WrappedMessage.IsWrapped(message))
            {
                return(message);
            }

            return(WrappedMessage.Create(message, DirectStandard.MailHeadersUsed));
        }
Пример #19
0
        Message UnwrapMessage(Message message)
        {
            if (!m_wrappingEnabled)
            {
                return(message);
            }

            if (m_allowNonWrappedIncoming && !WrappedMessage.IsWrapped(message))
            {
                return(message);
            }

            return(WrappedMessage.ExtractInner(message));
        }
Пример #20
0
        public ExampleResponse1 SendAndWaitResponse_WithRPC(string message)
        {
            var responseQueue = new BlockingCollection <ExampleResponse1>();

            var content = new ExampleMessage1()
            {
                SentMessage = message,
                Date        = DateTime.Now
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    DelayedBy5SecondsQueue.DeclareQueue(channel);

                    // Create a new queue to await the results. The created queue has a unique name, is temporary and can be consumed exclusively to this channel. That way we can avoid other channels "stealing" the results of this call
                    var temporaryResponseQueue = channel.QueueDeclare(exclusive: true);
                    var responseQueueName      = temporaryResponseQueue.QueueName;

                    // CorrelationID should be a unique code, shared between the send and returned message
                    var correlationId = Guid.NewGuid().ToString("n");

                    // Send the message
                    var messageProperties = channel.CreateBasicProperties();
                    messageProperties.CorrelationId = correlationId;
                    messageProperties.ReplyTo       = responseQueueName;

                    var body = WrappedMessage.Wrap(ExampleMessage1.TypeID, content).ToBytes();
                    channel.BasicPublish(exchange: DefaultExchange.ExchangeName, routingKey: DelayedBy5SecondsQueue.QueueName, basicProperties: messageProperties, body: body);

                    // Listen to the response queue to receive the result data
                    var consumer = new EventingBasicConsumer(channel);
                    consumer.Received += (ch, ea) =>
                    {
                        if (ea.BasicProperties.CorrelationId == correlationId)
                        {
                            var response = WrappedMessage <ExampleResponse1> .Unwrap(ea.Body);

                            channel.BasicAck(ea.DeliveryTag, false);
                            responseQueue.Add(response);
                        }
                    };

                    channel.BasicConsume(responseQueueName, false, consumer);

                    // Any call that halts the execution until the response is received works
                    return(responseQueue.Take());
                }
        }
Пример #21
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (wMsg.Host != "dev.indins.ru")
            {
                return;
            }

            if (wMsg.Message.Subject.StartsWith("Access to the ") && wMsg.Message.Subject.EndsWith(" project was granted"))
            {
                wMsg.Move("Gitlab // Access granted", new List <string> {
                    "Gitlab", "Access granted"
                });
                return;
            }
        }
Пример #22
0
        public static void Filter(WrappedMessage wMsg)
        {
            Beeline(wMsg);
            Cian(wMsg);
            RussianPost(wMsg);

            if (wMsg.Host == "beget.com" ||
                wMsg.Host == "beget.ltd" ||
                wMsg.Host == "beget.ru")
            {
                wMsg.Move("BeGet", new List <string> {
                    "beget"
                });
            }
        }
Пример #23
0
        public object ObjectFromByteBuffer(byte[] buf)
        {
            WrappedMessage wm = WrappedMessage.Parser.ParseFrom(buf);

            switch (wm.WrappedDescriptorId)
            {
            case 42:
                return(Person.Parser.ParseFrom(wm.WrappedMessageBytes));
            }
            base_types bt = base_types.Parser.ParseFrom(buf);

            return(bt);

            throw new NotImplementedException();
        }
Пример #24
0
        public static void Avito(WrappedMessage wMsg)
        {
            if (wMsg.SenderAddress != "*****@*****.**")
            {
                return;
            }

            switch (wMsg.Message.Subject.ToLower())
            {
            case "вам пришло новое сообщение":
            case "вам пришли новые сообщения":
                wMsg.Move("store // Avito // New message", new List <string> {
                    "stores", "Avito", "New message"
                });
                return;

            case "завтра объявление опубликуется заново":
                wMsg.Move("store // Avito // Ad renew", new List <string> {
                    "stores", "Avito", "Ad renew"
                });
                return;

            case "новые объявления":
                wMsg.Move("store // Avito // New ads", new List <string> {
                    "stores", "Avito", "New ads"
                });
                return;

            case "подтверждение подписки на сохраненный поиск":
                wMsg.Move("store // Avito // Subscription Confirmation", new List <string> {
                    "stores", "Avito", "Subscription Confirmation"
                });
                return;
            }

            if (wMsg.Message.Subject.Contains("Персональная подборка автомобилей"))
            {
                wMsg.Move("store // Avito // New ads // Cars", new List <string> {
                    "stores", "Avito", "New ads", "Cars"
                });
            }
            else if (wMsg.Message.Subject.Contains("Не пропустите подборку интересных объявлений"))
            {
                wMsg.Move("store // Avito // New ads", new List <string> {
                    "stores", "Avito", "New ads"
                });
            }
        }
Пример #25
0
        public void SendExampleMessage2()
        {
            var content = new ExampleMessage2()
            {
                Guid = Guid.NewGuid()
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    MainQueue.DeclareQueue(channel);

                    var body = WrappedMessage.Wrap(ExampleMessage2.TypeID, content).ToBytes();
                    channel.BasicPublish(exchange: DefaultExchange.ExchangeName, routingKey: MainQueue.QueueName, basicProperties: null, body: body);
                }
        }
Пример #26
0
        internal void ContinuousQueryListenerFunction(ClientCacheEntryCustomEvent ev)
        {
            byte[] data = ev.GetEventData();
            try
            {
                WrappedMessage        wm = WrappedMessage.Parser.ParseFrom(data);
                ContinuousQueryResult r  = ContinuousQueryResult.Parser.ParseFrom(wm.WrappedMessageBytes);
                ContinuousQueryResult.Types.ResultType t = r.ResultType;
                K k = (K)marshaller.ObjectFromByteBuffer(r.Key.ToByteArray());
                V v = default(V);
                if (r.Projection.Count != 0)
                {
                    WrappedMessage[] awm = r.Projection.ToArray();
                    object[]         ret = new object[awm.Length];
                    for (var i = 0; i < awm.Length; i++)
                    {
                        ret[i] = marshaller.ObjectFromByteBuffer(awm[i].ToByteArray());
                    }
                    v = (V)(object)ret;
                }
                else
                {
                    v = (V)marshaller.ObjectFromByteBuffer(r.Value.ToByteArray());
                }
                switch (t)
                {
                case ContinuousQueryResult.Types.ResultType.Joining:
                    JoiningCallback(k, v);
                    break;

                case ContinuousQueryResult.Types.ResultType.Leaving:
                    LeavingCallback(k, v);
                    break;

                case ContinuousQueryResult.Types.ResultType.Updated:
                    UpdatedCallback(k, v);
                    break;

                default:
                    break;
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #27
0
        public static void Filter(WrappedMessage wMsg)
        {
            if (wMsg.Host.Contains("atlassian.net"))
            {
                wMsg.Move("Jira", new List <string> {
                    "Jira"
                });
                return;
            }

            if (wMsg.Host == "bitbucket.org")
            {
                wMsg.Move("Bitbucket", new List <string> {
                    "Bitbucket"
                });
            }
        }
Пример #28
0
        public override void OnMessage(WrappedMessage message)
        {
            short msgType = message.messageType;

            if (msgType == MsgType.ServerUpdate)
            {
                if (!isHosted)
                {
                    var newState = message.ReadExtraMessage <GameState>();
                    Match.UpdateState(newState);
                }
            }
            else
            {
                base.OnMessage(message);
            }
        }
Пример #29
0
        public void SendExampleMessage1_WithDelay(string name)
        {
            var content = new ExampleMessage1()
            {
                SentMessage = name,
                Date        = DateTime.Now
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // Delay configuration is done inside the queue declaration
                    DelayedBy5SecondsQueue.DeclareQueue(channel);

                    var body = WrappedMessage.Wrap(ExampleMessage1.TypeID, content).ToBytes();
                    channel.BasicPublish(exchange: DefaultExchange.ExchangeName, routingKey: DelayedBy5SecondsQueue.QueueName, basicProperties: null, body: body);
                }
        }
Пример #30
0
        public static void RussianPost(WrappedMessage wMsg)
        {
            if (wMsg.SenderAddress == "*****@*****.**")
            {
                wMsg.Move("RussianPost", new List <string> {
                    "Почта России"
                });
                return;
            }

            if (wMsg.SenderAddress == "*****@*****.**")
            {
                wMsg.Move("RussianPost // News", new List <string> {
                    "Почта России", "Новости"
                });
                return;
            }
        }
        private byte[] ObjectToByteBuffer(int descriptorId, object obj)
        {
            IMessage u = (IMessage)obj;

            int size = u.CalculateSize();
            byte[] bytes = new byte[size];
            CodedOutputStream cos = new CodedOutputStream(bytes);
            u.WriteTo(cos);
            
            cos.Flush();
            WrappedMessage wm = new WrappedMessage();
            wm.WrappedMessageBytes = ByteString.CopyFrom(bytes);
            wm.WrappedDescriptorId = descriptorId;

            byte[] msgBytes = new byte[wm.CalculateSize()];
            CodedOutputStream msgCos = new CodedOutputStream(msgBytes);
            wm.WriteTo(msgCos);
            msgCos.Flush();
            return msgBytes;
        }
Пример #32
0
        public void EqHybridQueryWithParamTest()
        {
            IRemoteCache<int, User> userCache = remoteManager.GetCache<int, User>(NAMED_CACHE);
            
            QueryRequest.Types.NamedParameter param = new QueryRequest.Types.NamedParameter();
            WrappedMessage wm = new WrappedMessage();
            wm.WrappedString = "Doe";
            param.Name = "surnameParam";
            param.Value = wm;

            QueryRequest qr = new QueryRequest();
            // JpqlString will be deprecated please use QueryString
	    // qr.JpqlString = "from sample_bank_account.User u where (u.notes = \"Lorem ipsum dolor sit amet\") and (u.surname = :surnameParam)";
            qr.QueryString = "from sample_bank_account.User u where (u.notes = \"Lorem ipsum dolor sit amet\") and (u.surname = :surnameParam)";
            qr.NamedParameters.Add(param);

            QueryResponse result = userCache.Query(qr);
            List<User> listOfUsers = RemoteQueryUtils.unwrapResults<User>(result);

            Assert.AreEqual(1, listOfUsers.Count);
            Assert.AreEqual(1, listOfUsers.ElementAt(0).Id);
        }