Example #1
0
 public void FileMessage(string emailAddress, int groupId, FileMessage file)
 {
     file.UserId  = emailAddress;
     file.GroupId = groupId;
     _context.FileMessage.Add(file);
     _context.SaveChanges();
 }
Example #2
0
        public ActionResult <IEnumerable <Order> > Get()
        {
            var file     = new File();
            var fileInfo = new FileInfo(FilePath);
            var engine   = new FileHelperEngine <Order>();
            var records  = engine.ReadFile(fileInfo.FullName);

            file.TotalRecords     = engine.TotalRecords;
            file.FilePath         = fileInfo.FullName;
            file.LastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
            file.ProcessTimeUtc   = DateTime.UtcNow;

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "files", durable: true, exclusive: false, autoDelete: false, arguments: null);

                    var fileMsg = new FileMessage(channel);
                    fileMsg.Push(file);
                    channel.QueueDeclare(queue: "orders", durable: false, exclusive: false, autoDelete: false, arguments: null);
                    var msg = new OrderMessage(channel);
                    foreach (var record in records)
                    {
                        msg.Push(record);
                    }
                }

            return(records);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>Stand</returns>
        private List <Stands> GetAllStands()
        {
            List <Stands> stand = null;

            FileStatus = FileMessage.None;
            try
            {
                using (StandRepository sRepository = new StandRepository())
                {
                    stand = sRepository.GetAll() as List <Stands>;
                };

                if (stand != null)
                {
                    FileStatus = FileMessage.Complete;
                }
                else
                {
                    FileStatus = FileMessage.RecordNotFound;
                }
            }
            catch (Exception)
            {
                FileStatus = FileMessage.FileAccessError;
            }

            return(stand);
        }
Example #4
0
        ///
        ///  retrieve a stand using the repository
        ///
        private Stands GetStand(int id)
        {
            Stands stand = null;

            FileStatus = FileMessage.None;
            try
            {
                using (StandRepository sRepository = new StandRepository())
                {
                    stand = sRepository.GetById(id);
                };

                if (stand != null)
                {
                    FileStatus = FileMessage.Complete;
                }
                else
                {
                    FileStatus = FileMessage.RecordNotFound;
                }
            }
            catch (Exception)
            {
                FileStatus = FileMessage.FileAccessError;
            }

            return(stand);
        }
Example #5
0
        public void SendFile(string filePath)
        {
            if (receiver == null)
            {
                return;
            }

            var fileInfo   = new FileInfo(filePath);
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);;

            try
            {
                var buffer = new byte[fileStream.Length];

                fileStream.Read(buffer, 0, buffer.Length);

                var fMsg = new FileMessage();
                fMsg.FileName = fileInfo.Name;
                fMsg.Sender   = localClient.Name;
                fMsg.Data     = buffer;
                chatClient.SendFileAsync(fMsg, receiver);
            }
            catch (Exception exception)
            {
                ServiceMessage.AppendLine(exception.Message);
            }
            finally
            {
                fileStream.Close();
            }
        }
Example #6
0
        private void Connection_ClientPullFile(object sender, byte[] data)
        {
            var @this = sender as Connection;

            if (@this == null)
            {
                return;
            }
            var fileId = Encoding.UTF8.GetString(data);

            lock (_filenames)
            {
                if (_filenames.TryGetValue(fileId, out string fileName))
                {
                    IPEndPoint endPoint = (IPEndPoint)@this.Socket.RemoteEndPoint;
                    Console.WriteLine($"Client [{endPoint.Address}:{endPoint.Port}]({@this.ClientName}) pull file {fileName}({fileId}).");

                    FileInfo fileInfo = new FileInfo("attachments/" + fileId);
                    if (!fileInfo.Exists)
                    {
                        //FIXME
                        return;
                    }

                    byte[] fileBytes   = File.ReadAllBytes(fileInfo.FullName);
                    var    fileMessage = new FileMessage(Utility.GenerateID(), null, null, fileId, fileName, fileInfo.Length)
                    {
                        data = fileBytes
                    };
                    @this.SendMessage(MessageType.SYSTEM_FILE_TRANSFER, fileMessage);
                }
            }
        }
Example #7
0
        public async Task <IActionResult> PutFileMessage([FromRoute] int id, [FromBody] FileMessage fileMessage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != fileMessage.FileMessageId)
            {
                return(BadRequest());
            }

            _context.Entry(fileMessage).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FileMessageExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #8
0
    private IEnumerator LoadWavCoroutine(string fileName)
    {
        networkUIManager.ShowClientInfo("File is loading... please wait...");
        StartCoroutine(audioSerializer.LoadAudioClipToByte(fileName));
        while (audioSerializer.isLoading == true)
        {
            yield return(null);
        }
        networkUIManager.ShowClientInfo("File loading complete!");
        int size    = audioSerializer.loadedAudio.Length;
        int fracNum = (size / 1024) + 1;

        Debug.Log(size.ToString());
        Debug.Log(fracNum.ToString());
        FileMessage[] message = new FileMessage[fracNum];

        for (int i = 0; i < message.Length; i++)
        {
            message[i]          = new FileMessage();
            message[i].contents = new byte[1024];
            Debug.Log(i);
            Buffer.BlockCopy(audioSerializer.loadedAudio, 1024 * i, message[i].contents, 0, 1024);
            message[i].fileType = FileType.Wav;
            message[i].fileName = fileName;
            message[i].maxFrac  = fracNum;
            message[i].fracNum  = i + 1;
        }

        for (int i = 0; i < message.Length; i++)
        {
            client.Send(CustomMsgType.FileMsgType, message[i]);
            yield return(null);
        }
    }
Example #9
0
        public string CREATE_FILE_MESSAGE(FileMessage fm)
        {
            var f = fm.file;

            return($"insert into {GeneralConsts.FILE_MESSAGE_TABLE} (messageUUID, fileUUID, filePath) output inserted.* " +
                   $"values ('{fm.messageUUID}', '{f.uuid}', '{f.filePath}');");
        }
Example #10
0
        private void Invoke(csockdata message)
        {
            switch (message.MessageType)
            {
            case MessageType.Message:
                MessageObject objmes = JsonConvert.DeserializeObject <MessageObject>(message.Value, _jsonSerializerSettings);
                if (OnMessage != null)
                {
                    OnMessage(objmes);
                }
                break;

            case MessageType.FileAction:
                FileMessage fileMessage = JsonConvert.DeserializeObject <FileMessage>(message.Value, _jsonSerializerSettings);
                if (OnFileMessage != null)
                {
                    OnFileMessage(fileMessage);
                }
                break;

            case MessageType.GetAllFileInformation:
                List <FileMessage> fileMessages = JsonConvert.DeserializeObject <List <FileMessage> >(message.Value, _jsonSerializerSettings);
                if (OnGetAllFileInformation != null)
                {
                    OnGetAllFileInformation(fileMessages);
                }
                break;
            }
        }
Example #11
0
        public Task SendFile(string filename)
        {
            var file        = new BrokeredMessage(OpenFile(filename));
            var fileMessage = new FileMessage(Path.GetFileName(filename), file);

            return(Task.Factory.StartNew(() => _messageClient.Send(fileMessage)));
        }
Example #12
0
    bool CheckEveryoneReady()
    {
        foreach (KeyValuePair <int, Player> entry in players)
        {
            if (entry.Value.ready == false)
            {
                return(false);
            }
        }

        GameStateManager.instance.setGlobalStateIndex(GameStateManager.STATE_PLAYING);
        VRAR_Level levelTile   = GameStateManager.instance.getCurrentLevel();
        var        fileMessage = new FileMessage();
        TextReader tr;

        if (Application.isEditor)
        {//use the project location
            tr = new StreamReader(Application.dataPath + "/levels/" + "/level_" + levelTile.levelTile.tileIndex_X + "#" + levelTile.levelTile.tileIndex_Y + ".sav");
        }
        else
        {//use the user save location
            tr = new StreamReader(Application.persistentDataPath + "/levels/" + "/level_" + levelTile.levelTile.tileIndex_X + "#" + levelTile.levelTile.tileIndex_Y + ".sav");
        }
        fileMessage.file = tr.ReadToEnd();
        NetworkServer.SendToAll(NetworkMessages.File, fileMessage);

        SceneManager.LoadScene(1);


        return(true);
    }
Example #13
0
        public FileMessage GetFileMessage(System.Net.WebResponse response)
        {
            FileMessage info = new FileMessage();

            if (response.Headers["Content-Disposition"] != null)
            {
                Match match = Regex.Match(response.Headers["Content-Disposition"], "filename=(.*)");
                if (match.Success)
                {
                    string   fileName = match.Groups[1].Value;
                    Encoding encoding = Encoding.UTF8;
                    string   str      = (response as HttpWebResponse).CharacterSet;
                    if (!String.IsNullOrEmpty(str))
                    {
                        encoding = Encoding.GetEncoding(str);
                    }
                    info.FileName = System.Web.HttpUtility.UrlDecode(fileName, encoding);
                }
            }

            if (response.Headers["Content-Length"] != null)
            {
                info.Length = long.Parse(response.Headers.Get("Content-Length"));
            }
            else
            {
                info.Length = response.ContentLength;
            }

            return(info);
        }
Example #14
0
        public static FileMessage Directory(String path, ref Int32 fileNumber, ref String[] files, Boolean absolutePath)
        {
            FileMessage fMSG = Directory(path, ref files, absolutePath);

            fileNumber = files == null ? 0 : files.Length;
            return(fMSG);
        }
Example #15
0
        public override void Send(FileMessage fileMessage)
        {
            var udpClient = new UdpClient();

            udpClient.Connect(this.ServerName, this.ServerPort);

            try
            {
                var message = fileMessage.ToByteArray();

                udpClient.Send(message, message.Length);

                this.Results.BytesSent        = message.Length;
                this.Results.NumberOfMessages = 1;

                var RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, ServerPort);
                var receiveBytes     = udpClient.Receive(ref RemoteIpEndPoint);
                var returnData       = Encoding.ASCII.GetString(receiveBytes);

                Console.WriteLine(this.GetResultsMessage);
                Console.WriteLine($"Message from server: {returnData}");

                udpClient.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #16
0
 public List <FileMessage> GetAllFileInformation(string username, string path)
 {
     try
     {
         List <FileMessage> result   = new List <FileMessage>();
         string             rootPath = Constants.ServerFolderPath;
         string             getPath  = rootPath;
         if (string.Compare(path, "root") == 0)
         {
             getPath = rootPath + path;
         }
         String[] allfiles = System.IO.Directory.GetFiles(rootPath, "*.*", System.IO.SearchOption.AllDirectories);
         Random   gen      = new Random();
         foreach (string f in allfiles)
         {
             FileMessage temp = new FileMessage();
             temp.Action           = FileAction.All;
             temp.FileName         = System.IO.Path.GetFileName(f);
             temp.FilePath         = f.Substring(rootPath.Length, f.Length - temp.FileName.Length - rootPath.Length - 1);
             temp.UserName         = username;
             temp.FullName         = username;
             temp.LockedByFullName = gen.Next(100) < 50 ? "Server Locked" : "";
             temp.LockedByUserName = string.IsNullOrEmpty(temp.LockedByFullName) ? "" : "ServerLocked";
             temp.FileMD5          = FileHelper.GetMD5HashFromFile(f);
             result.Add(temp);
         }
         return(result);
     }
     catch { return(null); }
 }
Example #17
0
        private async void SendFileBtnEvent(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() == true)
            {
                string      fullPath = openFileDialog.FileName;
                string      fileName = System.IO.Path.GetFileName(fullPath);
                FileMessage file     = new FileMessage()
                {
                    FileBinary  = File.ReadAllBytes(fullPath),
                    FileHeaders = fileName
                };
                try
                {
                    await connection.InvokeAsync("FileMessage", _emailAddress, _groupId, file);

                    await connection.InvokeAsync("SendMessage", _emailAddress, _groupId, "Sent file \"" + fileName + "\"");
                }
                catch (Exception exception)
                {
                    MessageList.AppendText(exception.Message);
                }
            }
        }
Example #18
0
        private void Websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            var message = JsonConvert.DeserializeObject <csockdata>(e.Message);

            switch (message.MessageType)
            {
            case MessageType.Message:
                MessageObject objmes = JsonConvert.DeserializeObject <MessageObject>(message.Value, _jsonSerializerSettings);
                if (OnMessage != null)
                {
                    OnMessage(objmes);
                }
                break;

            case MessageType.FileAction:
                FileMessage fileMessage = JsonConvert.DeserializeObject <FileMessage>(message.Value, _jsonSerializerSettings);
                if (OnFileMessage != null)
                {
                    OnFileMessage(fileMessage);
                }
                break;

            case MessageType.GetAllFileInformation:
                List <FileMessage> fileMessages = JsonConvert.DeserializeObject <List <FileMessage> >(message.Value, _jsonSerializerSettings);
                if (OnGetAllFileInformation != null)
                {
                    OnGetAllFileInformation(fileMessages);
                }
                break;
            }
        }
Example #19
0
 public void ReceiverFile(FileMessage fileMessage, string receiver)
 {
     try
     {
         DialogResult dialogResult = MessageBox.Show(fileMessage.Sender + " send cho ban " + fileMessage.FileName, "Send file",
                                                     MessageBoxButtons.OKCancel);
         if (dialogResult == DialogResult.OK)
         {
             SaveFileDialog saveFileDialog1 = new SaveFileDialog();
             saveFileDialog1.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
             saveFileDialog1.FilterIndex      = 2;
             saveFileDialog1.FileName         = fileMessage.FileName;
             saveFileDialog1.RestoreDirectory = true;
             saveFileDialog1.ShowDialog();
             FileStream fileStream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
             fileStream.Write(fileMessage.Data, 0, fileMessage.Data.Length);
             AppendText(RTBRoom, Color.Blue, "\n                              Received File " + fileMessage.FileName + "\n");
             proxy.SendMessageBack(fileMessage.Sender, "                              File Sent!\n");
         }
     }
     catch (Exception ex)
     {
         AppendText(RTBRoom, Color.Blue, ex.Message.ToString());
     }
 }
Example #20
0
        /// <summary>
        /// 发送图片
        /// </summary>
        /// <param name="fileName"></param>
        private void sendPicture(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }

            var ext     = fileName.Substring(fileName.LastIndexOf('.') + 1);
            var message = new NIMImageMessage
            {
                SessionType     = NIMSessionType.kNIMSessionTypeP2P,
                ReceiverID      = target.accid,
                ImageAttachment = new NIMImageAttachment {
                    DisplayName = fileName, FileExtension = ext
                },
                LocalFilePath = fileName,
            };
            var body = new FileMessage {
                image = Util.getImageFromFile(fileName)
            };

            message.ImageAttachment.Height = body.image.Height;
            message.ImageAttachment.Width  = body.image.Width;

            sendMessage(1, body);
            TalkAPI.SendMessage(message);
        }
Example #21
0
        public bool SendFile(FileMessage fileMsg, Client receiver)
        {
            foreach (Client rcvr in clients.Keys)
            {
                if (rcvr.Name == receiver.Name)
                {
                    Message msg = new Message
                    {
                        Sender  = fileMsg.Sender,
                        Content = "I'M SENDING FILE.. " + fileMsg.FileName
                    };

                    IPOGCallback rcvrCallback = clients[rcvr];
                    rcvrCallback.ReceiveWhisper(msg, receiver);
                    rcvrCallback.ReceiverFile(fileMsg, receiver);

                    foreach (Client sender in clients.Keys)
                    {
                        if (sender.Name == fileMsg.Sender)
                        {
                            IPOGCallback sndrCallback = clients[sender];
                            sndrCallback.ReceiveWhisper(msg, receiver);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Example #22
0
 private void RecieveData(IAsyncResult iar)
 {
     try
     {
         ep     = ipEndPoint;
         kvPair = (KeyValuePair <Socket, byte[]>)iar.AsyncState;
         int recv = kvPair.Key.EndReceiveFrom(iar, ref ep);
         if (recv > 0)
         {
             string preamble = Encoding.Default.GetString(kvPair.Value, 0, 2);
             if (preamble == "AA")
             {
                 Msg = TextMessage.DecodeMessage(kvPair.Value);
                 if (TextMessageRecieved != null)
                 {
                     TextMessageRecieved(new MessageRecievedEventArgs(Msg));
                 }
             }
             else if (preamble == "BB")
             {
                 FileMessage msg = FileMessage.DecodeMessage(kvPair.Value);
                 if (FileMessageRecieved != null)
                 {
                     FileMessageRecieved(new FileMessageRecievedEventArgs(msg));
                 }
             }
         }
         Listen();
     }
     catch (Exception ex) { }
 }
Example #23
0
        /// <summary>
        /// 消息处理函数
        /// </summary>
        /// <param name="message">消息</param>
        private void OnMessage(ClientSocket socket, Message.Message req)
        {
            switch (req.Header.MsgType)
            {
            case MessageType.Text:
                Message.Message resp = new Message.Message();
                resp.Body = req.Body;

                socket.Send(resp.Serialize());
                break;

            case MessageType.File:
                if (!Directory.Exists(FileStoreDir))
                {
                    Directory.CreateDirectory(FileStoreDir);
                }

                FileMessage message = new FileMessage(req);
                using (FileStream fs = File.OpenWrite(FileStoreDir + Path.DirectorySeparatorChar + message.FileName))
                {
                    fs.Write(message.Data, 0, message.Data.Length);
                }

                Console.WriteLine("{0} saved to {1}", message.FileName, FileStoreDir);
                break;
            }
        }
Example #24
0
        public void SendImage( FileMessage fileMsg )
        {
            var ok = true;
            foreach (var img in SettingHandler.ImageList.Where(img => img == fileMsg.FileName))
            {
                ok = false;
            }
            if (ok)
            {
                MainWindow.CurrentInstance.UpdateFileReceive();
                try
                {
                    var fileStrm = new FileStream(XmlHandler.GrabXmlValue(SettingHandler.GrabSettingFile(), "PicFilePath") + @"\" + fileMsg.FileName, FileMode.Create, FileAccess.ReadWrite);
                    fileStrm.Write(fileMsg.Data, 0, fileMsg.Data.Length);
                    fileStrm.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            MainWindow.CurrentInstance.CreateNotification(new Uri(XmlHandler.GrabXmlValue(SettingHandler.GrabSettingFile(), "PicFilePath") + @"\" + fileMsg.FileName));

            var picnotinlist = true;
            foreach (var img in SettingHandler.ImageList.Where(img => fileMsg.FileName == img))
            {
                picnotinlist = false;
            }
            if (picnotinlist)
            {
                SettingHandler.ImageList.Add(fileMsg.FileName);
            }
        }
Example #25
0
        private void SaveFile(Entities.FileMessage msg)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            if (msg.FileMessageType == FileMessageType.Responese)
            {
                if (msg.FileStatus == FileStatus.NotStarted)
                {
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        FileNameToSave = dlg.FileName + ".pdf";
                        FileManager mgr = new FileManager(FileNameToSave, msg);
                        mgr.Save();

                        //msg.Index++;
                        msg.IpAddress       = com.GetMyIPAddress();
                        msg.FileStatus      = FileStatus.Started;
                        msg.FileMessageType = FileMessageType.Request;
                        msg.IPLength        = msg.IpAddress.Length;
                        com.Send(msg, new System.Net.IPEndPoint(IPAddress.Parse(msg.IpAddress), 8000));
                    }
                }
                else
                {
                    FileManager mgr = new FileManager(FileNameToSave, msg);
                    mgr.Save();

                    msg.Index++;
                    msg.IpAddress       = com.GetMyIPAddress();
                    msg.FileMessageType = FileMessageType.Request;
                    msg.IPLength        = msg.IpAddress.Length;
                    if (msg.FileStatus == FileStatus.Started)
                    {
                        com.Send(msg, new System.Net.IPEndPoint(IPAddress.Parse(msg.IpAddress), 8000));
                    }
                }
            }
            else if (msg.FileMessageType == FileMessageType.Request)
            {
                FileManager mgr = new FileManager(msg);
                //byte[] data = mgr.GetBytes(msg.Index);
                //msg.Data = new byte[data.Length];
                //Array.Copy(data, 0, msg.Data, 0, data.Length);
                //msg.IpAddress = com.GetMyIPAddress();
                //msg.IPLength = msg.IpAddress.Length;

                FileMessage fileMessage = mgr.GetMessage();
                fileMessage.FileMessageType = FileMessageType.Responese;
                fileMessage.IpAddress       = com.GetMyIPAddress();
                fileMessage.DataLength      = fileMessage.Data.Length;
                fileMessage.IPLength        = fileMessage.IpAddress.Length;
                fileMessage.FileName        = msg.FileName;
                fileMessage.FileNameLength  = msg.FileNameLength;
                fileMessage.FileStatus      = msg.FileStatus;
                fileMessage.Index           = msg.Index;
                fileMessage.Preamble        = msg.Preamble;
                com.Send(fileMessage, new System.Net.IPEndPoint(IPAddress.Parse(msg.IpAddress), 8000));
            }
        }
Example #26
0
 public void ReceiveFileMessage(FileMessage F)
 {
     File.WriteAllBytes(F.FileName, F.Content);
     txtConversation.Text      += F.From + ": " + F.FileName + '\n';
     txtConversation.CaretIndex = txtConversation.Text.Length;
     txtConversation.ScrollToEnd();
     txtMessage.Focus();
 }
Example #27
0
 void OnFileMessageReceivedFromPeerHandler2(int id, string peerId, FileMessage message)
 {
     Debug.Log("----------- id = " + id + " ,peerId = " + peerId + " fileMessage, = " + message.GetFileName() + "   " + message.GetMediaId() + "  " + message.GetRawMessageLength() + "  " + message.GetServerReceiveTs() + "  " + message.IsOfflineMessage());
     //fileMessage = rtmClient.CreateFileMessageByMediaId(message.GetMediaId());
     //Debug.Log("------------" + " fileMessage, = " + fileMessage.GetFileName() + "   " + fileMessage.GetMediaId() + "  " + fileMessage.GetRawMessageLength() + "  " + fileMessage.GetServerReceiveTs() + "  " + fileMessage.IsOfflineMessage());
     rtmClient.DownloadMediaToMemory(message.GetMediaId(), 1982939);
     rtmClient.DownloadMediaToFile(message.GetMediaId(), "/Users/zhangtao/Documents/work/Unitywork/unity_rtm/API-Example/test_download_file.txt", 1322323);
 }
Example #28
0
        private void ReceiveFileMessage(FileMessage file)
        {
            MessageList.AppendText("File received\n");

            Directory.CreateDirectory(storageDir);
            File.WriteAllBytes(System.IO.Path.Combine(storageDir, file.FileHeaders), file.FileBinary);
            MessageList.AppendText((file.FileHeaders));
        }
Example #29
0
        public PriorityFsQueue(QueueHost qp)
            : base(qp.HostName)
        {
            int numProcs         = Environment.ProcessorCount;
            int concurrencyLevel = numProcs * 2;
            int initialCapacity  = 101;

            QueueList = new ConcurrentDictionary <Ptr, IQueueItem>(concurrencyLevel, initialCapacity);

            //CommitMode = qp.CommitMode;
            //CoverMode = qp.Mode;
            RootPath   = qp.RootPath;
            CommitMode = qp.CommitMode;
            CoverMode  = qp.CoverMode;

            if (qp.CoverMode == CoverMode.FileStream)
            {
                CoverMode = CoverMode.FileStream;
                //DbLiteSettings settings = new DbLiteSettings()
                //{
                //    Name = qp.QueueName,
                //    CommitMode = (CommitMode)(int)qp.CommitMode,
                //    DbPath = AgentManager.Settings.QueuesPath
                //};
                //settings.SetFast();
                //QueueHost queueHost = qp.GetRoutHost();
                m_fs        = new FileMessage(qp);
                m_fs.Logger = Logger;
                //InitRecoverQueue();

                //m_db = new PersistentBinary<IQueueItem>(settings);
                ////m_db = new PersistentDictionary(settings);
                //m_db.BeginLoading += M_db_BeginLoading;
                //m_db.LoadCompleted += M_db_LoadCompleted;
                //m_db.ErrorOcurred += M_db_ErrorOcurred;
                //m_db.ClearCompleted += M_db_ClearCompleted;
                ////m_db.ItemChanged += M_db_ItemChanged;

                //m_db.ItemLoaded = (item) =>
                //{
                //    this.ReEnqueue(item);
                //};

                if (qp.ReloadOnStart)
                {
                    Logger.Info("PriorityFsQueue will load items to : {0}", qp.HostName);
                    m_fs.ReloadItemsAsync(FolderType.Queue, 0, (IQueueItem item) =>
                    {
                        this.ReEnqueue(item);
                    });
                }
                else
                {
                    Logger.Info("PriorityFsQueue will clear all items from : {0}", qp.HostName);
                    m_fs.ClearItems(FolderType.Queue);
                }
            }
        }
        /// <summary>
        /// restricted to upload image file , for staging purpose
        /// </summary>
        /// <param name="file"></param>
        /// <param name="key"></param>
        /// <param name="fileInfor"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        internal static FileMessage UploadFile(FileInfo file, string key, out FileInfor fileInfor, string p2)
        {
            var    client = _imageService;
            string fileKey;
            string fileExt;

            fileInfor = new FileInfor();
            FileMessage f = client.GetFileName(key, (int)file.Length, file.Name, file.Extension, out fileKey, out fileExt);

            if (f == FileMessage.Success)
            {
                fileInfor.FileName     = fileKey;
                fileInfor.FileSize     = (int)file.Length;
                fileInfor.FileExtName  = fileExt;
                fileInfor.ResourceType = ContentType.GetResourceType(fileExt);


                try
                {
                    FileUploadMessage inValue = new FileUploadMessage();
                    inValue.FileName   = fileKey;
                    inValue.KeyName    = key;
                    inValue.FileExt    = fileExt;
                    inValue.SaveOrigin = true;


                    using (var fileHR = file.OpenRead())
                    {
                        inValue.FileData = fileHR;

                        int width, height;
                        using (var image = System.Drawing.Image.FromStream(fileHR))
                        {
                            width  = image.Width;
                            height = image.Height;
                        }
                        fileHR.Seek(0, SeekOrigin.Begin);
                        fileInfor.Width  = width;
                        fileInfor.Height = height;

                        client.UploadFileAndReturnInfo(inValue);
                        fileHR.Close();
                    }


                    return(FileMessage.Success);
                }
                catch
                {
                    return(FileMessage.UnknowError);
                }
            }
            else
            {
                return(f);
            }
        }
Example #31
0
 /// <summary>
 /// 初始化界面,准备接收
 /// </summary>
 /// <param name="fm"></param>
 public void ReceiveFile( FileMessage fm)
 {
    
     var receiveFile = new FileTransferGrid(false, fm);
   
     sp.Children.Add(receiveFile);
     transferTask.Add(fm.Guid, receiveFile);
     count++;
 }
Example #32
0
 public override void Dispose()
 {
     base.Dispose();
     if (m_fm != null)
     {
         m_fm.Dispose();
         m_fm = null;
     }
 }
Example #33
0
        /// <summary>
        /// 初始化界面,准备发送
        /// </summary>
        /// <param name="fm"></param>
        public void SendFile( FileMessage fm)
        {
            
            var sendFile=new FileTransferGrid(true, fm);
           
            sp.Children.Add(sendFile);
             transferTask.Add(fm.Guid,sendFile);
            count++;

        }
Example #34
0
 public void SendFile( FileMessage fileMsg )
 {
     MainWindow.CurrentInstance.UpdateFileReceive();
     try
     {
         var fileStrm = new FileStream(XmlHandler.GrabXmlValue(SettingHandler.GrabSettingFile(), "DataFilePath") + fileMsg.FileName, FileMode.Create, FileAccess.ReadWrite);
         fileStrm.Write(fileMsg.Data, 0, fileMsg.Data.Length);
         fileStrm.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     MainWindow.CurrentInstance.UpdateFileReceive(true);
 }
Example #35
0
 public SendFileUtil(FileMessage fm, UI.FileTransferGrid fileTransferGrid):
     base(fm,fileTransferGrid)
 {
     initTCPClient();
 }
 public void ReceivedFile(FileMessage fileMsg)
 {
     Action file = () =>
     {
         _files.Add(new KeyValuePair<int, FileMessage>(_files.Count,fileMsg));
         mnuResivedFiles.Background = Brushes.Lime;
     };
     Dispatcher.BeginInvoke(file);
 }
        private void SendFile(string reciver)
        {
            var fd = new OpenFileDialog { Multiselect = false };
            if (fd.ShowDialog() == DialogResult.HasValue) return;

            var fm = new FileMessage
            {
                Data = File.ReadAllBytes(fd.FileName),
                Sender = _localClient.Name,
                FileName = fd.SafeFileName,
                Reciver = reciver,
                Time = DateTime.Now
            };
            _proxyClient.SendFileAsync(fm);
        }
Example #38
0
        void MyMenu_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            if (this.baseRole is Member)
            {
                Member member = this.baseRole as Member;
                if (member.status == MemberStatus.Offline)
                {
                    return;
                }

                switch(messageType)
                {
                    case MessageType.File:
                        {
                            OpenFileDialog ofd = new OpenFileDialog();
                            ofd.RestoreDirectory = true;
                            ofd.ShowDialog();

                            FileMessage fm = new FileMessage();
                            fm.from = DataUtil.Member;
                            fm.to = this.baseRole;

                            fm.Path = ofd.FileName;
                            if (!File.Exists(fm.Path))
                                return;
                            fm.FileName = ofd.SafeFileName;
                            fm.Size = ofd.OpenFile().Length;
                            fm.sendTime = DateTime.Now;
                            fm.Guid = Guid.NewGuid().ToString();


                            DataUtil.Transfer.SendFile(fm);
                            break;
                        }
                    case MessageType.Audio:
                        {

                            this.IsEnabled = false;
                            AudioMessage am = new AudioMessage();
                            am.from = DataUtil.Member;
                            am.to = this.baseRole;

                            DataUtil.Client.SendMesg(am);
                            AudioForm af = new AudioForm(am, true);
                            
                            af.Show();
                            af.Closed += new EventHandler((obj, args) =>
                                {
                                    this.IsEnabled = true;
                                });
                            break;
                        }
            }

            }
        }
Example #39
0
 public void ReceiverFile(FileMessage fileMessage, string receiver)
 {
     try
     {
         DialogResult dialogResult = MessageBox.Show(fileMessage.Sender + " send cho ban " + fileMessage.FileName, "Send file",
                     MessageBoxButtons.OKCancel);
         if (dialogResult == DialogResult.OK)
         {
             SaveFileDialog saveFileDialog1 = new SaveFileDialog();
             saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
             saveFileDialog1.FilterIndex = 2;
             saveFileDialog1.FileName = fileMessage.FileName;
             saveFileDialog1.RestoreDirectory = true;
             saveFileDialog1.ShowDialog();
             FileStream fileStream = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.ReadWrite);
             fileStream.Write(fileMessage.Data, 0, fileMessage.Data.Length);
             AppendText(RTBRoom, Color.Blue, "\n                              Received File " + fileMessage.FileName +"\n");
             proxy.SendMessageBack(fileMessage.Sender, "                              File Sent!\n");
         }
     }
     catch (Exception ex)
     {
         AppendText(RTBRoom, Color.Blue, ex.Message.ToString());
     }
 }
Example #40
0
        //test Send file
        private void button1_Click_1(object sender, EventArgs e)
        {
            Stream strm = null;
            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Multiselect = false;
                fileDialog.ShowDialog();
                strm = fileDialog.OpenFile();
                if (strm != null)
                {
                    byte[] buffer = new byte[(int)strm.Length];
                    int i = strm.Read(buffer, 0, buffer.Length);
                    if (i > 0)
                    {
                        var fileMessage = new FileMessage();
                        fileMessage.Sender = txtusername.Text;
                        fileMessage.FileName = fileDialog.SafeFileName;
                        fileMessage.Data = buffer;
                        fileMessage.Time = DateTime.Now;
                        AppendText(RTBPrivate, Color.Blue, "\n                              Sending File....\n");
                        AppendText(RTBRoom, Color.Blue, "\n                              Sending File....\n");
                        proxy.SendFile(fileMessage, _toUser);
                    }
                }

            }
            catch (Exception ex)
            {
                AppendText(RTBPrivate, Color.Blue, ex.Message.ToString());
                AppendText(RTBRoom, Color.Blue, ex.Message.ToString());
            }
            finally
            {
                if (strm != null)
                {
                    strm.Close();
                }
            }
        }
Example #41
0
 public TransferFileUtil(FileMessage fm, FileTransferGrid fileTransferGrid)
 {
     this.fm = fm;
     this.fileTransferGrid = fileTransferGrid;
 }
Example #42
0
        public FileTransferGrid(bool isSend,FileMessage fm)
        {


            this.fm = fm;
            RowDefinition row1 = new RowDefinition();
            row1.Height = new GridLength(20); 
            RowDefinition row2 = new RowDefinition();
            row2.Height = new GridLength(20); 
            RowDefinition row3 = new RowDefinition();
            row3.Height = new GridLength(20);
            this.RowDefinitions.Add(row1);
            this.RowDefinitions.Add(row2);
            this.RowDefinitions.Add(row3);


            ColumnDefinition column1 = new ColumnDefinition();
            column1.Width = new GridLength(200);
            ColumnDefinition column2 = new ColumnDefinition();
            column2.Width = new GridLength(100);
            ColumnDefinition column3 = new ColumnDefinition();
            column3.Width = new GridLength(100);
              ColumnDefinition column4 = new ColumnDefinition();
            column4.Width = new GridLength(100);
            this.ColumnDefinitions.Add(column1);
            this.ColumnDefinitions.Add(column2);
            this.ColumnDefinitions.Add(column3);
            this.ColumnDefinitions.Add(column4);


            file = new TextBlock();
            file.Text = fm.FileName;
            file.Margin = new Thickness(20,0,0,0);
            Grid.SetRow(file,1);
            Grid.SetColumn(file,0);
            this.Children.Add(file);


            bar = new ProgressBar();
            bar.Maximum = 100;
            bar.Margin=new Thickness(10,0,10,0);
            bar.Height = 10;
            Grid.SetRow(bar, 1);
            Grid.SetColumn(bar, 1);
            this.Children.Add(bar);


            tb = new TextBlock();
            Grid.SetRow(tb, 2);
            Grid.SetColumn(tb, 1);
            this.Children.Add(tb);
           
            saveAsBtn = new TextBlock();
            saveAsBtn.Background = new SolidColorBrush(Colors.Transparent);
            saveAsBtn.Text = "另存为";
            saveAsBtn.TextAlignment = TextAlignment.Center;

             saveBorder = new Border();
            saveBorder.BorderThickness = new Thickness(1);
            saveBorder.BorderBrush = new SolidColorBrush(Colors.Black);
            saveBorder.CornerRadius = new CornerRadius(10, 10, 10, 10);
            saveBorder.Background = new SolidColorBrush(Colors.White);
            saveBorder.Child = saveAsBtn;
            saveBorder.Width = 60;
            saveBorder.MouseLeftButtonDown += saveBorder_MouseLeftButtonDown;
           
           cancleBtn = new TextBlock();
          
            cancleBtn.Background = new SolidColorBrush(Colors.Transparent);
            cancleBtn.TextAlignment = TextAlignment.Center;


            Border cancleBorder = new Border();
            cancleBorder.CornerRadius = new CornerRadius(10, 10, 10, 10);
            cancleBorder.Background = new SolidColorBrush(Colors.White);
            cancleBorder.BorderBrush = new SolidColorBrush(Colors.Black);
            cancleBorder.BorderThickness = new Thickness(1);
            cancleBorder.Child = cancleBtn;
            cancleBtn.MouseLeftButtonDown += cancleBtn_MouseLeftButtonDown;
            cancleBorder.Width = 60;

            if (isSend)
            {
                cancleBtn.Text = "取消";
                Grid.SetRow(cancleBorder, 1);
                Grid.SetColumn(cancleBorder, 2);
                this.Children.Add(cancleBorder);

                this.Loaded += FileTransferGrid_Loaded;
                

            }

            else
            {
                cancleBtn.Text = "拒绝";
                Grid.SetRow(saveBorder, 1);
                Grid.SetColumn(saveBorder, 2);
                this.Children.Add(saveBorder);

                Grid.SetRow(cancleBorder, 1);
                Grid.SetColumn(cancleBorder, 3);
                this.Children.Add(cancleBorder);
            }
        }
Example #43
0
        private void chatButtonSendFile_Click(object sender, RoutedEventArgs e)
        {
            if (this.receiver != null)
            {
                Stream strm = null;
                try
                {
                    OpenFileDialog fileDialog = new OpenFileDialog();
                    fileDialog.Multiselect = false;

                    if (fileDialog.ShowDialog() == DialogResult.HasValue)
                    {
                        return;
                    }

                    strm = fileDialog.OpenFile();
                    if (strm != null)
                    {
                        byte[] buffer = new byte[(int)strm.Length];

                        int i = strm.Read(buffer, 0, buffer.Length);

                        if (i > 0)
                        {
                            SVC.FileMessage fMsg = new FileMessage();
                            fMsg.FileName = fileDialog.SafeFileName;
                            fMsg.Sender = this.localClient.Name;
                            fMsg.Data = buffer;
                            proxy.SendFileAsync(fMsg, this.receiver);
                            proxy.SendFileCompleted += new EventHandler<SendFileCompletedEventArgs>(proxy_SendFileCompleted);
                            chatLabelSendFileStatus.Content = "Sending...";
                        }

                    }
                }
                catch (Exception ex)
                {
                    chatTxtBoxType.Text = ex.Message.ToString();
                }
                finally
                {
                    if (strm != null)
                    {
                        strm.Close();
                    }
                }
            }

        }
Example #44
0
 public ReceiveFileUtil(FileMessage fm, UI.FileTransferGrid fileTransferGrid)
     : base(fm, fileTransferGrid)
 {
 }
 public IAsyncResult BeginReceiverFile(FileMessage fileMessage, string receiver, AsyncCallback callback, object asyncState)
 {
     throw new NotImplementedException();
 }
Example #46
0
	string FileMessageRichText (FileMessage message)
	{
		return "<color=#" + SendBirdTheme.ToHex (uiTheme.senderColor) + ">" + message.Sender.Nickname + ": </color>" + message.Name;
	}