コード例 #1
0
 public async Task PublishMultipleWorks()
 {
     var message1 = new byte[] { 1, 1, 1 };
     var message2 = new byte[] { 2, 2, 2 };
     MessageBody[] messages = new MessageBody[] { message1, message2 };
     await prod.PublishAsync(options.Topic, messages);
 }
コード例 #2
0
        protected override IList<HeaderInfo> DecodeHeader(MessageBody message)
        {
            var headerDecoder = new MessageHeaderDecoder(decoder, message);
            HeaderContent = headerDecoder.RawHeader;

            return headerDecoder.DecodedHeaders;
        }
コード例 #3
0
        public override IRemoteSupplier lookup(System.String supplierName)
        {
            MessageEnvelope message = new MessageEnvelope();
            MessageBody body = new MessageBody();

            LookupRequest request = new LookupRequest();
            request.SupplierName = supplierName;

            body.selectLookupRequest(request);
            message.Body = body;
            message.Id = this.ToString();

            IRemoteSupplier supplier = null;
            lock (clients)
            {
                foreach(ITransport client in clients)
                {
                    MessageEnvelope result = client.call(message, callTimeout);
                    if (result.Body.LookupResult.Code.Value == LookupResultCode.EnumType.success)
                    {
                        supplier = new RemoteSupplier(supplierName, client);
                        break;
                    }
                }
            }

            if (supplier == null)
                throw new Exception("Error when accessing to supplier '" + supplierName + "'! Unable to find any suitable supplier!");
            return supplier;
        }
コード例 #4
0
        protected virtual IList<HeaderInfo> DecodeHeader(MessageBody message)
        {
            var headers = message.HeaderRaw;
            var decodedResult = decoder.Decode(headers);

            return decodedResult.IsParsed ? decodedResult.Value : new HeaderInfo[0];
        }
コード例 #5
0
        public MessageBody MapBody(Message source)
        {
            var m = new MessageBody(source.Id, source.Label, source.SentTime)
            {
                BodyRaw       = source.BodyStream.GetAsBytes(),
                HeaderRaw     = source.Extension,
                CorrelationId = source.CorrelationId,
                TransactionId = source.TransactionId,
                Destination   = source.DestinationQueue == null ? null : MapQueue(source.DestinationQueue),
                Response      = source.ResponseQueue == null ? null : MapQueue(source.ResponseQueue),
            };

            return(m);
        }
コード例 #6
0
        public Message MapToMessage(HeartbeatRequest request)
        {
            var header = new MessageHeader(
                messageId: request.Id,
                topic: "Heartbeat",
                messageType: MessageType.MT_COMMAND,
                correlationId: request.ReplyAddress.CorrelationId, replyTo: request.ReplyAddress.Topic);

            var json    = new JObject(new JProperty("Id", request.Id));
            var body    = new MessageBody(json.ToString());
            var message = new Message(header, body);

            return(message);
        }
        /// <inheritdoc/>
        public async Task ProcessNotificationEntities(string applicationName, IList <EmailNotificationItemEntity> notificationEntities)
        {
            var traceprops = new Dictionary <string, string>();

            traceprops[AIConstants.Application] = applicationName;
            traceprops[AIConstants.MeetingNotificationCount] = notificationEntities?.Count.ToString(CultureInfo.InvariantCulture);

            this.logger.TraceInformation($"Started {nameof(this.ProcessNotificationEntities)} method of {nameof(DirectSendNotificationProvider)}.", traceprops);
            if (notificationEntities is null || notificationEntities.Count == 0)
            {
                throw new ArgumentNullException(nameof(notificationEntities), "notificationEntities are null.");
            }

            foreach (var item in notificationEntities)
            {
                item.EmailAccountUsed = item.From;
                item.TryCount++;
                item.ErrorMessage = string.Empty; // Reset the error message on next retry.
                try
                {
                    var         sendForReal = this.mailSettings.Find(a => a.ApplicationName == applicationName).SendForReal;
                    var         toOverride  = this.mailSettings.Find(a => a.ApplicationName == applicationName).ToOverride;
                    MessageBody body        = await this.emailManager.GetNotificationMessageBodyAsync(applicationName, item).ConfigureAwait(false);

                    DirectSend.Models.Mail.EmailMessage message = item.ToDirectSendEmailMessage(body, this.directSendSetting);
                    if (!sendForReal)
                    {
                        message.ToAddresses = toOverride.Split(Common.ApplicationConstants.SplitCharacter, System.StringSplitOptions.RemoveEmptyEntries)
                                              .Select(torecipient => new DirectSend.Models.Mail.EmailAddress {
                            Address = torecipient
                        }).ToList();
                        message.CcAddresses = null;
                    }

                    await this.mailService.SendEmailAsync(message).ConfigureAwait(false);

                    item.Status = NotificationItemStatus.Sent;
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    this.logger.WriteCustomEvent($"{AIConstants.CustomEventMailSendFailed} for notificationId:  {item.NotificationId} ");
                    item.Status       = NotificationItemStatus.Failed;
                    item.ErrorMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
                }
            }

            this.logger.TraceInformation($"Finished {nameof(this.ProcessNotificationEntities)} method of {nameof(DirectSendNotificationProvider)}.", traceprops);
        }
コード例 #8
0
        public Message MapToMessage(GreetingRequest request)
        {
            var header = new MessageHeader(
                messageId: request.Id,
                topic: "Greeting.Request",
                messageType: MessageType.MT_COMMAND,
                correlationId: request.ReplyAddress.CorrelationId,
                replyTo: request.ReplyAddress.Topic);

            var body    = new MessageBody(JsonSerializer.Serialize(new GreetingsRequestBody(request.Id.ToString(), request.Name, request.Language), JsonSerialisationOptions.Options));
            var message = new Message(header, body);

            return(message);
        }
コード例 #9
0
        private void UpdateSFDZT(MessageBody body)
        {
            SFInfo_DAL dal = new SFInfo_DAL();

            List <DJ_SFD> list = new List <DJ_SFD>();

            if (body.JFInfoList != null && body.JFInfoList.Count > 0)
            {
                foreach (JFInfoModel m in body.JFInfoList)
                {
                    //DJ_SFD sfd = GetSFD(m.SLBH);
                }
            }
        }
コード例 #10
0
        public Message MapToMessage(MyResponse request)
        {
            var header = new MessageHeader(
                messageId: request.Id,
                topic: request.SendersAddress.Topic,
                messageType: MessageType.MT_COMMAND,
                correlationId: request.SendersAddress.CorrelationId);

            var json    = new JObject(new JProperty("Id", request.Id), new JProperty("ReplyValue", request.ReplyValue));
            var body    = new MessageBody(json.ToString());
            var message = new Message(header, body);

            return(message);
        }
コード例 #11
0
        private static async Task UploadFile(MessageBody msg, JArray results)
        {
            Console.WriteLine(results);
            var putReq = new PutObjectRequest()
            {
                BucketName  = msg.DestBucketName,
                Key         = $"{AWS_BATCH_JOB_ID}-{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}-{msg.SourceKeyName}.json",
                ContentBody = results.ToString(),
                ContentType = "application/json"
            };
            var req = await s3Client.PutObjectAsync(putReq);

            System.Console.WriteLine(req.HttpStatusCode);
        }
コード例 #12
0
ファイル: Playfield.cs プロジェクト: Algorithman/TestCellAO
 /// <summary>
 /// </summary>
 /// <param name="messageBody">
 /// </param>
 /// <param name="dontSend">
 /// </param>
 public void AnnounceOthers(MessageBody messageBody, Identity dontSend)
 {
     foreach (IInstancedEntity entity in this.Entities)
     {
         var character = entity as Character;
         if (character != null)
         {
             if (character.Identity != dontSend)
             {
                 character.Send(messageBody);
             }
         }
     }
 }
コード例 #13
0
 public async Task SendtoAll(List <string> id, MessageBody messageBody)
 {
     foreach (var item in id)
     {
         if (_sockets.ContainsKey(item))
         {
             var   message = JsonConvert.SerializeObject(messageBody);
             var   buffer  = Encoding.UTF8.GetBytes(message);
             await _sockets[item].SendAsync(new ReadOnlyMemory <byte>(buffer), WebSocketMessageType.Text
                                            , true
                                            , CancellationToken.None);
         }
     }
 }
コード例 #14
0
        internal override string GetPowerShellCommand()
        {
            // [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('Your_Desired_Message','Your_Desired_Title');
            var sb = new System.Text.StringBuilder("[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('");

            sb.Append(MessageBody.Replace("'", "''"));
            if (Title != null)
            {
                sb.Append("','");
                sb.Append(Title.Replace("'", "''"));
            }
            sb.Append("'); ");
            return(sb.ToString());
        }
コード例 #15
0
        /// <summary>
        /// Get Notification Message Body Async.
        /// </summary>
        /// <param name="applicationName">Application sourcing the email notification.</param>
        /// <param name="notification">email notification item entity.</param>
        /// <returns>
        /// A <see cref="Task{TResult}" /> representing the result of the asynchronous operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// applicationName - applicationName cannot be null or empty.
        /// or
        /// notification - notification cannot be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// TemplateData cannot be null or empty.
        /// or
        /// Template cannot be found, please provide a valid template and application name.
        /// </exception>
        private async Task <MessageBody> GetNotificationMessageBodyAsync(string applicationName, EmailNotificationItemEntity notification)
        {
            this.logger.TraceInformation($"Started {nameof(this.GetNotificationMessageBodyAsync)} method of {nameof(EmailManager)}.");
            string notificationBody = null;

            try
            {
                if (string.IsNullOrEmpty(applicationName))
                {
                    throw new ArgumentNullException(nameof(applicationName), "applicationName cannot be null or empty.");
                }

                if (notification is null)
                {
                    throw new ArgumentNullException(nameof(notification), "notification cannot be null.");
                }

                if (string.IsNullOrEmpty(notification.Body) && !string.IsNullOrEmpty(notification.TemplateId))
                {
                    MailTemplate template = await this.templateManager.GetMailTemplate(applicationName, notification.TemplateId).ConfigureAwait(false);

                    if (template == null)
                    {
                        throw new ArgumentException("Template cannot be found, please provide a valid template and application name");
                    }

                    notificationBody = this.templateMerge.CreateMailBodyUsingTemplate(template.TemplateType, template.Content, notification.TemplateData);
                }
                else
                {
                    if (!string.IsNullOrEmpty(notification.Body))
                    {
                        notificationBody = notification.Body;
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.WriteException(ex);
                throw;
            }

            MessageBody messageBody = new MessageBody {
                Content = notificationBody, ContentType = Common.ApplicationConstants.EmailBodyContentType
            };

            this.logger.TraceInformation($"Finished {nameof(this.GetNotificationMessageBodyAsync)} method of {nameof(EmailManager)}.");
            return(messageBody);
        }
コード例 #16
0
        /// <summary>
        /// </summary>
        /// <param name="messageBody">
        /// </param>
        public void SendInitiateCompressionMessage(MessageBody messageBody)
        {
            // TODO: Investigate if reciever is a timestamp
            var message = new Message
            {
                Body   = messageBody,
                Header =
                    new Header
                {
                    MessageId  = 0xdfdf,
                    PacketType = messageBody.PacketType,
                    Unknown    = 0x0001,

                    // TODO: Make compression choosable in config.xml
                    Sender = 0x01000000,

                    // 01000000 = uncompressed, 03000000 = compressed
                    Receiver = 0                   // this.character.Identity.Instance
                }
            };

            byte[] buffer = this.messageSerializer.Serialize(message);

            if (Program.DebugNetwork)
            {
                LogUtil.Debug(NiceHexOutput.Output(buffer));
            }

            this.packetNumber = 1;

            this.Send(buffer);

            // Now create the compressed stream
            try
            {
                if (!this.zStreamSetup)
                {
                    // CreateIM the zStream
                    this.netStream         = new NetworkStream(this.TcpSocket);
                    this.zStream           = new ZOutputStream(this.netStream, zlibConst.Z_BEST_SPEED);
                    this.zStream.FlushMode = zlibConst.Z_SYNC_FLUSH;
                    this.zStreamSetup      = true;
                }
            }
            catch (Exception e)
            {
                LogUtil.ErrorException(e);
            }
        }
コード例 #17
0
        private bool IsOnPosZ(float trigpos)
        {
            bool      rect  = false;
            Stopwatch watch = new Stopwatch();

            try
            {
                watch.Start();
                float curPos;// = Manager.IMotorCtrl.GetAxisZPosUm() / 1000; ;
                while (true)
                {
                    if (Manager.IMotorCtrl.IsAxisRun(3))
                    {
                        Thread.Sleep(5);
                        continue;
                    }
                    else
                    {
                        break;
                    }
                    //curPos = Manager.IMotorCtrl.GetAxisZPosUm() / 1000; 20181213,顾叶俊
                    curPos = Manager.IMotorCtrl.GetAxisZPosUmEx() / 1000;
                    if (IsAbort)
                    {
                        break;
                    }
                    if (Math.Abs(trigpos - curPos) < 1)
                    {
                        break;
                    }
                    if (watch.ElapsedMilliseconds > TIMEOUT)
                    {
                        watch.Stop();
                        LogHelper.AppLoger.ErrorFormat("on z pos check time out.pls check.");
                        MessageBody msg = new MessageBody();
                        msg.type = MsgType.Error;
                        msg.msg  = "IsOnPostZ Time out .Plase check";
                        ThrowMessage(msg);
                        break;
                    }
                }
                rect = true;
            }
            catch (Exception ex)
            {
                LogHelper.AppLoger.Error(ex);
            }
            return(rect);
        }
コード例 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static async System.Threading.Tasks.Task Send <T>(IHubContext <T> context, Exception ex) where T : Hub
        {
            var category = "App";

            if (ex.GetType().IsSubclassOf(typeof(DbException)))
            {
                category = "DB";
            }
            var message = new MessageBody()
            {
                Category = category, Message = ex.Message
            };

            await Send(context.Clients.All, message);
        }
コード例 #19
0
        public MessageEnvelope createMessage(String vl)
        {
            MessageEnvelope message = new MessageEnvelope();

            message.Id = "MsgId-" + vl;
            MessageBody     msgBody  = new MessageBody();
            MessageUserBody userBody = new MessageUserBody();

            userBody.UserBody   = new byte[] { (byte)0xFF, (byte)0xFE };
            userBody.ConsumerId = this.ToString();
            userBody.QueuePath  = "testQueuePath/Temp";
            msgBody.selectMessageUserBody(userBody);
            message.Body = msgBody;
            return(message);
        }
コード例 #20
0
    // 处理消息
    public void Execute(MessageBody data)
    {
        // Debug.LogWarning("S2C commandId : " + data.commandId);
        // Debug.LogWarning("S2C msg : " + System.Text.Encoding.UTF8.GetString(data.msg));

        // 获取所有 handlers
        List <IHandler> handlers = GetHandlers(data.commandId);

        // 遍历所有 handlers
        foreach (var handler in handlers)
        {
            // handler 执行各自的方法
            handler.Execute(data);
        }
    }
コード例 #21
0
        internal override void Unlock(MessageBody messageBody)
        {
            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Unlocking {0}.", this);
            }

            // if gathered and released then data file has to be deleted
            var result = DataFileServant.Instance.TryDeleteFile(Path);

            if (!result)
            {
                messageBody.DataFile = new AwaitingRetryDataFile(this);
            }
        }
コード例 #22
0
        public void Handle(SelectedMessageChanged @event)
        {
            SelectedMessage = @event.Message;
            ClearHeaderValues();

            if (SelectedMessage == null)
            {
                Headers = null;
            }
            else
            {
                Headers = DecodeHeader(SelectedMessage);
                OnItemsLoaded();
            }
        }
コード例 #23
0
        public void Handle(SelectedMessageChanged @event)
        {
            SelectedMessage = @event.Message;
            ClearHeaderValues();

            if (SelectedMessage == null)
            {
                Headers = null;
            }
            else
            {
                Headers = DecodeHeader(SelectedMessage);
                OnItemsLoaded();
            }
        }
        public void Establish()
        {
            _mapper = new HeartbeatRequestCommandMessageMapper();
            var messageHeader = new MessageHeader(
                messageId: Guid.NewGuid(),
                topic: "Heartbeat",
                messageType: MessageType.MT_COMMAND,
                timeStamp: DateTime.UtcNow,
                correlationId: _correlationId, replyTo: TOPIC);

            var body        = String.Format("\"Id\": \"{0}\"", _commandId);
            var messageBody = new MessageBody("{" + body + "}");

            _message = new Message(header: messageHeader, body: messageBody);
        }
コード例 #25
0
        public HeartbeatMessageToRequestTests()
        {
            _mapper = new HeartbeatRequestCommandMessageMapper();
            var messageHeader = new MessageHeader(
                Guid.NewGuid(),
                "Heartbeat",
                MessageType.MT_COMMAND,
                DateTime.UtcNow,
                _correlationId, TOPIC);

            var body        = String.Format("\"Id\": \"{0}\"", _commandId);
            var messageBody = new MessageBody("{" + body + "}");

            _message = new Message(messageHeader, messageBody);
        }
コード例 #26
0
        public Message MapToMessage(HeartbeatRequest request)
        {
            var header = new MessageHeader(
                messageId: request.Id,
                topic: "Heartbeat",
                messageType: MessageType.MT_COMMAND,
                correlationId: request.ReplyAddress.CorrelationId,
                replyTo: request.ReplyAddress.Topic);

            var json    = JsonSerializer.Serialize(new HeartBeatRequestBody(request.Id.ToString()), JsonSerialisationOptions.Options);
            var body    = new MessageBody(json);
            var message = new Message(header, body);

            return(message);
        }
コード例 #27
0
ファイル: CQCodeUtil.cs プロジェクト: DeepOceanSoft/Sora
    /// <summary>
    /// 序列化某一个消息
    /// </summary>
    /// <param name="msg">消息</param>
    /// <param name="elementsIndex">消息段在字符串中的索引</param>
    public static string SerializeMessage(this MessageBody msg, out int[] elementsIndex)
    {
        var sb = new StringBuilder();

        int[] index = new int[msg.Count];

        for (int i = 0; i < msg.Count; i++)
        {
            index[i] = sb.Length;
            sb.Append(msg[i].SerializeSegment());
        }

        elementsIndex = index;
        return(sb.ToString());
    }
コード例 #28
0
        public void GivenTwoSameRecipients_ShouldStoreOne()
        {
            const string emailAddress = "*****@*****.**";
            var          recipient    = new EmailAddress(emailAddress);
            var          recipient2   = new EmailAddress(emailAddress);

            var message = EmailMessage.CreatePending(subject: "Test",
                                                     body: MessageBody.CreateTextBody("This is test message"),
                                                     sender: new EmailAddress("*****@*****.**"),
                                                     recipients: new[] { recipient });

            message.AddRecipient(recipient2);

            Assert.That(message.Recipients.Count(), Is.EqualTo(1));
        }
コード例 #29
0
ファイル: MessageForm.cs プロジェクト: kekici/EwsEditor
        private bool MakeResponseMessage(ResponseMessageType oResponseMessageType)
        {
            bool            bRet             = false;
            MessageBody     oMessageBody     = new MessageBody("----\r\n");
            ResponseMessage oResponseMessage = null;

            string sWindowTitle = string.Empty;

            try
            {
                if (oResponseMessageType == ResponseMessageType.Reply)
                {
                    _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                    oResponseMessage = _EmailMessage.CreateReply(false);
                    sWindowTitle     = "Reply Message";
                }
                if (oResponseMessageType == ResponseMessageType.ReplyAll)
                {
                    _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                    oResponseMessage = _EmailMessage.CreateReply(true);
                    sWindowTitle     = "Reply All Message";
                }
                if (oResponseMessageType == ResponseMessageType.Forward)
                {
                    _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                    oResponseMessage = _EmailMessage.CreateForward();
                    sWindowTitle     = "Forward Message";
                }

                //oResponseMessage.BodyPrefix = "===========\r\n";

                // Save as drafts AND set as new current message.
                _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                _EmailMessage = oResponseMessage.Save(WellKnownFolderName.Drafts);
                _EmailMessage.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                _EmailMessage.Load();

                SetFormFromMessage(_EmailMessage, true, true, false);

                bRet = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error creating message");
                bRet = false;
            }
            return(bRet);
        }
コード例 #30
0
        public Message Create(string redisMessage)
        {
            var message = new Message();

            if (redisMessage.IsNullOrEmpty())
            {
                return(message);
            }

            using (var reader = new StringReader(redisMessage))
            {
                var header = reader.ReadLine();
                if (header.TrimEnd() != "<HEADER")
                {
                    _logger.Value.ErrorFormat("Expected message to begin with <HEADER, but was {0}", redisMessage);
                    return(message);
                }

                var messageHeader = JsonConvert.DeserializeObject <MessageHeader>(reader.ReadLine());

                header = reader.ReadLine();
                if (header.TrimStart() != "HEADER/>")
                {
                    _logger.Value.ErrorFormat("Expected message to find end of HEADER/>, but was {0}", redisMessage);
                    return(message);
                }

                var body = reader.ReadLine();
                if (body.TrimEnd() != "<BODY")
                {
                    _logger.Value.ErrorFormat("Expected message to have beginning of <BODY, but was {0}", redisMessage);
                    return(message);
                }

                var messageBody = new MessageBody(reader.ReadLine());

                body = reader.ReadLine();
                if (body.TrimStart() != "BODY/>")
                {
                    _logger.Value.ErrorFormat("Expected message to find end of BODY/>, but was {0}", redisMessage);
                    return(message);
                }

                message = new Message(messageHeader, messageBody);
            }

            return(message);
        }
コード例 #31
0
        internal override void Lock(MessageBody messageBody)
        {
            if (_logger.IsDebugEnabled)
            {
                _logger.DebugFormat("Locking {0}.", this);
            }

            // take a new lock ---update timestamp while staying in released state--- so that this agent instance get
            // exclusive ownership of the data file should there be another remote agent instance working concurrently
            var releasedDataFile = new ReleasedDataFile(this);
            var result           = DataFileServant.Instance.TryMoveFile(Path, releasedDataFile.Path);

            messageBody.DataFile = result
                                ? (DataFile)releasedDataFile
                                : new AwaitingRetryDataFile(this);
        }
コード例 #32
0
        private static Message MapFunction(IDataReader dr)
        {
            if (dr.Read())
            {
                var id          = dr.GetGuid(dr.GetOrdinal("MessageId"));
                var messageType = (MessageType)Enum.Parse(typeof(MessageType), dr.GetString(dr.GetOrdinal("MessageType")));
                var topic       = dr.GetString(dr.GetOrdinal("Topic"));

                var header = new MessageHeader(id, topic, messageType);
                var body   = new MessageBody(dr.GetString(dr.GetOrdinal("Body")));

                return(new Message(header, body));
            }

            return(new Message());
        }
コード例 #33
0
        public async Task ReadAsyncFromNoContentLengthReturnsZero(HttpVersion httpVersion)
        {
            using (var input = new TestInput())
            {
                var body   = MessageBody.For(httpVersion, new FrameRequestHeaders(), input.Frame);
                var stream = new FrameRequestStream(Mock.Of <IHttpBodyControlFeature>());
                stream.StartAcceptingReads(body);

                input.Add("Hello");

                var buffer = new byte[1024];
                Assert.Equal(0, await stream.ReadAsync(buffer, 0, buffer.Length));

                await body.StopAsync();
            }
        }
        internal override void Lock(MessageBody messageBody)
        {
            if (_logger.IsDebugEnabled)
            {
                _logger.Debug($"Locking {this}.");
            }

            // try to add a .timestamp.locked extension to file name to get exclusive ownership should there be another
            // Claim Store Agent working concurrently from another computer
            var lockedDataFile = new LockedDataFile(this);
            var result         = DataFileServant.Instance.TryMoveFile(Path, lockedDataFile.Path);

            messageBody.DataFile = result
                                ? lockedDataFile
                                : new AwaitingRetryDataFile(this);
        }
コード例 #35
0
        private Message ParseMessage(string json)
        {
            JObject     o           = JObject.Parse(json);
            MessageType messageType = (MessageType)(int)o["type"];
            MessageBody messageBody = null;

            switch (messageType)
            {
            case MessageType.Inventory:
            {
                messageBody = o["body"].ToObject <Inventory>();
                break;
            }
            }
            return(new Message(messageType, messageBody));
        }
コード例 #36
0
 public MessageHeaderDecoder(IContentDecoder<IList<HeaderInfo>> decoder, MessageBody message)
 {
     RawHeader = Encoding.UTF8.GetString(message.HeaderRaw);
     var decodedResult = decoder.Decode(message.HeaderRaw);
     DecodedHeaders = decodedResult.IsParsed ? decodedResult.Value : new HeaderInfo[0];
 }
コード例 #37
0
ファイル: Publish.cs プロジェクト: jennings/Turbocharged.NSQ
 public Publish(Topic topic, MessageBody message)
 {
     _message = message;
     _topic = topic;
 }
コード例 #38
0
ファイル: Program.cs プロジェクト: kixtarte/cadencii
        static void Main( string[] args ) {
            print( "Content-type: text/html\n" );
            Console.OutputEncoding = Encoding.GetEncoding( _TEXT_ENC );
            string app_name = "webpoedit";
            string executing_file = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            app_name = Path.GetFileNameWithoutExtension( executing_file ).ToLower();
            string cgi_name = Path.GetFileName( executing_file ).ToLower();
            StreamWriter logger = null;
            print( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" );

            print( "<html>" );
            print( "<head>" );
            print( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + _TEXT_ENC + "\">" );
            print( "<meta http-equiv=\"Content-Style-Type\" content=\"text/css\">" );
            try {
                logger = new StreamWriter( "webpoedit.log", true );
                string project_name = "";
                StreamReader sr = null;
                if ( !File.Exists( config ) ) {
                    print( "<head><title>" + app_name + ": Error</title></head>" );
                    print( "<body>" );
                    print( "<b>configuration file not found</b>" );
                    print( "</body>" );
                    print( "</html>" );
                    return;
                }
                try {
                    sr = new StreamReader( config );
                    project_name = sr.ReadLine();
                } catch ( Exception ex ) {
                    print( "<head><title>" + app_name + ": Error<title></head>" );
                    print( "<body>" );
                    print( "<b>configuration file I/O error</b>" );
                    print( "</body>" );
                    print( "</html>" );
                    return;
                }
                print( "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + project_name + "/style.css\">" );

                TextReader tr = Console.In;
                string stdin = "";
                string line = "";
                while ( (line = tr.ReadLine()) != null ) {
                    stdin += line;
                }
                string get_res = Environment.GetEnvironmentVariable( "QUERY_STRING" );
                string command0 = "";
                string author = "";
                List<KeyValuePair<string, string>> commands = new List<KeyValuePair<string, string>>();
                if ( get_res != "" ) {
                    string[] spl = get_res.Split( '&' );
                    for ( int i = 0; i < spl.Length; i++ ) {
                        string s = spl[i];
                        string[] spl2 = s.Split( "=".ToCharArray(), 2 );
                        commands.Add( new KeyValuePair<string, string>( spl2[0], spl2[1] ) );
                        if ( spl2[0] == "author" ) {
                            author = spl2[1];
                        } else {
                            if ( command0 == "" ) {
                                command0 = spl2[0];
                            }
                        }
                    }
                }
                if ( stdin != "" ) {
                    string[] spl = stdin.Split( '&' );
                    foreach ( string s in spl ) {
                        string[] spl2 = s.Split( "=".ToCharArray(), 2 );
                        commands.Add( new KeyValuePair<string, string>( spl2[0], spl2[1] ) );
                        if ( spl2[0] == "author" ) {
                            author = spl2[1];
                        }
                        if ( spl2[0] == "rauthor" ) {
                            author = enc_b64( dec_url( spl2[1] ) );
                        }
                    }
                }
                Messaging.loadMessages( project_name );
#if DEBUG
                if ( commands.Count > 0 ) print( "commands[0].Key=" + commands[0].Key + "; commands[0].Value=" + commands[0].Value );
#endif
                if ( author == "" ) {
                    print( "<title>" + project_name + " localization</title>" );
                    print( "</head>" );
                    print( "<body>" );
                    print( "<div class=\"top\"><br>&nbsp;&nbsp;<a href=\"" + cgi_name + "\">" + project_name + "</a></div>" );
                    print( "enter your nickname<br>" );
                    print( "<form method=\"post\" action=\"" + cgi_name + "?start=0\">" );
                    print( "<input type=\"text\" name=\"rauthor\" size=30 value=\"\">" );
                    print( "<input type=\"submit\" value=\"start\"></form>" );
                    print( "</body>" );
                    print( "</html>" );
                } else if ( command0 == "start" ) {
                    logger.WriteLine( DateTime.Now + " start; author=" + dec_b64( author ) );
                    // 現在編集可能な言語ファイルのリストを表示
                    print( "<title>" + project_name + " localization</title>" );
                    print( "</head>" );
                    print( "<body>" );
                    print( "<div class=\"top\"><br>&nbsp;&nbsp;<a href=\"" + cgi_name + "?start=0&author=" + author + "\">" + project_name + "</a></div>" );
                    print( "<h4>List of language configuration</h4>" );
                    print( "  <table class=\"padleft\" border=0 cellspacing=0 width=\"100%\">" );
                    print( "    <tr>" );
                    print( "      <td class=\"header\">Language</td>" );
                    print( "      <td class=\"header\">Progress</td>" );
                    print( "      <td class=\"header\">Download language config</td>" );
                    print( "    </tr>" );
                    List<string> languages = new List<string>( Messaging.getRegisteredLanguage() );
                    int count = -1;
                    MessageBody mben = new MessageBody( "en", Path.Combine( project_name, "en.po" ) );
                    foreach ( string lang in languages ) {
                        if ( lang == "en" ) {
                            continue;
                        }
                        count++;
                        string class_kind = "\"even\"";
                        if ( count % 2 != 0 ) {
                            class_kind = "\"odd\"";
                        }
                        print( "    <tr>" );
                        string desc = "";
                        for ( int i = 0; i < _LANGS.GetUpperBound( 0 ) + 1; i++ ) {
                            if ( _LANGS[i, 1] == lang ) {
                                desc = _LANGS[i, 0];
                                break;
                            }
                        }

                        // 進捗率を計算。
                        MessageBody mb = new MessageBody( lang, Path.Combine( project_name, lang + ".po" ) );
                        int en_count = mben.list.Count;
                        int lang_count = 0;
                        foreach ( string id in mben.list.Keys ) {
                            if ( mb.list.ContainsKey( id ) ) {
                                if ( mb.list[id].message != id ) {
                                    lang_count++;
                                }
                            }
                        }
                        float prog = (float)lang_count / (float)en_count * 100.0f;
                        print( "      <td class=" + class_kind + ">" + desc + "&nbsp;[" + lang + "]&nbsp;&nbsp;<a href=\"" + cgi_name + "?target=" + lang + "&author=" + author + "\">edit</a></td>" );
                        print( "      <td class=" + class_kind + ">" + prog.ToString( "0.00" ) + "% translated</td>" );
                        print( "      <td class=" + class_kind + "><a href=\"" + project_name + "/" + lang + ".po\">Download</a></td>" );
                        print( "    </tr>" );
                    }
                    print( "  </table>" );
                    print( "  <br>" );
                    print( "<h4>If you want to create new language configuration, select language and press \"create\" button.</h4>" );
                    print( "  <div class=\"padleft\">" );
                    print( "  <form method=\"post\" action=\"" + cgi_name + "?create=0&author=" + author + "\">" );

                    // ブラウザの使用言語を取得
                    string http_accept_language = Environment.GetEnvironmentVariable( "HTTP_ACCEPT_LANGUAGE" );
                    string[] spl = http_accept_language.Split( ',' );
                    Dictionary<string, float> accept_language_list = new Dictionary<string, float>();
                    foreach ( string s in spl ) {
                        // ja,fr;q=0.7,de;q=0.3
                        if ( s.Contains( ";" ) ) {
                            string[] spl2 = s.Split( ';' ); //spl2 = { "fr", "q=0.7" }
                            if ( spl2.Length >= 2 ) {
                                string[] spl3 = spl2[1].Split( '=' ); //spl3 = { "q", "0.7" }
                                if ( spl3.Length >= 2 ) {
                                    float q = 0.0f;
                                    if ( float.TryParse( spl3[1], out q ) ) {
                                        accept_language_list.Add( spl2[0], q );
                                    }
                                }
                            }
                        } else {
                            accept_language_list.Add( s, 1.0f );
                        }
                    }
                    // 最も品質値の高い言語はどれか
                    string most_used = "en";
                    float most_used_q = 0.0f;
                    foreach ( string key in accept_language_list.Keys ) {
                        if ( most_used_q < accept_language_list[key] ) {
                            most_used = key;
                            most_used_q = accept_language_list[key];
                        }
                    }

                    // 未作成の言語設定ファイルを列挙
                    print( "  <select name=\"lang\">" );
                    int len = _LANGS.GetUpperBound( 0 ) + 1;
                    for ( int i = 0; i < len; i++ ) {
                        if ( languages.Contains( _LANGS[i, 1] ) ) {
                            print( "    <option value=\"" + _LANGS[i, 1] + "\" disabled>" + _LANGS[i, 0] );
                        } else if ( most_used == _LANGS[i, 1] ) {
                            print( "    <option value=\"" + _LANGS[i, 1] + "\" selected>" + _LANGS[i, 0] );
                        } else {
                            print( "    <option value=\"" + _LANGS[i, 1] + "\">" + _LANGS[i, 0] );
                        }
                    }
                    print( "  <input type=\"submit\" value=\"create\">" );
                    print( "  </form>" );
                    print( "  </div>" );
                    print( "</body>" );
                    print( "</html>" );
                } else if ( command0 == "target" || command0 == "update" || command0 == "create" ) {
                    // 指定された言語の現在の状態を表示。
                    string lang = commands[0].Value;

                    List<string> keys = new List<string>( Messaging.getKeys( "en" ) );
                    keys.Sort();

                    if ( command0 == "create" ) {
                        foreach ( KeyValuePair<string, string> v in commands ) {
                            if ( v.Key == "lang" ) {
                                lang = v.Value;
                                break;
                            }
                        }
                        string newpo = Path.Combine( project_name, lang + ".po" );
                        MessageBody mb0 = null;
                        if ( File.Exists( newpo ) ) {
                            // すでに存在するlangでcreateが指定された場合
                            mb0 = new MessageBody( lang, newpo );
                        } else {
                            mb0 = new MessageBody( lang );
                        }
                        Messaging.setLanguage( "en" );
                        foreach ( string id in keys ) {
                            if ( !mb0.list.ContainsKey( id ) ) {
                                MessageBodyEntry item = Messaging.getMessageDetail( id );
                                MessageBodyEntry add = new MessageBodyEntry( item.message, item.location.ToArray() );
                                mb0.list.Add( id, add );
                            }
                        }

                        // google language apiを使って訳せるところは訳す。en -> [lang]の結果が元のenと異なり、かつ、en -> [lang] -> enが元のenと同じなら翻訳できたとみなす
                        //url: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cit
                        //{"responseData": {"translatedText":"ciao mondo"}, "responseDetails": null, "responseStatus": 200}
                        foreach ( string en_query in keys ) {
                            if ( en_query == mb0.getMessage( en_query ) ) {
                                string lang_query = translate( en_query, "en", lang );
                                string en_revert = translate( lang_query, lang, "en" );
                                if ( en_query.ToLower() == en_revert.ToLower() ) {
                                    mb0.list[en_query].message = lang_query;
                                    logger.WriteLine( "    translated: {id,value}={" + en_query + "," + lang_query + "}" );
                                }
                            }
                        }

                        mb0.write( newpo );
                    }

                    bool is_rtl = Util.isRightToLeftLanguage( lang );
                    logger.WriteLine( DateTime.Now + " " + command0 + "; lang=" + lang + "; author=" + dec_b64( author ) );

                    print( "<title>" + project_name + "&nbsp;&gt;&gt;&nbsp;" + lang + "</title>" );
                    print( "</head>" );
                    if ( is_rtl ) {
                        print( "<body dir=\"rtl\">" );
                    } else {
                        print( "<body>" );
                    }
                    print( "<form method=\"post\" action=\"" + cgi_name + "?update=" + lang + "&author=" + author + "\">" );
                    print( "<div class=\"top\"><br>&nbsp;&nbsp;<a href=\"" + cgi_name + "?start=0&author=" + author + "\">" + project_name + "</a>&gt;&gt;" + lang + "</div>" );
                    print( "<div align=\"center\">" );
                    print( "<table border=0 cellspacing=0 width=\"100%\">" );
                    print( "  <tr>" );
                    print( "    <td class=\"header\">English</td>" );
                    print( "    <td class=\"header\">translation</td>" );
                    print( "  </tr>" );
                    Messaging.setLanguage( lang );
                    MessageBody mb = new MessageBody( lang, Path.Combine( project_name, lang + ".po" ) );
                    if ( command0 == "update" ) {
                        string[] spl = stdin.Split( '&' );
                        foreach ( string s in spl ) {
                            string[] spl2 = s.Split( '=' );
                            if ( spl2.Length >= 2 ) {
                                string id = dec_b64( spl2[0] );
                                string value = dec_url( spl2[1] ).Replace( "\\n", "\n" );
                                if ( mb.list.ContainsKey( id ) ) {
                                    if ( keys.Contains( id ) ) {
                                        string old = mb.list[id].message;
                                        mb.list[id].message = value;
                                        if ( old != value ) {
                                            logger.WriteLine( "    replaced: {id,value,old_value}={" + id + "," + value + "," + old + "}" );
                                        }
                                    } else {
                                        mb.list.Remove( id );
                                    }
                                } else if ( keys.Contains( id ) ) {
                                    mb.list.Add( id, new MessageBodyEntry( value, new string[]{} ) );
                                    logger.WriteLine( "    added: {id,value}={" + id + "," + value + "}" );
                                }
                            }
                        }
                        mb.write( Path.Combine( project_name, lang + ".po" ) );
                    }
                    int count = -1;
                    foreach ( string key in keys ) {
                        count++;
                        string class_kind = "\"even\"";
                        if ( count % 2 != 0 ) {
                            class_kind = "\"odd\"";
                        }
                        string id = enc_b64( key );
                        print( "  <tr>" );
                        print( "    <td class=" + class_kind + ">" + key.Replace( "\n", "\\" + "n" ) + "</td>" );
                        string msg = mb.getMessage( key );
                        print( "    <td nowrap class=" + class_kind + ">" );
                        if ( msg == key ) {
                            print( "      <input type=\"text\" name=\"" + id + "\" class=\"highlight\" size=60 value=\"" + msg.Replace( "\n", "\\" + "n" ) + "\">" );
                        } else {
                            print( "      <input type=\"text\" name=\"" + id + "\" size=60 value=\"" + msg.Replace( "\n", "\\" + "n" ) + "\">" );
                        }
                        print( "      <input type=\"submit\" value=\"submit\">" );
                        print( "    </td>" );
                        print( "  </tr>" );
                    }
                    print( "</table>" );
                    print( "</div>" );
                    print( "</form>" );
                    print( "</body>" );
                    print( "</html>" );
                }
            } catch ( Exception exm ) {
                logger.WriteLine( DateTime.Now + " error; exm=" + exm );
                print( "<head><title>" + app_name + ": Error</title></head>" );
                print( "<body>" );
                print( "</body>" );
                print( "</html>" );
            } finally {
                if ( logger != null ) {
                    logger.Close();
                }
            }
        }