Example #1
0
        public async Task CreateAsync_ShouldReturnErrorWhenExceptionInQuery2()
        {
            var newMessageFile = new MessageFile {
                Id = 10, Name = "NewFileName", FileTypeId = 1
            };

            var mockMessageFilesQuery = new Mock <IMessageFileQuery>();

            mockMessageFilesQuery
            .Setup(m => m.Create(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(newMessageFile);

            var mockMessagesQuery = new Mock <IMessagesQuery>();

            mockMessagesQuery.Setup(m => m.Create(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <byte>(), It.IsAny <int?>()))
            .ThrowsAsync(new Exception("Mock exception"));

            var mockFileService = new Mock <IFileService <ChatFilesConfiguration> >();

            var mockContextFactory = SetupContextFactory(mockMessagesQuery.Object, mockMessageFilesQuery.Object, null);

            _sut = new TeacherChatService(mockContextFactory.Object, mockFileService.Object, _mapper);
            var request = new MessageCreateRequest {
                Sender = 1, Recipients = new int[] { 1, 2, 3 }, Text = "NewMessageText"
            };

            // ACT
            var actual = await _sut.CreateAsync(request);

            // ASSERT
            Assert.Equal("Mock exception", actual.Error.Message);
        }
Example #2
0
        public DialogPreview(TabInfo sourceTab)
        {
            InitializeComponent();

            this.Text     += sourceTab.filename;
            this.sourceTab = sourceTab;

            NodesComboBox.Items.AddRange(DialogueParser.GetAllNodesName(scrProc).ToArray());

            Procedure curProc = sourceTab.parseInfo.GetProcedureFromPosition(sourceTab.textEditor.ActiveTextAreaControl.Caret.Line);

            if (curProc == null || !NodesComboBox.Items.Contains(curProc.name))
            {
                int indx = sourceTab.parseInfo.GetProcedureIndex("talk_p_proc");
                if (indx == -1)
                {
                    return;
                }
                curProc = scrProc[indx];
            }

            MessagesData = File.ReadAllLines(sourceTab.msgFilePath, Settings.EncCodePage);
            if (sourceTab.messages.Count == 0)
            {
                MessageFile.ParseMessages(sourceTab, MessagesData);
            }

            NodesComboBox.Text = curProc.name;
            nodesNavigation.Add(curProc.name);
            GotoNode(curProc);
        }
        private void ParseCode()
        {
            nodeParseData.Clear();
            dgvMessages.Rows.Clear();

            //распарсить код
            DialogueParser.ParseNodeCode(textEditor.Text, nodeParseData, PI, splitOption: StringSplitOptions.None);

            foreach (DialogueParser data in nodeParseData)
            {
                bool   error = false;
                string msg = null, path = null;

                if (data.numberMsgLine > 0)
                {
                    if (data.numberMsgFile > 0)
                    {
                        if (MessageFile.GetPath(sourceTab, data.numberMsgFile, out path))
                        {
                            string[] MsgData = File.ReadAllLines(path, Settings.EncCodePage);
                            msg = MessageFile.GetMessages(MsgData, data.numberMsgLine);
                        }
                        else
                        {
                            msg   = String.Format(MessageFile.msgfileError, data.numberMsgFile); //<Not found message file>
                            error = true;
                        }
                    }
                    else if (sourceTab.messages.ContainsKey(data.numberMsgLine))
                    {
                        msg = sourceTab.messages[data.numberMsgLine];
                    }
                    if (msg == null)
                    {
                        msg   = MessageFile.messageError;
                        error = true;
                    }
                }
                else
                {
                    continue;
                }

                string msgFile = (data.numberMsgFile == -1) ? sourceTab.msgFilePath : path; //MessageFile.GetMessageFilePath(data.numberMsgFile, curTab);

                dgvMessages.Rows.Add(data.numberMsgLine, msg, Path.GetFileName(msgFile));
                dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[0].Tag = data;
                dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[2].Tag = msgFile;

                if (error)
                {
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].ReadOnly        = true;
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].Style.ForeColor = Color.Red;
                }
                else if (data.opcode == OpcodeType.Option || data.opcode == OpcodeType.giq_option || data.opcode == OpcodeType.gsay_option)
                {
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].Style.ForeColor = Color.Blue;
                }
            }
        }
Example #4
0
        // call from main script editor
        public static MessageEditor MessageEditorInit(TabInfo tab, Form frm)
        {
            string msgPath = null;

            if (tab != null)
            {
                if (!MessageFile.GetAssociatePath(tab, true, out msgPath))
                {
                    return(null);
                }

                tab.msgFilePath = msgPath;
            }

            // Show form
            MessageEditor msgEdit = new MessageEditor(msgPath, tab);

            msgEdit.scriptForm = frm;
            if (tab != null)
            {
                msgEdit.alwaysOnTopToolStripMenuItem.Checked = true;
            }
            msgEdit.Show();
            //if (Settings.autoOpenMsgs && msgEdit.scrptEditor.msgAutoOpenEditorStripMenuItem.Checked)
            //    msgEdit.WindowState = FormWindowState.Minimized;

            return(msgEdit);
        }
Example #5
0
 public AdminCommandResult(TimeSpan executionTime, string text, Embed embed, MessageFile file, bool isSuccessful)
 {
     ExecutionTime = executionTime;
     Text          = text;
     Embed         = embed;
     File          = file;
     IsSuccessful  = isSuccessful;
 }
Example #6
0
        /// <summary>
        ///     Прикрепление файла.
        /// </summary>
        /// <param name="fileName"> Имя файла. </param>
        /// <param name="data"> Массив байтов файла. </param>
        /// <returns> Сообщение. </returns>
        public EmailMessage AddFile(string fileName, byte[] data)
        {
            var file = new MessageFile(fileName, data);

            Body.Files.Add(file);

            return(this);
        }
Example #7
0
        /// <summary>
        ///     Прикрепление файла.
        /// </summary>
        /// <param name="fileName"> Имя файла. </param>
        /// <param name="stream"> Поток для чтения файла. </param>
        /// <returns> Сообщение. </returns>
        public EmailMessage AddFile(string fileName, Stream stream)
        {
            var file = new MessageFile(fileName, stream);

            Body.Files.Add(file);

            return(this);
        }
Example #8
0
        /// <summary>
        ///     Прикрепление файла.
        /// </summary>
        /// <param name="path"> Путь к файлу. </param>
        /// <returns> Сообщение. </returns>
        public EmailMessage AddFile(string path)
        {
            var file = new MessageFile(path);

            Body.Files.Add(file);

            return(this);
        }
Example #9
0
        private void SaveFileMsg()
        {
            bool prevLine;
            bool replaceX = (enc.CodePage == 866);

            dgvMessage.EndEdit();
            linesMsg.Clear();
            for (int i = 0; i < dgvMessage.Rows.Count; i++)
            {
                Entry  entries = (Entry)dgvMessage.Rows[i].Cells[0].Tag;
                string line    = entries.ToString(out prevLine);

                if (replaceX)
                {
                    line = line.Replace('\u0425', '\u0058'); //Replacement of Russian letter "X", to English letter
                }
                linesMsg.Add(line);

                if (prevLine)
                {
                    linesMsg[i - 1] = linesMsg[i - 1].TrimEnd('}');
                }

                foreach (DataGridViewCell cells in dgvMessage.Rows[i].Cells)
                {
                    switch (cells.ColumnIndex)
                    {
                    case 0:
                        cells.Style.ForeColor = Color.Chocolate;
                        break;

                    case 2:
                        cells.Style.ForeColor = Color.Gray;
                        break;

                    default:
                        if (entries.pcMark)
                        {
                            cells.Style.ForeColor = pcColor;
                        }
                        else
                        {
                            cells.Style.ForeColor = dgvMessage.RowsDefaultCellStyle.ForeColor;
                        }
                        break;
                    }
                }
            }
            File.WriteAllLines(msgPath, linesMsg.ToArray(), enc);
            msgSaveButton.Enabled = false;

            if (associateTab != null)
            {
                MessageFile.ParseMessages(associateTab, linesMsg.ToArray());
            }
        }
Example #10
0
 private void OpenOrCreateLastDataFile(long startId)
 {
     _lastDataFile?.Dispose();
     _lastDataFile = new MessageFile(this, startId);
     if (this._fileStartIds.Contains(startId))
     {
         return;
     }
     this._fileStartIds.Add(startId);
 }
Example #11
0
        // change the text of a field message
        public static void SetText(FileSource fieldSource, string fieldName, int messageId, string newText)
        {
            var fieldPath   = FieldScript.GetFieldPath(fieldName);
            var msdPath     = Path.Combine(fieldPath, fieldName + Globals.MessageFileExtension);
            var innerSource = new FileSource(fieldPath, fieldSource);
            var fieldText   = MessageFile.FromSource(innerSource, msdPath);

            fieldText.Messages[messageId] = newText;
            innerSource.ReplaceFile(msdPath, fieldText.Encode());
        }
Example #12
0
 public static void InitMessage()
 {
     string[] messages = Directory.GetFiles(MSG_PATH, DATAEXT);
     MESSAGES = new Dictionary <string, string>();
     foreach (string path in messages)
     {
         MessageFile mf = new MessageFile(path);
         MESSAGES = MESSAGES.Concat(mf.msgs).ToDictionary(x => x.Key, x => x.Value);
     }
 }
Example #13
0
        private bool sendFile(string path)
        {
            Message msg = MessageFile.createMessage(path);

            if (msg == null)
            {
                return(false);
            }
            return(m_messageStream.writeMessage(msg));
        }
Example #14
0
        private MessageEditor(string msg, TabInfo ti)
        {
            InitializeComponent();

            //dgvMessage.DoubleBuffered(true);
            //dgvMessage.VirtualMode = true;

            dgvMessage.Columns[2].Visible          = Settings.msgLipColumn;
            showLIPColumnToolStripMenuItem.Checked = Settings.msgLipColumn;

            FontSizeComboBox.SelectedIndex = Settings.msgFontSize;
            if (Settings.msgFontSize != 0)
            {
                FontSizeChanged(null, null);
            }
            FontSizeComboBox.SelectedIndexChanged += FontSizeChanged;

            ColorComboBox.SelectedIndex = Settings.msgHighlightColor;
            HighlightingCommToolStripMenuItem.Checked = Settings.msgHighlightComment;

            if (Settings.encoding == (byte)EncodingType.OEM866)
            {
                encodingTextDOSToolStripMenuItem.Checked = true;
            }

            StripComboBox.SelectedIndex = 2;
            if (!Settings.msgLipColumn)
            {
                dgvMessage.Columns[2].Visible          = false;
                showLIPColumnToolStripMenuItem.Checked = false;
            }

            UpdateRecentList();

            msgPath = msg;
            if (msgPath != null)
            {
                ReadMsgFile();
            }
            else
            {
                this.Text = "Empty" + this.Tag;
                AddRow(new Entry());
                linesMsg = new List <string>();
            }

            associateTab = ti;
            if (associateTab != null)
            {
                MessageFile.ParseMessages(associateTab, linesMsg.ToArray());
            }
        }
Example #15
0
        /// <summary>
        /// 从 指定fromId 开始顺序读取一定数量的消息。
        /// </summary>
        /// <param name="fromId"> 开始的Id,包含。如果fromId所在的数据已经被删除,返回空List。外面根据需要可以判断FirstId修正,内部不自动修正。 </param>
        /// <param name="count"> 读取数量,-1 一直读到结尾。</param>
        /// <returns></returns>
        public List <ChatHistoryMessage> ReadMessage(long fromId, int count)
        {
            if (fromId < 0)
            {
                throw new ArgumentException();
            }

            List <ChatHistoryMessage> result = new List <ChatHistoryMessage>();

            long countReal = count; // 内部使用long类型

            if (countReal < 0)
            {
                countReal = LastId - fromId;
            }
            if (countReal < 0)
            {
                return(result);
            }

            lock (this)
            {
                int startIdIndex = FindStartIdIndex(fromId);
                if (startIdIndex < 0)
                {
                    return(result);
                }

                for (; countReal > 0 && startIdIndex < _fileStartIds.Count; ++startIdIndex)
                {
                    long startId = _fileStartIds[startIdIndex];
                    if (_lastDataFile.StartId == startId)
                    {
                        //int realReadCount =
                        _lastDataFile.Read(fromId, countReal, result);
                        return(result); // 最后一个文件,读多少算多少,直接返回。
                    }

                    using (MessageFile mf = new MessageFile(this, startId))
                    {
                        long r = mf.Read(fromId, count, result);
                        if (r > 0)
                        {
                            countReal -= r;
                            fromId     = result[result.Count - 1].Id + 1;
                        }
                    }
                }
            }
            return(result);
        }
        private void dgvMessages_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            DataGridViewCell cell = dgvMessages.Rows[e.RowIndex].Cells[1];
            DialogueParser   data = (DialogueParser)dgvMessages.Rows[e.RowIndex].Cells[0].Tag;

            string text        = (string)cell.Value;
            string msgfilePath = (string)dgvMessages.Rows[e.RowIndex].Cells[2].Tag;

            if (MessageFile.SaveToMessageFile(msgfilePath, text, data.numberMsgLine) && data.numberMsgFile == -1)
            {
                sourceTab.messages[data.numberMsgLine] = text;
            }
        }
Example #17
0
        private void handleMessageFile(Message msg)
        {
            MessageFile msgFile = null;

            try
            {
                msgFile = new MessageFile(msg);
            }
            catch (Exception)
            {
                // Ignore
                return;
            }

            string filePath = msgFile.getFilePath();
            int    fileSize = msgFile.getFileSize();

            CConsole.writeInfoLine(string.Format("{0} Recv file {1}|{2}", cur(), filePath, fileSize));

            string saveFilePath   = m_sessionFolderPath + PathUtils.makeValidPath(filePath);
            string saveFolderPath = Path.GetDirectoryName(saveFilePath);

            if (!Directory.Exists(saveFolderPath))
            {
                Directory.CreateDirectory(saveFolderPath);
            }

            IOUtils.writeFile_Bytes(saveFilePath, msgFile.getData(), msgFile.getOffset(), fileSize);

            string clientRoot = Path.GetPathRoot(filePath);

            if (!m_listRoot.Contains(clientRoot))
            {
                m_listRoot.Add(clientRoot);

                string serverRoot = m_sessionFolderPath + PathUtils.makeValidPath(clientRoot);
                if (m_debugPrefixMap.Length > 0)
                {
                    m_debugPrefixMap += " ";
                }

                m_debugPrefixMap += GccCmdParser.makeDebugPrefixMapString(serverRoot, clientRoot);
            }
        }
Example #18
0
        public async Task CreateAsync_ShouldReturnTrueWhenAplliedFileNotNull()
        {
            var newMessageFile = new MessageFile {
                Id = 10, Name = "NewFileName", FileTypeId = 1
            };

            var mockMessageFilesQuery = new Mock <IMessageFileQuery>();

            mockMessageFilesQuery
            .Setup(m => m.Create(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(newMessageFile);

            var mockMessagesQuery = new Mock <IMessagesQuery>();

            mockMessagesQuery
            .Setup(m => m.Create(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <byte>(), It.IsAny <int?>()))
            .ReturnsAsync(0);

            var mockFormFile = new Mock <IFormFile>();

            mockFormFile.SetupGet(f => f.ContentType).Returns(GetTestFileTypes().First().Type);
            mockFormFile.SetupGet(f => f.FileName).Returns(newMessageFile.Name);

            var mockFileService = new Mock <IFileService <ChatFilesConfiguration> >();

            mockFileService
            .Setup(f => f.UploadAsync(It.IsAny <IFormFile>()))
            .ReturnsAsync(newMessageFile.Name);

            var mockContextFactory = SetupContextFactory(mockMessagesQuery.Object, mockMessageFilesQuery.Object, null);

            _sut = new TeacherChatService(mockContextFactory.Object, mockFileService.Object, _mapper);
            var request = new MessageCreateRequest {
                Sender = 1, Recipients = new int[] { 2, 3 }, Text = "NewMessageText", AppliedFile = mockFormFile.Object
            };

            // ACT
            var actual = await _sut.CreateAsync(request);

            // ASSERT
            Assert.True(actual.Entity);
        }
Example #19
0
        private static void AddAttachment(BodyBuilder builder, MessageFile file)
        {
            if (file.FileName == null)
            {
                throw new ArgumentException("Не указано имя прикрепляемого файла");
            }

            if (file.Stream != null)
            {
                builder.Attachments.Add(file.FileName, file.Stream);
                return;
            }

            if (file.Data != null)
            {
                builder.Attachments.Add(file.FileName, file.Data);
                return;
            }

            builder.Attachments.Add(file.FileName);
        }
Example #20
0
        private static void GiveFieldReward(FileSource fieldSource, int encounterID, int opCode, int[] args, string message)
        {
            var boss        = Boss.Encounters[encounterID];
            var fieldPath   = Field.FieldScript.GetFieldPath(boss.FieldID);
            var innerSource = new FileSource(fieldPath, fieldSource);

            // add message
            var msdPath   = Path.Combine(fieldPath, boss.FieldID + Globals.MessageFileExtension);
            var fieldText = MessageFile.FromSource(innerSource, msdPath);
            var msgID     = fieldText.Messages.Count;

            fieldText.Messages.Add(message);

            // give reward
            var field  = Field.FieldScript.FromSource(fieldSource, boss.FieldID);
            var script = field.Entities[boss.FieldEntity].Scripts[boss.FieldScript];
            var index  = script.Instructions.FindLastIndex(i => i.OpCode == Field.FieldScript.OpCodesReverse["battle"]) + 1;

            var awardInstructions = new List <Field.Instruction>();
            var push = Field.FieldScript.OpCodesReverse["pshn_l"];

            foreach (var a in args)
            {
                awardInstructions.Add(new Field.Instruction(push, a));
            }
            awardInstructions.Add(new Field.Instruction(opCode));

            // show message
            awardInstructions.Add(new Field.Instruction(push, 0));
            awardInstructions.Add(new Field.Instruction(push, msgID));
            awardInstructions.Add(new Field.Instruction(push, 70));
            awardInstructions.Add(new Field.Instruction(push, 70));
            awardInstructions.Add(new Field.Instruction(Field.FieldScript.OpCodesReverse["amesw"]));

            // apply changes
            script.Instructions.InsertRange(index, awardInstructions);
            innerSource.ReplaceFile(msdPath, fieldText.Encode());
            innerSource.ReplaceFile(Field.FieldScript.GetFieldPath(boss.FieldID) + "\\" + boss.FieldID + Globals.ScriptFileExtension, field.Encode());
        }
Example #21
0
        public void DeleteMessage(long id)
        {
            int startIdIndex = FindStartIdIndex(id);

            if (startIdIndex < 0)
            {
                return;
            }

            long startId = _fileStartIds[startIdIndex];

            if (_lastDataFile.StartId == startId)
            {
                _lastDataFile.Delete(id);
                return;
            }

            using (MessageFile mf = new MessageFile(this, startId))
            {
                mf.Delete(id);
            }
        }
        public ActionResult CreateThread(CreateThreadViewModel request)
        {
            try
            {
                var newThread = new PrivateThread();

                var userId = User.Identity.GetUserId();

                newThread.Recipient = db.Users.ToList().Find(x => x.UserName == request.Recipient);
                newThread.SenderID  = userId;
                newThread.Title     = request.Title;

                db.PrivateThreads.Add(newThread);
                db.SaveChanges();

                var newMessage = new PrivateMessage();

                newMessage.AuthorID      = userId;
                newMessage.Content       = Html.EditMarkers(request.Content);
                newMessage.Date          = DateTime.Now;
                newMessage.PrivateThread = newThread;


                if (Request.Files != null)
                {
                    bool error = false;
                    if (Request.Files.Count > 3)
                    {
                        error         = true;
                        ViewBag.Error = Resources.AttachmentCount;
                    }
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        if (Request.Files[i].ContentLength > 512 * 1024)
                        {
                            ViewBag.Error = Resources.AttachmentSize;
                            error         = true;
                            break;
                        }
                    }
                    if (error)
                    {
                        request.User        = db.Users.ToList().Find(x => x.Id == userId);
                        request.PostsCount  = db.Posts.ToList().FindAll(x => x.UserID == request.User.Id).Count();
                        request.TopicsCount = db.Topics.ToList().FindAll(x => x.UserID == request.User.Id).Count();

                        request.Roles = new List <IdentityRole>();

                        foreach (IdentityUserRole role in request.User.Roles)
                        {
                            request.Roles.Add(db.Roles.ToList().Find(x => x.Id == role.RoleId));
                        }

                        return(View(request));
                    }
                    db.PrivateMessages.Add(newMessage);
                    db.SaveChanges();
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFileBase file = Request.Files[i];
                        if (file == null || file.FileName == "")
                        {
                            continue;
                        }
                        file.SaveAs(HttpContext.Server.MapPath("~/Content/Attachments/")
                                    + file.FileName);
                        MessageFile _messageFile = new MessageFile();
                        _messageFile.Filename       = "~/Content/Attachments/" + file.FileName;
                        _messageFile.PrivateMessage = newMessage;
                        db.MessageFiles.Add(_messageFile);
                        db.SaveChanges();
                    }
                }
                else
                {
                    db.PrivateMessages.Add(newMessage);
                    db.SaveChanges();
                }

                return(RedirectToAction("ViewThread", new { id = newThread.ID }));
            }
            catch
            {
                var userId = User.Identity.GetUserId();

                request.User        = db.Users.ToList().Find(x => x.Id == userId);
                request.PostsCount  = db.Posts.ToList().FindAll(x => x.UserID == request.User.Id).Count();
                request.TopicsCount = db.Topics.ToList().FindAll(x => x.UserID == request.User.Id).Count();

                request.Roles = new List <IdentityRole>();

                foreach (IdentityUserRole role in request.User.Roles)
                {
                    request.Roles.Add(db.Roles.ToList().Find(x => x.Id == role.RoleId));
                }

                return(View(request));
            }
        }
        public ActionResult CreateReply(PrivateThreadViewModel request, int id)
        {
            var _newMessage = new PrivateMessage();
            var user        = db.Users.Find(User.Identity.GetUserId());
            int postsPerPage;

            _newMessage.Content = Html.EditMarkers(request.Content);

            request = new PrivateThreadViewModel();

            _newMessage.Date   = DateTime.Now;
            _newMessage.Author = db.Users.ToList().Find(x => x.Id == user.Id);

            request.User = _newMessage.Author;

            request.Content = "";

            request.PostsCount  = db.Posts.ToList().FindAll(x => x.UserID == request.User.Id).Count();
            request.TopicsCount = db.Topics.ToList().FindAll(x => x.UserID == request.User.Id).Count();

            request.Roles = new List <IdentityRole>();

            request.PrivateThread      = db.PrivateThreads.ToList().Find(x => x.ID == id);
            request.PrivateThread.Seen = false;

            _newMessage.PrivateThreadID = id;

            if (User.Identity.IsAuthenticated)
            {
                postsPerPage = user.PostsPerPage.Quantity;
            }
            else
            {
                postsPerPage = 25;
            }

            request.Messages = db.PrivateMessages.ToList().FindAll(x => x.PrivateThreadID == id).ToPagedList(1, postsPerPage);
            bool error = false;

            if (Request.Files.Count > 3)
            {
                error         = true;
                ViewBag.Error = Resources.AttachmentCount;
            }
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength > 512 * 1024)
                {
                    ViewBag.Error = Resources.AttachmentSize;
                    error         = true;
                    break;
                }
            }
            if (error)
            {
                return(View("ViewThread", request));
            }

            db.PrivateMessages.Add(_newMessage);
            db.SaveChanges();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];

                if (file.FileName == "")
                {
                    continue;
                }

                file.SaveAs(HttpContext.Server.MapPath("~/Content/Attachments/")
                            + file.FileName);
                MessageFile _messageFile = new MessageFile();
                _messageFile.Filename       = "~/Content/Attachments/" + file.FileName;
                _messageFile.PrivateMessage = _newMessage;
                db.MessageFiles.Add(_messageFile);
                db.SaveChanges();
            }

            ModelState.Clear();

            return(RedirectToAction("ViewThread", new { id = id }));
        }
Example #24
0
 protected async Task <Message> WhenReadingTheMessageFileContent()
 {
     Assert.NotNull(MessageFileInfo);
     MessageFile = new MessageFile(MessageFileInfo);
     return(ReadMessage = await MessageFile.ReadMessage());
 }
Example #25
0
 protected override async Task GivenExistingQueuedMessage(QueueName queueName, Message message, IPrincipal principal)
 {
     var queueDirectory = QueueDirectory(queueName);
     await MessageFile.Create(queueDirectory, message);
 }
Example #26
0
        public async Task <HttpResponseMessage> SendMessage(MessageCustomModel model)
        {
            try
            {
                Message email     = new Message();
                string  fromName  = "";
                var     docsender = (from doc in db.Doctors where doc.email == model.@from select new DoctorModel {
                    firstName = doc.firstName, lastName = doc.lastName
                }).FirstOrDefault();
                var patsender     = (from pat in db.Patients where pat.email == model.@from select new PatientModel {
                    firstName = pat.firstName, lastName = pat.lastName
                }).FirstOrDefault();

                if (docsender != null)
                {
                    fromName = docsender.firstName + " " + docsender.lastName;
                }
                if (patsender != null)
                {
                    fromName = patsender.firstName + " " + patsender.lastName;
                }

                if (model.to == "0")
                {
                    model.to = "*****@*****.**";
                }
                if (model.to == "" || model.to == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Reciever's email address is invalid."
                    });
                    return(response);
                }
                if (!(IsValid(model.to)))
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Reciever's email address is invalid."
                    });
                    return(response);
                }
                if (model.from == null || model.from == "" || !(IsValid(model.from)))

                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Sender's email address is invalid."
                    });
                    return(response);
                }
                if (model.message == null || model.message == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Empty message is not allowed."
                    });
                    return(response);
                }

                email.cd         = System.DateTime.Now;
                email.senderName = fromName;
                email.subject    = model.subject;
                email.mesage     = model.message;
                email.from       = model.from;
                email.to         = model.to;
                email.isRead     = false;
                email.status     = "1";
                email.replyLink  = model.replyLink;
                if (model.msgFile != null)
                {
                    email.hasAttachment = true;
                }
                if (model.msgFile == null)
                {
                    email.hasAttachment = false;
                }
                db.Messages.Add(email);
                await db.SaveChangesAsync();

                if (model.msgFile != null)
                {
                    foreach (var item in model.msgFile)
                    {
                        MessageFile emailattch = new MessageFile();
                        emailattch.msgID       = email.msgID;
                        emailattch.fileContent = item.fileContent;
                        emailattch.fileName    = item.fileName;
                        db.MessageFiles.Add(emailattch);
                        await db.SaveChangesAsync();
                    }
                }

                response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                    ID = email.msgID, message = ""
                });
                return(response);
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "SendMessage in MessagesController."));
            }
        }
Example #27
0
 protected AdminCommandResult CommandErrorLocalized(string key, Embed embed = null, MessageFile file = null,
                                                    params object[] args)
 => new AdminCommandResult(_watch.Elapsed, Localization.Localize(Context.Language, key, args), embed, file,
                           false);
Example #28
0
 protected MessageFile WhenReadingTheMessageFileContent()
 {
     Assert.NotNull(MessageFileInfo);
     return(MessageFile = new MessageFile(MessageFileInfo));
 }
        public ActionResult SendMessage(MessageAuthor message)
        {
            //Доделать проверку
            Message m = new Message()
            {
                TopicId = message.TopicId, Content = message.Content
            };

            m.UserId = db.Users.FirstOrDefault(n => n.Email == message.Author).Id;
            m.Date   = DateTime.Now;
            db.Messages.Add(m);
            db.SaveChanges();
            m = db.Messages.Find(m.Id);
            if (message.Files.Count() != 0)
            {
                foreach (var photo in message.Photos)
                {
                    if (photo == null)
                    {
                        continue;
                    }
                    string Extension = Path.GetExtension(photo.FileName);
                    string Name      = (Directory.GetFiles(Server.MapPath("~/Files/Photo")).Length / 2).ToString();
                    photo.InputStream.Seek(0, SeekOrigin.Begin);
                    ImageBuilder.Current.Build(new ImageJob(
                                                   photo.InputStream,
                                                   Server.MapPath("~/Files/Photo/") + Name + "_small" + Extension,
                                                   new Instructions("maxwidth=100&maxheight=100"),
                                                   false,
                                                   false
                                                   )
                                               );
                    photo.InputStream.Seek(0, SeekOrigin.Begin);
                    photo.SaveAs(Server.MapPath("~/Files/Photo/") + Name + Extension);
                    MessageFile mf = new MessageFile()
                    {
                        Path = Name + Extension, MessageId = m.Id, IsPhoto = true, OriginalName = Name + Extension
                    };
                    mf.Name      = Name;
                    mf.Extension = Extension;
                    db.MessageFiles.Add(mf);
                    db.SaveChanges();
                }
                foreach (var file in message.Files)
                {
                    if (file == null)
                    {
                        continue;
                    }
                    string Extension = Path.GetExtension(file.FileName);
                    string Name      = Directory.GetFiles(Server.MapPath("~/Files/UserFiles/")).Length.ToString();
                    file.SaveAs(Server.MapPath("~/Files/UserFiles/") + Name + Extension);
                    MessageFile mf = new MessageFile()
                    {
                        Path = Name + Extension, MessageId = m.Id, IsPhoto = false, OriginalName = Name + Extension
                    };
                    mf.Name      = Name;
                    mf.Extension = Extension;
                    db.MessageFiles.Add(mf);
                    db.SaveChanges();
                }
            }

            return(RedirectToAction("Topic", "Home", new { id = message.TopicId }));
        }
Example #30
0
        private void BuildMessageDialog()
        {
            int addFemale = 0;

            if (femaleToolStripMenuItem.Checked)
            {
                int.TryParse(toolStripTextBox.Text, out addFemale);
            }

            string msg, msgPath = null;

            foreach (DialogueParser line in Arguments)
            {
                if (line.opcode == OpcodeType.None)
                {
                    continue;
                }
                int  n     = addFemale;
                bool error = false;
                if (line.numberMsgLine > 0)
                {
                    if (readMsgNum != line.numberMsgFile)
                    {
                        if (line.numberMsgFile != -1)
                        {
                            string path;
                            if (!MessageFile.GetPath(sourceTab, line.numberMsgFile, out path))
                            {
                                msg     = String.Format(MessageFile.msgfileError, line.numberMsgFile);
                                msgPath = null;
                                error   = true;
                                goto skip;
                            }
                            msgPath = path;
                        }
                        else
                        {
                            msgPath = sourceTab.msgFilePath;
                        }

                        readMsgNum   = line.numberMsgFile;
                        MessagesData = File.ReadAllLines(msgPath, Settings.EncCodePage); // загрузить другой файл сообщений
                    }

                    msg = MessageFile.GetMessages(MessagesData, addFemale + line.numberMsgLine);
                    if (msg == null && addFemale > 0)
                    {
                        msg = MessageFile.GetMessages(MessagesData, line.numberMsgLine);
                        n   = 0;
                    }
                    if (msg == null)
                    {
                        msg   = MessageFile.messageError;
                        error = true;
                    }
                }
                else
                {
                    msg = "<" + line.shortcode + ">";
                }
skip:
                dgvMessages.Rows.Add(line.toNode.Trim('"', ' '), msg, line.iq, (line.numberMsgLine > 0) ? n + line.numberMsgLine : line.numberMsgLine);
                dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[0].Tag = line.opcode;
                if (line.opcode == OpcodeType.Option || line.opcode == OpcodeType.giq_option || line.opcode == OpcodeType.gsay_option)
                {
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].Value = (char)0x25CF + " " + msg;
                    if (!error)
                    {
                        dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].Style.ForeColor = Color.Blue;
                    }
                }
                if (line.numberMsgFile != -1)
                {
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[3].Tag = msgPath;
                }
                if (error)
                {
                    dgvMessages.Rows[dgvMessages.Rows.Count - 1].Cells[1].Style.ForeColor = Color.Red;
                }
            }
        }