public async Task <PostMessageResponse> PostMessage(PostMessage message)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var serializedPayload = JsonConvert.SerializeObject(message);

            using var postContent = new StringContent(serializedPayload, Encoding.UTF8, ContentType);
            _logger.LogTrace("Json: {rawJsonContent}", serializedPayload);

            using var response = await _client.PostAsync("chat.postMessage", postContent).ConfigureAwait(false);

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var parsed = JsonConvert.DeserializeObject <PostMessageResponse>(content);

            if (response.StatusCode != System.Net.HttpStatusCode.OK || !parsed.Ok)
            {
                _logger.LogError("Status code: {statusCode}. Error message: {error}", response.StatusCode, parsed?.Error);
                _logger.LogError("Content: {content}", content);
                throw new SlackLibException($"Something went wrong while posting alert. Code was {response.StatusCode}, message: {parsed?.Error}");
            }
            return(parsed);
        }
Example #2
0
        public void Send(PostMessage message)
        {
            lock (this) {
                SmtpConfig conf = null;
                if (!Registry.ContainsKey(message.From))
                {
                    if (message.CanUseDefault && Registry.ContainsKey("default"))
                    {
                        conf = Registry["default"];
                    }
                    else
                    {
                        throw new Exception(message.From + " not configured");
                    }
                }
                else
                {
                    conf = Registry[message.From];
                }

                var mail = BuildMessage(message, conf);
                var prev = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager
                .ServerCertificateValidationCallback =
                    (sender, cert, chain, sslPolicyErrors) => true;

                conf.SmtpClient.Send(mail);
                ServicePointManager
                .ServerCertificateValidationCallback = prev;
            }
        }
        public PostMessage PushMessage(PostMessage message)
        {
            if (!Enabled)
            {
                throw new Exception("not available");
            }


            if (message.CreateTime.Year <= 1900)
            {
                message.CreateTime = DateTime.Now.ToUniversalTime();
            }
            if (message.StartTime.ToUniversalTime() < DateTime.Now.ToUniversalTime())
            {
                message.StartTime = DateTime.Now.ToUniversalTime();
            }
            if (message.SentTime.Year <= 1900)
            {
                message.SentTime = DateTime.MinValue.ToUniversalTime();
            }
            if (string.IsNullOrWhiteSpace(message.Id))
            {
                var json = message.stringify() + Guid.NewGuid();
                message.Id = "M" + json.GetMd5();
            }
            Store(message);
            return(message);
        }
Example #4
0
        public void CanDetectNotSent()
        {
            if (ignoreelastic)
            {
                Assert.Ignore("no elastic search");
            }
            var mq = _container.Get <IMessageQueue>();

            for (var i = 0; i < 10; i++)
            {
                var message = new PostMessage
                {
                    Id        = "M" + i,
                    Addresses = new[] { "*****@*****.**" },
                    From      = "support",
                    Body      = "<h1>Привет</h1>"
                };
                if (i > 4)
                {
                    message.StartTime = DateTime.Now.AddDays(1).ToUniversalTime();
                }
                if (i == 2)
                {
                    message.WasSent  = true;
                    message.SentTime = DateTime.Now.ToUniversalTime();
                }
                mq.PushMessage(message);
            }
            var needsend = mq.GetRequireSendMessages().ToArray();

            Assert.AreEqual(4, needsend.Length);
            Assert.AreEqual("M0,M1,M3,M4", string.Join(",", needsend.Select(_ => _.Id).OrderBy(_ => _)));
        }
Example #5
0
        public void ChangeTile(PostMessage forImage, int cnt, bool setcount)
        {
            int count;

            if (setcount)
            {
                count = cnt;
            }
            else
            {
                count = counter + cnt;
            }

            if (count > 99)
            {
                count = 99;              // Система больше не позволяет
            }
            var apptile     = ShellTile.ActiveTiles.First();
            var appTileData = new StandardTileData();

            //    appTileData.Title = "";
            appTileData.Count               = count;
            appTileData.BackTitle           = forImage.pubDate;
            appTileData.BackContent         = "";
            appTileData.BackBackgroundImage = new Uri(forImage.mainImage, UriKind.RelativeOrAbsolute);
            apptile.Update(appTileData);
            counter  = count;
            lastRead = Convert.ToDateTime(forImage.pubDate);
        }
Example #6
0
        public async Task AddAsync(PostMessage entity)
        {
            await DbContextManager.BeginTransactionAsync();

            var spParameters = new SqlParameter[2];

            spParameters[0] = new SqlParameter()
            {
                ParameterName = "userid", Value = entity.UserId
            };
            spParameters[1] = new SqlParameter()
            {
                ParameterName = "post", Value = entity.Message
            };

            await DbContextManager.StoreProc <StoreProcResult>("[dbo].spInsertPostMessages", spParameters);

            try
            {
                await DbContextManager.CommitAsync();
            }
            catch (Exception)
            {
                DbContextManager.RollbackTransaction();
            }
        }
Example #7
0
        public ActionResult Message(int id, PostMessageForm message)
        {
            PostMessage action = new PostMessage(_db, id, Requester(), message);

            action.Execute();
            return(RedirectToAction("Messages", new { id }));
        }
Example #8
0
      // GET: PostMessages/EditPostMessage/5
      public ActionResult EditPostMessage(int?id)
      {
          if (id == null)
          {
              return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
          }
          PostMessage postMessage = db.PostMessages.Find(id);

          if (postMessage == null)
          {
              return(HttpNotFound());
          }
          PostMessageViewModel postMessageViewModel = new PostMessageViewModel();

          postMessageViewModel.post_message_id = postMessage.Post_Message_Id;
          postMessageViewModel.post_message    = postMessage.Post_Message;
          int  message_id = postMessage.Post_Message_Id;
          int  post_id    = db.PostMessages.Where(p => p.Post_Message_Id == message_id).Select(p => p.Post.Post_Id).FirstOrDefault();
          Post post       = db.Posts.Find(post_id);

          //post.Post_Title = postMessageViewModel.post_title;
          postMessageViewModel.post_title = post.Post_Title;


          return(View(postMessageViewModel));
      }
Example #9
0
        public ActionResult CreatePost([Bind(Include = "post_title,post_message")] PostViewModel postViewModel, HttpPostedFileBase postedFile)
        {
            var   myUniqueFileName = string.Format(@"{0}", Guid.NewGuid());
            Image image            = new Image();


            if (ModelState.IsValid)
            {
                Post        post        = new Post();
                PostMessage postMessage = new PostMessage();
                post.Post_Title = postViewModel.post_title;
                db.Posts.Add(post);
                db.SaveChanges();
                postMessage.ApplicationUser = db.Users.Find(User.Identity.GetUserId());
                postMessage.Post_Message    = postViewModel.post_message;
                postMessage.Post            = post;
                if (postedFile != null)
                {
                    image.Image_Path = myUniqueFileName;
                    string serverPath    = Server.MapPath("~/Uploads/");
                    string fileExtension = Path.GetExtension(postedFile.FileName);
                    string filePath      = image.Image_Path + fileExtension;
                    image.Image_Path = filePath;
                    postedFile.SaveAs(serverPath + image.Image_Path);
                    db.Images.Add(image);
                    db.SaveChanges();
                    postMessage.Image = image;
                }
                db.PostMessages.Add(postMessage);
                db.SaveChanges();
                return(RedirectToAction("PostsList"));
            }

            return(View(postViewModel));
        }
Example #10
0
     public void Send(PostMessage message) {
         lock (this) {
             SmtpConfig conf = null;
             if (!Registry.ContainsKey(message.From)) {
                 if (message.CanUseDefault && Registry.ContainsKey("default")) {
                     conf = Registry["default"];
                 }
                 else {
                     throw new Exception(message.From + " not configured");
                 }
             }
             else {
                 conf = Registry[message.From];
             }   
             
             var mail = BuildMessage(message, conf);
             var prev = ServicePointManager.ServerCertificateValidationCallback;
             ServicePointManager
 .ServerCertificateValidationCallback =
 (sender, cert, chain, sslPolicyErrors) => true;
             
             conf.SmtpClient.Send(mail);
             ServicePointManager
                 .ServerCertificateValidationCallback = prev;
         }
     }
Example #11
0
    /// <summary>
    /// This method is called when user has entered their message and hits the send button.
    /// It calls the <see cref="NetworkManager.PostRequest(string, string)"> coroutine to send
    /// the user message to the bot and also updates the UI with user message.
    /// </summary>
    public void SendMessageToRasa()
    {
        // get user messasge from input field, create a json object
        // from user message and then clear input field
        string message = botUI.inputField.text;

        botUI.inputField.text = "";

        // if user message is not empty, send message to bot
        if (message != "")
        {
            // create json from message
            PostMessage postMessage = new PostMessage {
                sender  = "user",
                message = message
            };
            string jsonBody = JsonUtility.ToJson(postMessage);

            // update UI object with user message
            botUI.UpdateDisplay("user", message, "text");

            // Create a post request with the data to send to Rasa server
            StartCoroutine(PostRequest(rasa_webhook_url, jsonBody));
        }
    }
        /// <summary>
        /// 添加信息记录数据校验
        /// </summary>
        /// yaoy    16.09.26
        /// <param name="postmessage"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddInfomationData(PostMessage postmessage, ref string message)
        {
            var result = true;

            MessageInfo messageInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <MessageInfo>(postmessage.Value);

            InfoTypeInfo        infoType            = new DataRule().GetDataRuleByInfoTypeId(postmessage.InfoTypeId);
            MessageFileTypeInfo messageFileTypeInfo = new DataRule().GetMessageFileTypeInfoById(postmessage.messageTypeID);

            // 数据合法性校验
            result &= new DataAndRuleComPare().Compare(infoType, postmessage.recordID, postmessage.ReportId, messageInfo, postmessage, ref message);

            // 数据规则校验
            // 企业通用规则校验
            if (messageFileTypeInfo.FileType == 1)
            {
                result &= new Validates.ComInformationValidate(infoType.InfoTypeId, messageInfo).BaseValidateMethod();
            }
            // 个人通用规则校验
            else
            {
                result &= new Validates.PerInformationValidate(infoType.InfoTypeId, messageInfo).BaseValidateMethod();
            }

            return(result);
        }
Example #13
0
 public async Task SendMessage(string Message)
 {
     PostMessage postMessage = new PostMessage {
         Channel = Channel, ClientName = Client, Message = Message
     };
     string message = JsonConvert.SerializeObject(postMessage);
     await CommonClient.PostAsync(new Uri($"{Url}chat/{CommonClient.Escape(Client)}/{CommonClient.Escape(Channel)}/send"), message, HttpClient);
 }
Example #14
0
 private Task SendMessageOverRtmAsync(PostMessage message)
 {
     return(this.websocket.SendAsync(
                new ArraySegment <byte>(Encoding.UTF8.GetBytes(message.Text)),
                WebSocketMessageType.Text,
                true,
                this.tokenSource.Token));
 }
Example #15
0
        /// <summary>
        /// Handle a SAY or COMMENT in a forum topic. The current topic must be set before this
        /// function is called or it does nothing. The replyNumber specifies whether this is a new
        /// thread (a SAY) or a reply to an existing thread (a COMMENT). A value of 0 starts a new
        /// thread otherwise it is the number of the message to which this is a reply.
        /// </summary>
        /// <param name="buffer">The I/O buffer</param>
        /// <param name="replyNumber">The message to which this is a reply</param>
        private void SayOrCommentCommand(LineBuffer buffer, int replyNumber)
        {
            if (_currentTopic != null)
            {
                PostMessage message = new PostMessage
                {
                    MsgID = replyNumber,
                    Forum = _currentTopic.Forum.Name,
                    Topic = _currentTopic.Name
                };

                buffer.WriteLine("Enter message. End with '.<CR>'");

                // The body of the message comprises multiple lines terminated by a line
                // that contains a single period character and nothing else.
                StringBuilder bodyMessage = new StringBuilder();

                string bodyLine = buffer.ReadLine();
                while (bodyLine != ".")
                {
                    bodyMessage.AppendLine(bodyLine.Trim());
                    bodyLine = buffer.ReadLine();
                }
                message.Body = bodyMessage.ToString();

                WebRequest wrPosturl = APIRequest.Post("forums/post", APIRequest.APIFormat.XML, message);

                buffer.WriteString("Adding..");

                try
                {
                    Stream objStream = wrPosturl.GetResponse().GetResponseStream();
                    if (objStream != null)
                    {
                        using (TextReader reader = new StreamReader(objStream))
                        {
                            XmlDocument doc = new XmlDocument {
                                InnerXml = reader.ReadLine()
                            };

                            if (doc.DocumentElement != null)
                            {
                                int newMessageNumber = Int32.Parse(doc.DocumentElement.InnerText);
                                buffer.WriteLine(string.Format("Message {0} added.", newMessageNumber));
                            }
                        }
                    }
                }
                catch (WebException e)
                {
                    if (e.Message.Contains("401"))
                    {
                        throw new AuthenticationException("Authentication Failed", e);
                    }
                }
            }
        }
Example #16
0
        public ActionResult ApprovePostMessageConfirmed(int id)
        {
            PostMessage postMessage = db.PostMessages.Find(id);

            postMessage.Message_Status  = false;
            db.Entry(postMessage).State = EntityState.Modified;
            db.SaveChanges();
            return(RedirectToAction("PostDetails", new { id = postMessage.Post.Post_Id }));
        }
Example #17
0
      public ActionResult DeletePostMessageConfirmed(int id)
      {
          PostMessage postMessage = db.PostMessages.Find(id);
          int         post_id     = postMessage.Post.Post_Id;

          db.PostMessages.Remove(postMessage);
          db.SaveChanges();
          return(RedirectToAction("MemberPostDetails", new { id = post_id }));
      }
Example #18
0
 public async Task PostMessage(PostMessage message)
 {
     await Clients.Group(message.Group).SendAsync("message", new
     {
         Message = message.Message,
         Group   = message.Group,
         Nick    = ClientNick
     });
 }
Example #19
0
        public void MessageIsEncoded(char unenc, string enc)
        {
            var message = new PostMessage("channel", $"test {unenc} test");

            var result = message
                         .ToKeyValuePairs()
                         .First(m => m.Key == "text");

            Assert.Equal($"test {enc} test", result.Value);
        }
        protected void PostMessageButton_Click(object sender, EventArgs e)
        {
            if (PostMessage == null)
            {
                return;
            }

            var args = PostMessage.CreateArgs(PostMessageTextBox.Text);

            PostMessage(this, args);
        }
    public void SendMessageToRasa()
    {
        PostMessage postMessage = new PostMessage
        {
            sender  = sender,                             //NOMBRE
            message = message
        };
        string jsonBody = JsonUtility.ToJson(postMessage);

        StartCoroutine(PostRequest(rasa_url, jsonBody));
    }
Example #22
0
        public async Task <IActionResult> AddMessage([FromBody] PostMessage model)
        {
            await dbMessages.InsertMessage(new Message
            {
                FromId         = new ObjectId(model.FromId),
                ConversationId = new ObjectId(model.ConversationId),
                DateSent       = DateTime.UtcNow,
                Content        = model.Content
            });

            return(NoContent());
        }
        private void Store(PostMessage message)
        {
            var result = EsClient.ExecuteCommand(BaseUrl() + "/" + message.Id + "?refresh=true", message.stringify());

            if (null == result)
            {
                Logg.Error(new {
                    error_in_es = EsClient.LastError.Message,
                    urls        = EsClient.Urls.ToArray()
                }.stringify());
                throw  EsClient.LastError;
            }
        }
Example #24
0
        public async Task PostSendMessage(HttpContext context)
        {
            var inputDoc = await context.ReadStringAsync();

            PostMessage postMessage = JsonConvert.DeserializeObject <PostMessage>(inputDoc);
            var         client      = postMessage.ClientName;
            var         channel     = postMessage.Channel;
            var         message     = postMessage.Message;

            await chatFacade.SendMessage(client, channel, message);

            await context.RespondStringAsync(inputDoc);
        }
Example #25
0
        public void CanSendMail()
        {
            var smtpsender = new SmtpMessageSender();
            var conf       = new BxlParser().Parse(File.ReadAllText(EnvironmentInfo.ResolvePath("@repos@/zrepos/mail.bxls")), options: BxlParserOptions.ExtractSingle);

            smtpsender.InitializeFromXml(conf);
            var message = new PostMessage();

            message.From      = "ivan";
            message.Addresses = new[] { "*****@*****.**" };
            message.Body      = "<h1>Привет!</h1>";
            smtpsender.Send(message);
        }
Example #26
0
        private void SendImageCommandHandler(object obj)
        {
            string fileName = ShowDialogAndFetchFileName();

            PostMessage message = new PostMessage()
            {
                FromUserId  = LoginUser.UserId,
                ToUserId    = ActiveTabUser.InboxUserId,
                MessageType = MessageType.FacebookMessengerImage,
                ImagePath   = fileName
            };

            _dbHelper.Add(message);
        }
Example #27
0
        /// <summary>
        /// Post this message to the server
        /// </summary>
        private void PostMessage()
        {
            CIX.FolderCollection.NotifyMessagePostStarted(this);
            PostPending = false;
            try
            {
                Folder      folder      = Topic;
                PostMessage postMessage = new PostMessage
                {
                    Body       = Body.FixQuotes(),
                    Forum      = folder.ParentFolder.Name,
                    Topic      = folder.Name,
                    WrapColumn = "0",
                    MarkRead   = "1",
                    MsgID      = CommentID.ToString(CultureInfo.InvariantCulture)
                };

                HttpWebRequest postUrl        = APIRequest.Post("forums/post", APIRequest.APIFormat.XML, postMessage);
                string         responseString = APIRequest.ReadResponseString(postUrl);

                int newRemoteID;
                if (int.TryParse(responseString, out newRemoteID))
                {
                    RemoteID = newRemoteID;
                    Date     = DateTime.UtcNow.UTCToGMTBST();
                    lock (CIX.DBLock)
                    {
                        CIX.DB.Update(this);
                    }
                    if (CommentID == 0)
                    {
                        LogFile.WriteLine("Posted new thread \"{0}\" as message {1}", Body.FirstLine(), RemoteID);
                    }
                    else
                    {
                        LogFile.WriteLine("Posted new reply to message {0} as message {1}", CommentID, RemoteID);
                    }
                    CIX.FolderCollection.NotifyMessageChanged(this);
                }
                else
                {
                    LogFile.WriteLine("Failed to post message {0} : {1}", ID, responseString);
                }
            }
            catch (Exception e)
            {
                CIX.ReportServerExceptions("CIXMessage.PostMessage", e);
            }
            CIX.FolderCollection.NotifyMessagePostCompleted(this);
        }
Example #28
0
      // GET: Posts/DeletePostMessage/5
      public ActionResult DeletePostMessage(int?id)
      {
          if (id == null)
          {
              return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
          }
          PostMessage postMessage = db.PostMessages.Find(id);

          if (postMessage == null)
          {
              return(HttpNotFound());
          }
          return(View(postMessage));
      }
        public IActionResult OnGet(int?id)
        {
            PostMessage = new PostMessage();


            if (PostMessage == null)
            {
                return(RedirectToPage("./PageNotFound"));
            }
            else
            {
                return(Page());
            }
        }
Example #30
0
        /// <summary>
        /// Attempts to target a Unit.
        /// Does not work very well currently.
        /// TODO: Facade this when Settings are implmented
        /// </summary>
        /// <param name="u"></param>
        private void targetUnit(Unit u)
        {
            // Tab targeting method

            /*if (target!= null && MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, objBase + PlayerOffsets.CUR_TARGET_GUID_OFFSET) == u.getGUID())
             *  return; // Already targeting
             * else
             * {
             *  while (true)
             *  {
             *      try
             *      {
             *
             *          faceLocation(u.getLocation());
             *          PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "F");
             *          Thread.Sleep(200);
             *          if (MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, objBase + PlayerOffsets.CUR_TARGET_GUID_OFFSET) == u.getGUID())
             *              this.target = u;
             *              return;
             *      }
             *      catch (Exception ex) { }
             *  }
             * } */

            // Memory write method. Requires macro: '' bound to key 'T'.
            if (target != null && MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, objBase + PlayerOffsets.CUR_TARGET_GUID_OFFSET) == u.getGUID())
            {
                return; // Already targeting
            }
            else
            {
                while (true)
                {
                    try
                    {
                        faceLocation(u.getLocation());
                        MemoryWriter.WriteMem(WoW_Instance.getProcess(), 0xB4E2E0, BitConverter.GetBytes(u.getGUID()));
                        Thread.Sleep(100);
                        PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "T");
                        Thread.Sleep(200);
                        if (MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, objBase + PlayerOffsets.CUR_TARGET_GUID_OFFSET) == u.getGUID())
                        {
                            this.target = u;
                        }
                        return;
                    }
                    catch (Exception ex) { }
                }
            }
        }
Example #31
0
        /// <summary>
        /// Attempts to loot the current target.
        /// Seems to be working fairly well but hijacks the mouse.
        /// TODO: Facade this when Settings are implmented
        /// </summary>
        /// <param name="u"></param>
        private void LootUnit(Unit u)
        {
            while (this.getLocation().getDistance(u.getLocation()) > 4.0f)
            {
                moveToLoc(u.getLocation());
                Thread.Sleep(200);
            }

            Boolean foundInteract = false;

            if (MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, 0x00B4E2C8) == u.getGUID())
            {
                foundInteract = true;
                goto End;
            }

            Rectangle r = WoW_Instance.getWindowDimensions();

            for (int i = -50; i < 50; i += 25)
            {
                for (int j = -25; j < 75; j += 25)
                {
                    PostMessage.setCursor((i + (r.X + (r.Width / 2))), (j + (r.Y + (r.Height / 2))));
                    Thread.Sleep(200);
                    if (MemoryReader.readUInt64(WoW_Instance.getProcess().Handle, 0x00B4E2C8) == u.getGUID())
                    {
                        PostMessage.setCursor(((i + 3) + (r.X + (r.Width / 2))), ((j + 6) + (r.Y + (r.Height / 2))));
                        foundInteract = true;
                        goto End;
                    }
                }
            }
End:

            if (foundInteract == true)
            {
                for (int i = 0; i < 3; i++)
                {
                    PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{SHIFTD}");
                    Thread.Sleep(100);
                    PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{SHIFTD}");
                    Thread.Sleep(100);
                    PostMessage.RightClick();
                    Thread.Sleep(200);
                }

                PostMessage.SendKeys((int)WoW_Instance.getProcess().MainWindowHandle, "{SHIFTU}");
            }
        }
Example #32
0
        private static MailMessage BuildMessage(PostMessage message, SmtpConfig conf) {
            var m = new MailMessage {
                From = new MailAddress(conf.From, conf.Name),
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = true,
                Body = message.Body,
                SubjectEncoding = Encoding.UTF8,
                Subject = message.Subject
            };
            m.Body += "<div style='color:gray;font-size:8pt'>messageid:" + message.Id + "</div>";
            if (message.Type != "subscribe") {
                 m.Subject += "; messageid:" + message.Id;
            }
            foreach (var address in message.Addresses) {
                m.Bcc.Add(new MailAddress(address));
            }
            m.Bcc.Add(conf.From);

            return m;
        }
        public PostMessage PushMessage(PostMessage message) {
            if (!Enabled) {
                throw new Exception("not available");
            }


            if (message.CreateTime.Year <= 1900) {
                message.CreateTime = DateTime.Now.ToUniversalTime();
            }
            if (message.StartTime.ToUniversalTime() < DateTime.Now.ToUniversalTime()) {
                message.StartTime = DateTime.Now.ToUniversalTime();
            }
            if (message.SentTime.Year <= 1900) {
                message.SentTime = DateTime.MinValue.ToUniversalTime();
            }
            if (string.IsNullOrWhiteSpace(message.Id)) {
                var json = message.stringify() + Guid.NewGuid();
                message.Id = "M" + json.GetMd5();
            }
            Store(message);
            return message;
        }
 private static PostMessage CreateFromJson(object j) {
     var pm = new PostMessage();
     pm.Id = j.str("_id");
     var _src = j.map("_source");
     pm.Addresses = _src.arr("Addresses").Select(_ => _.ToStr()).ToArray();
     pm.From = _src.str("From");
     pm.CanUseDefault = _src.bul("CanUseDefault");
     pm.CreateTime = _src.date("CreateTime");
     pm.StartTime = _src.date("StartTime");
     pm.Body = _src.str("Body");
     pm.Subject = _src.str("Subject");
     pm.SentTime = _src.date("SentTime");
     pm.WasSent = _src.bul("WasSent");
     pm.Tags = _src.map("Tags");
     pm.Type = _src.str("Type");
     return pm;
 }
 private void Store(PostMessage message) {
     var result = EsClient.ExecuteCommand(BaseUrl() + "/" + message.Id + "?refresh=true", message.stringify());
     if (null == result) {
         Logg.Error(new {
             error_in_es = EsClient.LastError.Message,
             urls = EsClient.Urls.ToArray()
         }.stringify());
         throw  EsClient.LastError;
     }
 }
Example #36
0
 public eGFX_Tools(PostMessage PCM)
 {
     MessagePost += PCM;
 }