Example #1
0
        private static void TestNdsRomRead(string romPath, string filePath, string outPath)
        {
            DataStream romStream = new DataStream(romPath, FileMode.Open, FileAccess.Read);
            Format     romFormat = FileManager.GetFormat("Rom");

            GameFolder main = new GameFolder("main");
            GameFile   rom  = new GameFile(Path.GetFileName(romPath), romStream, romFormat);

            main.AddFile(rom);
            romFormat.Initialize(rom);

            XDocument xmlGame = new XDocument();                // TODO: Replace with ExampleGame.xml

            xmlGame.Add(new XElement("GameInfo", new XElement("Files")));
            FileManager.Initialize(main, FileInfoCollection.FromXml(xmlGame));

            GameFile file = FileManager.GetInstance().RescueFile(filePath);

            if (file != null)
            {
                file.Stream.WriteTo(outPath);
            }

            romStream.Dispose();
        }
        async public static Task <FileInfoCollection> GetFileList()
        {
            FileInfoCollection fileInfos = new FileInfoCollection();

            try
            {
                DataTable table = await MySqlDB.GetDataTableAsync(conStr : _conStr, query : SELECT_FILE_LIST).ConfigureAwait(false);

                if (table.Rows.Count > 0)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        uint   id       = ConvertUtil.StringToUint(row[ColumnNames.ID].ToString());
                        string fileName = row[ColumnNames.NAME].ToString();
                        string fileType = row[ColumnNames.TYPE].ToString();

                        fileInfos.Add(new FileInfo(id: id, fileName: fileName, fileType: fileType));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(fileInfos);
        }
Example #3
0
 void UpdateGrid(FileInfoCollection fileInfos)
 {
     this.Dispatcher.Invoke(() =>
     {
         gridFileList.ItemsSource = fileInfos;
     });
 }
Example #4
0
        private void InitializeFileTypes(FileContainer root, XDocument xmlGame)
        {
            FileInfoCollection fileInfo = FileInfoCollection.FromXml(xmlGame);

            // Add the parameters to each file format.
            // They can be used to add specific properties of the project to the formats parsers.
            // E.g.: to pass the key of the GoogleSpreadsheets to parse.
            foreach (XElement fileEdit in edit.Root.Element("Files").Elements("File"))
            {
                // In order to set parameters the type must be defined in the XML. Otherwise it will defined in run-time
                string filePath = fileEdit.Element("Path").Value;
                if (!fileInfo.Contains(filePath))
                {
                    continue;
                }

                FileInfo info = fileInfo[filePath];
                if (info.Parameters == null)
                {
                    info.Parameters = fileEdit.Element("Parameters");
                }
                else
                {
                    info.Parameters.Add(fileEdit.Element("Parameters")?.Elements());
                }
            }

            FileManager.Initialize(root, fileInfo);
        }
Example #5
0
        private static void TestNinokuniExportImport(string romPath, string filePath)
        {
            DataStream romStream      = new DataStream(romPath, FileMode.Open, FileAccess.Read);
            Format     romFormat      = FileManager.GetFormat("Rom");
            Format     subtitleFormat = FileManager.GetFormat("Subtitle");

            GameFile rom = new GameFile(Path.GetFileName(romPath), romStream, romFormat);

            romFormat.Initialize(rom);

            XDocument xmlGame = XDocument.Load(Path.Combine(AppPath, "ExampleGame.xml"));
            XDocument xmlEdit = XDocument.Load(Path.Combine(AppPath, "ExampleEdition.xml"));

            FileManager.Initialize(rom, FileInfoCollection.FromXml(xmlGame));
            Configuration.Initialize(xmlEdit);

            GameFile file = FileManager.GetInstance().RescueFile(filePath);

            subtitleFormat.Initialize(file);
            file.Format.Read();
            file.Format.Import("/home/benito/Dropbox/Ninokuni español/Texto/Subs peli/s01.xml");
            file.Format.Write();

            romFormat.Write();
            rom.Stream.WriteTo("/lab/nds/projects/generic/test.nds");
            romStream.Dispose();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            FileInfoCollection Fileinfocollection = new FileInfoCollection();

            this.TreeGridColumnTemplate.DataSource = Fileinfocollection.GetFileInfoCollections();
            this.TreeGridColumnTemplate.DataBind();
        }
Example #7
0
        public void FileInfoCollection_AddRange_md5sum()
        {
            FileInfoCollection files = new FileInfoCollection();

            files.AddRange((new DirectoryInfo(@"Test File\")).GetFiles());
            files.WaitMd5();

            Assert.AreEqual("2AAAD2B38E77F4F0E2045CD118116F80", files[0].md5sum());
        }
Example #8
0
        async private void BtnGetFileInfo_Click(object sender, RoutedEventArgs e)
        {
            PacketValue packet = new PacketValue(protocol: Protocols.GET_FILE_LIST, value: 1);

            PacketSerialized result = await this.client.Send(packet).ConfigureAwait(false) as PacketSerialized;

            FileInfoCollection fileInfos = (FileInfoCollection)StreamUtil.DeserializeObject(result.SerializedData);

            UpdateGrid(fileInfos: fileInfos);
        }
Example #9
0
        public void FileInfoCollection_Add_md5sum()
        {
            FileInfoCollection files = new FileInfoCollection();

            files.Add(new FileInfo(@"Test File\md5sum Test document.txt"));
            files.Add(new FileInfo(@"Test File\md5sum Test document2.txt"));
            files.WaitMd5();

            Assert.AreEqual("2AAAD2B38E77F4F0E2045CD118116F80", files[0].md5sum());
            Assert.AreEqual("2AAAD2B38E77F4F0E2045CD118116F80", files[1].md5sum());
        }
Example #10
0
        public Transaction(string HashPassword)
        {
            this.CTS = new CancellationTokenSource();
            this.HashingPass = HashPassword;
            this.TransferredData_Path = Path.Combine(Environment.CurrentDirectory, "TransferredData.DAT");
            this.DetectedData_Path = Path.Combine(Environment.CurrentDirectory, "DetectedData.DAT");

            TransformPhysicalDisk.Reporter += (source, e) => Transaction.Reporter(source, e);
            TransformPhysicalDisk.ProgressChanged += (source, e) => Transaction.ProgressChanged(source, e);
            //
            #region Transferred Files Initialization
            //
            TransferredFiles = new FileInformationCollection();

            string _Tdata = TransformPhysicalDisk.SecureDataReaderAsync(TransferredData_Path, HashingPass).Result;
            List<FileInformation> ResourcesTransferredFiles = null;

            if (!string.IsNullOrEmpty(_Tdata))
            { ResourcesTransferredFiles = FileInformationCollection.Parse(_Tdata); }

            if (ResourcesTransferredFiles != null && ResourcesTransferredFiles.Count > 0)
            { TransferredFiles.PushRange(ResourcesTransferredFiles); }
            else
            {
                //
                // These files exist in mostly common windows systems, so filtered by app's.
                //
                TransferredFiles.Push(new FileInformation("Chrysanthemum.jpg", 879394));
                TransferredFiles.Push(new FileInformation("Desert.jpg", 845941));
                TransferredFiles.Push(new FileInformation("Hydrangeas.jpg", 595284));
                TransferredFiles.Push(new FileInformation("Jellyfish.jpg", 775702));
                TransferredFiles.Push(new FileInformation("Koala.jpg", 780831));
                TransferredFiles.Push(new FileInformation("Lighthouse.jpg", 561276));
                TransferredFiles.Push(new FileInformation("Penguins.jpg", 777835));
                TransferredFiles.Push(new FileInformation("Tulips.jpg", 620888));
            }
            //
            #endregion
            //
            #region Detected Files Initialization
            //
            DetectedFiles = new FileInfoCollection();
            string _Ddata = TransformPhysicalDisk.SecureDataReaderAsync(DetectedData_Path, HashingPass).Result;
            List<FileInfo> ResourcesDetectedFiles = null;

            if (!string.IsNullOrEmpty(_Ddata))
            { ResourcesDetectedFiles = FileInfoCollection.Parse(_Ddata); }

            if (ResourcesDetectedFiles != null && ResourcesDetectedFiles.Count > 0)
                DetectedFiles.PushRange(ResourcesDetectedFiles);
            //
            #endregion
            //
        }
        public void WriteToFile(FileInfoCollection fileInfoCollection, Dictionary<string, string> translations, string entryKey, TranslatorForm form)
        {
            resourceEntries = new Hashtable(translations);

                foreach (var fileInfo in fileInfoCollection.FilesInfo)
                    foreach (KeyValuePair<string, string> translation in translations)
                        if (fileInfo.Name.ToLower().Contains(translation.Key.ToLower()))
                        {
                            resourceEntries = new Hashtable() {{entryKey, translation.Value}};
                            Helper.UpdateResourceFile(resourceEntries, fileInfo.FullName, form);
                        }
        }
        async static Task <PacketSerialized> UploadFile(PacketFile packet)
        {
            FileManager.SetFileToWaitingPath(fileName: packet.Desc, fileData: packet.FileData);

            string fileName = Path.GetFileNameWithoutExtension(packet.Desc);
            string fileType = Path.GetExtension(packet.Desc);
            bool   result   = await DatabaseManager.AddFile(fileName : fileName, fileType : fileType);

            FileInfoCollection files = await DatabaseManager.GetFileList();

            return(new PacketSerialized(protocol: packet.Protocol, serializedData: StreamUtil.SerializeObject(files)));
        }
Example #13
0
        /// <summary>
        /// Refreshes the local list view.
        /// </summary>
        public void RefreshLocalList()
        {
            try
            {
                DirectoryInfo      directory = new DirectoryInfo(_currentLocalDirectory);
                FileInfoCollection list      = DiskFileSystem.Default.ListDirectory(directory.FullName);

                ListFiles(list, directory.FullName.Length <= 3, true);
            }
            catch (Exception exc)
            {
                _view.ShowError(exc);
                return;
            }
        }
Example #14
0
        async private void BtnAddFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() == true)
            {
                byte[]           data    = File.ReadAllBytes(openFileDialog.FileName);
                PacketFile       request = new PacketFile(protocol: Protocols.UPLOAD_FILE, desc: Path.GetFileName(openFileDialog.FileName), fileData: data);
                PacketSerialized result  = await this.client.Send(sendPacket : request).ConfigureAwait(false) as PacketSerialized;

                FileInfoCollection fileInfos = (FileInfoCollection)StreamUtil.DeserializeObject(result.SerializedData);

                MessageBox.Show("Upload를 완료했습니다.");

                UpdateGrid(fileInfos: fileInfos);
            }
        }
            internal static void Start(DriveInfo TargetDrive, FileInfoCollection DetectedList,
                FileInformationCollection TransferredList, string HashPassword,
                string Transferred_DAT_Path, string Detected_DAT_Path)
            {
                #region Set Variable Values
                //
                CTS = new CancellationTokenSource();
                MassStorage = TargetDrive;
                DetectedFiles = DetectedList;
                TransferredFiles = TransferredList;
                //
                #region ZipEncryption Initialization
                ZipE = new Zipper.ZipEncryption(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), HashPassword);
                ZipE.ReportOccurrence += (source, e) => Reporter(source, e);
                ZipE.SaveProgress += (source, e) => ProgressChanged(source, e);
                #endregion
                #endregion
                //
                TransferAsyncAwaiter = TransferAsync(HashPassword).ContinueWith(async (setter) =>
                    {
                        //
                        // Reports TransferAsync Task Exceptions...
                        //
                        await Task.Run(() =>
                        {
                            AggregateException AExps = setter.Exception;

                            if (AExps != null)
                            {
                                foreach (var exp in AExps.InnerExceptions)
                                {
                                    Reporter("TransferToDisk", new ReportEventArgs("TransformPhysicalDisk.TransferAsync", exp));
                                }
                            }
                        });
                        //
                        // Save Files
                        //
                        await SecureDataSaverAsync(DetectedFiles.ToString(), Detected_DAT_Path, HashPassword);

                        await SecureDataSaverAsync(TransferredFiles.ToString(), Transferred_DAT_Path, HashPassword);
                    });

                Task.WaitAll(TransferAsyncAwaiter);
            }
        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker pkr = new FileOpenPicker();

            pkr.FileTypeFilter.Add("*");
            StorageFile file = await pkr.PickSingleFileAsync();

            var loader = new Windows.ApplicationModel.Resources.ResourceLoader();


            FileInfo test = new FileInfo()
            {
                Name = file.Name, DateCreated = file.DateCreated, Path = file.Path, IsAvailable = (file.IsAvailable) ? loader.GetString("True") : loader.GetString("False")
            };
            FileInfoCollection test2 = new FileInfoCollection();

            test2.Items = new System.Collections.ObjectModel.ObservableCollection <FileInfo>();
            test2.Items.Add(test);

            MainSection.DataContext = test2;
        }
Example #17
0
        private void Download(IAsyncResult iar)
        {
            try
            {
                client.EndConnect(iar);
            }
            catch (SocketException)
            {
            #region load Server
                IPEndPoint remoteendpoint = (IPEndPoint)iar.AsyncState;
                time.Stop();//停止计时
                try
                {
                    if (LoadServer(remoteendpoint))
                    {
                        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        time.Start();//开始计时
                        client.BeginConnect(remoteendpoint, new AsyncCallback(Download), client);
                    }
                    else
                    {
                        SetControlText(labelInfo, labelCanNotConnect.Text);//
                        SetState(State.Idle);
                    }
                    return;
                }
                catch (ObjectDisposedException)
                {
                    SetControlText(labelInfo, labelUpdateCancel.Text);
                    SetState(State.Idle);
                    time.Stop();
                    return;
                }
                #endregion
            }
            catch (ObjectDisposedException)
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
                SetState(State.Idle);
                time.Stop();
                return;
            }
            time.Stop();//停止计时

            FileInfoCollection fc = new FileInfoCollection();
            if (true)//是否只更新有修改过的文件
            {
                try
                {
                    fc.Load(Config.WorkPath);
                    if (File.Exists("Resume.xml"))                      //存在续传记录
                    {
                        if (MessageBox.Show(this, labelResume.Text, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            XmlDocument xmlresume = new XmlDocument();
                            try
                            {
                                xmlresume.Load("Resume.xml");
                                XmlNode noderesume = xmlresume.SelectSingleNode("Resume/FileResume");
                                int id = Convert.ToInt32(noderesume.Attributes["ID"].Value);
                                DateTime date = Convert.ToDateTime(noderesume.Attributes["Date"].Value);
                                int length = Convert.ToInt32(noderesume.Attributes["Length"].Value);
                                int offset = Convert.ToInt32(noderesume.Attributes["Offset"].Value);
                                fc.SetFiletoResumeInfo(id, date, length, offset);
                            }
                            catch
                            { }
                        }
                        else//清空临时文件夹
                        {
                            Directory.Delete("temp", true);
                            Directory.CreateDirectory("temp");
                        }
                    }
                }
                catch
                {
                    fc.Clear();
                }
                File.Delete("Resume.xml");
            }

            time.Start();//开启计时
            byte[] xml = fc.SaveToBuffer();

            MessageBuffer buf = new MessageBuffer(MessageType.RequeryFile, 0, 0, xml.Length);
            FileStream fs = null;
            buf.SetFileBytes(xml);

            int fileid = 0; //记录当前下载的文件ID
            int fileoffset = 0;//记录当前下载的文件偏移量
            try
            {
                client.Send(buf.GetBytes());//发送已经存在文件列表
                SetControlText(labelInfo, labelDownloadingList.Text);

                int filelength = 0;//记录所有文件的大小
                int filelengthfinished = 0; //记录已经完成的文件的大小

                byte[] btbufundecoded = new byte[0];//存放上次未处理的娄组

                while (true)
                {
                    byte[] bufmax = new byte[Config.MAX_LENGTH];//存放接收到的数组
                    int length = client.Receive(bufmax);//接收数据
                    time.Restart();//重启计时
                    //重写算法
                    byte[] btbuf = new byte[length + btbufundecoded.Length];//存放接收到及未处理的数组
                    if (btbufundecoded.Length > 0)
                    {
                        Buffer.BlockCopy(btbufundecoded, 0, btbuf, 0, btbufundecoded.Length);//将未完成的字节加入队列的开始
                    }
                    Buffer.BlockCopy(bufmax, 0, btbuf, btbufundecoded.Length, length);//加入接收到的字节
                    int bufindex = 0;
                    bool iscompleted = true;
                    while (bufindex < btbuf.Length) //全部处理完也要跳出循环
                    {
                        btbufundecoded = new byte[0];//清空
                        byte[] btmb = new byte[btbuf.Length - bufindex];
                        Buffer.BlockCopy(btbuf, bufindex, btmb, 0, btmb.Length);//将已经处理完的字节移出
                        MessageBuffer mb = new MessageBuffer(btmb);

                        iscompleted = mb.Completed;//判断这个Message是否完整
                        if (!mb.Completed)//是否完整
                        {
                            btbufundecoded = btmb;
                            break;//跳出循环,未处理的在下次接收后一同处理
                        }
                        else
                        {
                            bufindex += mb.FileLength + 13;//修改已经处理的位置
                            switch (mb.Header)
                            {
                                case MessageType.SendFileList:
                                    Config.LocalFiles.Load(mb.GetFileBytes());
                                    filelength = Config.LocalFiles.Length;
                                    break;
                                case MessageType.SendFile:
                                    {
                                        if (fileid != mb.FileID)    //新文件
                                        {
                                            fileid = mb.FileID;
                                            fileoffset = mb.FileOffSet;

                                            if (fs != null)
                                            {
                                                fs.Close();//写回到文件
                                            }
                                            fs = new FileStream(string.Format("temp\\{0}.tmp", fileid), FileMode.OpenOrCreate);
                                            SetControlText(labelInfo, labelDownloading.Text + Config.LocalFiles[fileid].ToString());
                                        }

                                        fs.Position = mb.FileOffSet;
                                        fs.Write(mb.GetFileBytes(), 0, mb.FileLength);//写入到流
                                        fileoffset += mb.FileLength;
                                        filelengthfinished += mb.FileLength;

                                        SetProgressBarValue(progressBarDetail, (int)((double)fileoffset / (double)Config.LocalFiles[fileid].Length * 100));
                                        SetProgressBarValue(progressBarTotal, (int)((double)filelengthfinished / (double)filelength * 100));
                                        //刷新进度条

                                        if (fileoffset == Config.LocalFiles[fileid].Length)//完成这个文件
                                        {
                                            fs.Close();//从流写回到文件
                                            fs = null;
                                            string filename = Config.WorkPath + Config.LocalFiles[fileid].ToString();
                                            if (!Directory.Exists(Path.GetDirectoryName(filename)))//创建目的文件夹
                                            {
                                                Directory.CreateDirectory(Path.GetDirectoryName(filename));
                                            }

                                            if (File.Exists(filename))//如果文件存在则删除
                                            {
                                                File.Delete(filename);
                                            }
                                            File.Move(string.Format("temp\\{0}.tmp", mb.FileID), filename);//移动文件到目的文件夹
                                            File.SetLastWriteTime(filename, Config.LocalFiles[fileid].Date);//设置最后修改时间

                                            Config.LocalFiles.Remove(fileid);
                                        }
                                        break;
                                    }
                                case MessageType.SendFinished:
                                    if (true)
                                    {
                                        client.Send(MessageBuffer.ReceiveFinished.GetBytes());
                                    }
                                    else// 用来申请某个文件中的一部分,可能用不到
                                    {
                                        //MessageBuffer mbreqblock = new MessageBuffer(MessageType.RequeryBlock, "id", "offset", "length");
                                        //client.Send(mbreqblock.GetBytes());
                                    }
                                    if (filelength == 0)
                                    {
                                        SetControlText(labelInfo, labelNoUpdateFound.Text);
                                    }
                                    else
                                    {
                                        SetControlText(labelInfo, labelUpdateFinished.Text);
                                    }
                                    SetProgressBarValue(progressBarDetail, 100);
                                    SetProgressBarValue(progressBarTotal, 100);
                                    client.Shutdown(SocketShutdown.Both);
                                    client.Close(100);
                                    if (true)
                                    {
                                        if (File.Exists(Config.WorkPath + "\\" + Config.PreInstall) && !Config.CheckPreInstall())
                                        {
                                            try
                                            {
                                                System.Diagnostics.Process pro = System.Diagnostics.Process.Start(Config.WorkPath + "\\" + Config.PreInstall);
                                                pro.WaitForInputIdle();
                                            }
                                            catch { }
                                        }
                                        try
                                        {
                                            if (CurrentSolution != null)
                                            {
                                                XmlDocument clientxml = CreateClientXml(CurrentSolution);
                                                clientxml.Save(Config.WorkPath + @"\EEPNetClient.xml");
                                            }
                                        }
                                        catch(Exception e)
                                        {
                                            SetMessageBox(e.Message);
                                        }
                                        try
                                        {
                                            String S = CurrentSolution.Language.ToString() + " " + CurrentSolution.IP +
                                                " " + CurrentSolution.ApPort.ToString();
                                            System.Diagnostics.Process pro
                                                = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Config.WorkPath + "\\" + Config.LaunchPath, S));
                                            pro.WaitForInputIdle();
                                            SetState(State.Idle);
                                            //Application.Exit();
                                        }
                                        catch(Exception e)
                                        {
                                            SetMessageBox(e.Message);
                                        }
                                    }
                                    return;
                            }
                        }
                    }
                }
            }
            catch (Exception e)//有些文件在copy时会有权限问题,还查不出
            {
                if (client.Connected)
                {
                    client.Send(MessageBuffer.ReceiveFinished.GetBytes());
                }
                if (buttonStart.Text == labelStart.Text)
                {
                    SetControlText(labelInfo, labelUpdateCancel.Text);
                    if (fileid != 0 && fileoffset != Config.LocalFiles[fileid].Length)//当前文件未完成
                    {
                        //存入文件
                        XmlDocument xmlresume = new XmlDocument();
                        XmlNode nodedoc = xmlresume.CreateElement("Resume");
                        xmlresume.AppendChild(nodedoc);
                        XmlNode nodefileresume = xmlresume.CreateElement("FileResume");
                        XmlAttribute att = xmlresume.CreateAttribute("ID");
                        att.Value = fileid.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Offset");
                        att.Value = fileoffset.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Date");
                        att.Value = Config.LocalFiles[fileid].Date.ToString();
                        nodefileresume.Attributes.Append(att);
                        att = xmlresume.CreateAttribute("Length");
                        att.Value = Config.LocalFiles[fileid].Length.ToString();
                        nodefileresume.Attributes.Append(att);

                        nodedoc.AppendChild(nodefileresume);
                        xmlresume.Save("Resume.xml");//记录续传文件的信息
                    }
                }
                else
                {
                    SetControlText(labelInfo, string.Empty);
                    SetMessageBox(e.Message);
                }
                SetState(State.Idle);
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                //if (!this.Disposing)
                //{
                //    SetState(State.Idle);
                //}
                client.Close();
                time.Stop();
            }
        }
Example #18
0
        private void DownLoad(object uri)
        {
            IPEndPoint iep = (IPEndPoint)uri;
            LoaderObject loader = (LoaderObject)Activator.GetObject(typeof(LoaderObject), string.Format("http://{0}/LoaderObject.rem", uri));
            int fileid = 0; //记录当前下载的文件ID
            int fileoffset = 0;//记录当前下载的文件偏移量
            try
            {
                FileInfoCollection fc = new FileInfoCollection();
                try
                {
                    fc.Load(Config.WorkPath);
                    if (File.Exists("Resume.xml"))                      //存在续传记录
                    {
                        if (MessageBox.Show(this, labelResume.Text, "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            XmlDocument xmlresume = new XmlDocument();
                            try
                            {
                                xmlresume.Load("Resume.xml");
                                XmlNode noderesume = xmlresume.SelectSingleNode("Resume/FileResume");
                                int id = Convert.ToInt32(noderesume.Attributes["ID"].Value);
                                DateTime date = Convert.ToDateTime(noderesume.Attributes["Date"].Value);
                                int length = Convert.ToInt32(noderesume.Attributes["Length"].Value);
                                int offset = Convert.ToInt32(noderesume.Attributes["Offset"].Value);
                                fc.SetFiletoResumeInfo(id, date, length, offset);
                            }
                            catch
                            { }
                        }
                        else//清空临时文件夹
                        {
                            Directory.Delete("temp", true);
                            Directory.CreateDirectory("temp");
                            File.Delete("Resume.xml");
                        }
                    }
                }
                catch
                {
                    fc.Clear();
                }
                SetControlText(labelInfo, labelDownloadingList.Text);
                byte[] bt = loader.GetDownLoadList(fc.SaveToBuffer());
                if (bt != null)
                {
                    Config.LocalFiles.Load(bt);
                }
                byte[] btimage = loader.GetClientImage(ImageType.Client);
                if (btimage != null)
                {
                    try
                    {
                        if (!Directory.Exists(Config.WorkPath))
                        {
                            Directory.CreateDirectory(Config.WorkPath);
                        }
                        using (FileStream fs = new FileStream(string.Format("{0}\\EEPNetClient.jpg", Config.WorkPath), FileMode.OpenOrCreate))
                        {
                            fs.Write(btimage, 0, btimage.Length);
                        }
                    }
                    catch { }
                }
                btimage = loader.GetClientImage(ImageType.ClientMain);
                if (btimage != null)
                {
                    try
                    {
                        if (!Directory.Exists(Config.WorkPath))
                        {
                            Directory.CreateDirectory(Config.WorkPath);
                        }
                        using (FileStream fs = new FileStream(string.Format("{0}\\EEPNetClientMain.jpg", Config.WorkPath), FileMode.OpenOrCreate))
                        {
                            fs.Write(btimage, 0, btimage.Length);
                        }
                    }
                    catch { }
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ConnectFailure)
                {
                    if (LoadServer(iep))
                    {
                        Thread.Sleep(1000);
                        DownLoad(uri);
                        return;
                    }
                    else
                    {
                        SetControlText(labelInfo, labelCanNotConnect.Text);
                    }
                }
                else
                {
                    SetMessageBox(e.Message);
                }
                SetState(State.Idle);
                return;
            }
            catch (ThreadAbortException)
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
                return;
            }
            catch (Exception e)
            {
                SetMessageBox(e.Message);
                SetState(State.Idle);
                return;
            }
            try
            {
                File.Delete("Resume.xml");
                System.Collections.IEnumerator ie = Config.LocalFiles.GetEnumerator();
                int filelength = Config.LocalFiles.Length;
                int filelengthfinished = 0;
                if(filelength > 0)
                {
                    while (ie.MoveNext())
                    {
                        FileInfo fi = ((DictionaryEntry)ie.Current).Value as FileInfo;
                        SetControlText(labelInfo, labelDownloading.Text + fi.ToString());
                        using (FileStream fs = new FileStream(string.Format("temp\\{0}.tmp", fi.ID), FileMode.OpenOrCreate))
                        {
                            fileid = fi.ID;
                            int length = fi.Length;
                            int i = 0;
                            if (Config.LocalFiles.FileResume != null && Config.LocalFiles.FileResume.ID == fi.ID)
                            {
                                i = Config.LocalFiles.FileOffSet;//续传文件从续传位置开始
                            }
                            for (; i < length; i += Config.FILE_BLOCK_LENGTH)
                            {
                                int len = Math.Min(Config.FILE_BLOCK_LENGTH, length - i);
                                byte[] btfile = loader.GetFile(fi.ID, i, len);
                                fs.Position = i;
                                fs.Write(btfile, 0, len);
                                fileoffset = i + len;
                                filelengthfinished += len;

                                SetProgressBarValue(progressBarDetail, (int)((double)(i + len) / (double)fi.Length * 100));
                                SetProgressBarValue(progressBarTotal, (int)((double)filelengthfinished / (double)filelength * 100));
                            }
                        }
                        string filename = Config.WorkPath + fi.ToString();
                        if (!Directory.Exists(Path.GetDirectoryName(filename)))//创建目的文件夹
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(filename));
                        }
                        if (File.Exists(filename))//如果文件存在则删除
                        {
                            File.Delete(filename);
                        }
                        File.Move(string.Format("temp\\{0}.tmp", fi.ID), filename);//移动文件到目的文件夹
                        File.SetLastWriteTime(filename, fi.Date);//设置最后修改时间
                    }
                    SetControlText(labelInfo, labelUpdateFinished.Text);
                }
                else
                {
                    SetControlText(labelInfo, labelNoUpdateFound.Text);
                }
                SetProgressBarValue(progressBarDetail, 100);
                SetProgressBarValue(progressBarTotal, 100);
                if (File.Exists(Config.WorkPath + "\\" + Config.PreInstall) && !Config.CheckPreInstall())
                {
                    try
                    {
                        System.Diagnostics.Process pro = System.Diagnostics.Process.Start(Config.WorkPath + "\\" + Config.PreInstall);
                        pro.WaitForInputIdle();
                    }
                    catch { }
                }
                try
                {
                    if (CurrentSolution != null)
                    {
                        XmlDocument clientxml = CreateClientXml(CurrentSolution);
                        clientxml.Save(Config.WorkPath + @"\EEPNetClient.xml");
                    }
                }
                catch
                {
                    SetMessageBox("Can not Refresh client xml, check it's property not be readonly.");
                }
                try
                {
                    String S = string.Format("{0} {1} {2} {3} {4} {5} {6} {7}", CurrentSolution.Language, CurrentSolution.IP, CurrentSolution.ApPort
                    , CurrentSolution.Text, ProxySetting.Default.ProxyEnable,
                    string.Format("{0}:{1}", ProxySetting.Default.ProxyAddress, ProxySetting.Default.ProxyPort)
                    , ProxySetting.Default.ProxyUser, ProxySetting.Default.ProxyPassword);
                    System.Diagnostics.Process pro
                        = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Config.WorkPath + "\\" + Config.LaunchPath, S));
                    pro.WaitForInputIdle();
                    SetState(State.Idle);
                    //Application.Exit();
                    return;
                }
                catch(Exception e)
                {
                    SetMessageBox(e.Message);
                    SetState(State.Idle);
                }

            }
            catch (ThreadAbortException)
            {
                SetControlText(labelInfo, labelUpdateCancel.Text);
                SetState(State.Idle);
            }
            catch (Exception e)
            {
                SetMessageBox(e.Message);
                SetState(State.Idle);
            }
            finally
            {
                if (fileid != 0 && fileoffset != Config.LocalFiles[fileid].Length)//当前文件未完成
                {
                    //存入文件
                    XmlDocument xmlresume = new XmlDocument();
                    XmlNode nodedoc = xmlresume.CreateElement("Resume");
                    xmlresume.AppendChild(nodedoc);
                    XmlNode nodefileresume = xmlresume.CreateElement("FileResume");
                    XmlAttribute att = xmlresume.CreateAttribute("ID");
                    att.Value = fileid.ToString();
                    nodefileresume.Attributes.Append(att);
                    att = xmlresume.CreateAttribute("Offset");
                    att.Value = fileoffset.ToString();
                    nodefileresume.Attributes.Append(att);
                    att = xmlresume.CreateAttribute("Date");
                    att.Value = Config.LocalFiles[fileid].Date.ToString();
                    nodefileresume.Attributes.Append(att);
                    att = xmlresume.CreateAttribute("Length");
                    att.Value = Config.LocalFiles[fileid].Length.ToString();
                    nodefileresume.Attributes.Append(att);

                    nodedoc.AppendChild(nodefileresume);
                    xmlresume.Save("Resume.xml");//记录续传文件的信息
                }

                //SetState(State.Idle);
            }
        }
Example #19
0
        private ArrayList listthread = new ArrayList(); //记录所有运行的线程

        private void Receive(object param)
        {
            Socket client = param as Socket;
            bool finished = false;
            try
            {
                byte[] btbufundecoded = new byte[0];
                while (!finished)
                {
                    byte[] bufmax = new byte[Config.MAX_LENGTH];
                    int length = client.Receive(bufmax);//接收消息

                    //接收不完整的时候出现问题

                    byte[] btbuf = new byte[length + btbufundecoded.Length];
                    if (btbufundecoded.Length > 0)
                    {
                        Buffer.BlockCopy(btbufundecoded, 0, btbuf, 0, btbufundecoded.Length);//将未完成的字节加入队列的开始
                    }
                    Buffer.BlockCopy(bufmax, 0, btbuf, btbufundecoded.Length, length);//加入接收到的字节
                    MessageBuffer mb = new MessageBuffer(btbuf);
                    if (mb.Completed)
                    {
                        switch (mb.Header)
                        {
                            case MessageType.RequerySolution:
                                {
                                    XmlDocument xmldoc = new XmlDocument();
                                    if (System.IO.File.Exists(Config.SolutionFile))
                                    {
                                        try
                                        {
                                            xmldoc.Load(Config.SolutionFile);
                                        }
                                        catch { }
                                    }
                                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                                    xmldoc.Save(ms);
                                    byte[] xml = ms.ToArray();

                                    MessageBuffer mbsolutionlist = new MessageBuffer(MessageType.SendSolutionList, 0, 0,xml.Length);
                                    mbsolutionlist.SetFileBytes(xml);
                                    client.Send(mbsolutionlist.GetBytes());
                                    finished = true;
                                    break;
                                }

                            case MessageType.RequeryFile:
                                {
                                    UserInfo user = new UserInfo((IPEndPoint)client.RemoteEndPoint);
                                    FileInfoCollection fc = new FileInfoCollection();
                                    fc.Load(mb.GetFileBytes());
                                    user.FilesToDownLoad = Config.LocalFiles.GetDownloadList(fc);
                                    RefreshList(RefreshType.Add, user.ID, user);//增加用户,刷新列表

                                    byte[] xml = user.FilesToDownLoad.SaveToBuffer();
                                    MessageBuffer mbfilelist = new MessageBuffer(MessageType.SendFileList, 0, 0, xml.Length);
                                    mbfilelist.SetFileBytes(xml);
                                    client.Send(mbfilelist.GetBytes());//发送更新列表

                                    user.FilesToDownLoad.Send(client);//发送文件内容
                                    client.Send(MessageBuffer.SendFinished.GetBytes());//发送完毕
                                    break;
                                }
                            case MessageType.RequeryBlock:
                                Config.LocalFiles.Send(client, mb.FileID, mb.FileOffSet, mb.FileLength);//发送文件部分内容
                                break;

                            case MessageType.ReceiveFinished:
                                finished = true;
                                break;
                        }
                    }
                }
            }
            catch (SocketException)//客户端退出或者取消或者超时关闭
            {

            }
            catch//确保服务器稳定
            {
                //记录错误,有心情再做
            }
            finally
            {
                RefreshList(RefreshType.Remove, ((IPEndPoint)client.RemoteEndPoint).ToString().GetHashCode(), null);//移除用户,刷新列表
                client.Close();
            }
        }
Example #20
0
 private bool Save()
 {
     try
     {
         Config.ServerPort = Convert.ToInt32(textBoxPort.Text);
     }
     catch
     {
         MessageBox.Show(this, "The port is not valid ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return false;
     }
     Config.TempWorkPath = textBoxFolder.Text;
     if (pictureBoxClient.ImageLocation != null)
     {
         Config.ClientImagePath = pictureBoxClient.ImageLocation;
     }
     if (pictureBoxClientMain.ImageLocation != null)
     {
         Config.ClientMainImagePath = pictureBoxClientMain.ImageLocation;
     }
     if (pictureBoxClientLoader.ImageLocation != null)
     {
         Config.ClientLoaderImagePath = pictureBoxClientLoader.ImageLocation;
     }
     Config.Save();
     //取得更新文件的集合
     FileInfoCollection fc = new FileInfoCollection();
     GetFileTreeNode(treeViewFiles.Nodes[0],fc);
     Config.TempLocalFiles = fc;
     Config.SaveFiles(fc);
     return true;
 }
Example #21
0
 private void GetFileTreeNode(TreeNode nodeparent, FileInfoCollection fc)
 {
     for (int i = 0; i < nodeparent.Nodes.Count; i++)
     {
         TreeNode node = nodeparent.Nodes[i];
         if (node.Nodes.Count > 0)
         {
             GetFileTreeNode(node, fc);
         }
         else if (node.ImageIndex == 1 && node.Checked)//CheckedFile
         {
             System.IO.FileInfo fi = new System.IO.FileInfo(node.Name);
             FileInfo finew = new FileInfo(fi);
             if (node.Tag != null)
             {
                 finew.OverWritable = (bool)node.Tag;
             }
             fc.Add(finew.ID, finew);
         }
     }
 }
Example #22
0
        private void ListFiles(FileInfoCollection files, bool rootDir, bool local)
        {
            List <ListItemInfo> viewList = new List <ListItemInfo>();
            ListItemInfo        item;

            // Add directories into the list first.
            for (int i = 0; i < files.Count; i++)
            {
                AbstractFileInfo f = files[i];

                if (f.IsDirectory)
                {
                    if (f.Name != "." && f.Name != "..")
                    {
                        item          = new ListItemInfo();
                        item.FileInfo = f;

                        if (!local)
                        {
                            item.Permissions = _clientPlugin.GetPermissionsString(f);
                        }

                        viewList.Add(item);
                    }
                }
                else if (f.IsSymlink) // Add symlinks.
                {
                    item             = new ListItemInfo();
                    item.FileInfo    = f;
                    item.LinkedFile  = _client.GetFileInfo(f.SymlinkPath);
                    item.Permissions = _clientPlugin.GetPermissionsString(f);

                    viewList.Add(item);
                }
                else //Add Files.
                {
                    item          = new ListItemInfo();
                    item.FileInfo = f;
                    if (!local)
                    {
                        item.Permissions = _clientPlugin.GetPermissionsString(f);
                    }

                    viewList.Add(item);
                }
            }

            if (!rootDir)
            {
                // Add Cdup list item.
                item = new ListItemInfo();
                if (local)
                {
                    item.FileInfo = DiskFileSystem.Default.CreateFileInfo("..", FileAttributes.Directory, -1, DateTime.MinValue);
                }
                else
                {
                    item.FileInfo = _client.CreateFileInfo("..", FileAttributes.Directory, -1, DateTime.MinValue);
                }
                viewList.Add(item);
            }

            if (local)
            {
                _view.ListLocalFiles(viewList);
            }
            else
            {
                _view.ListRemoteFiles(viewList);
            }
        }
Example #23
0
 void DoListDirPost(FileInfoCollection files)
 {
     ListFiles(files, _currentDirectory.Length <= 1, false);
 }
 public ResourceTranslator(FileInfoCollection fileInfoCollection, FileInputValidator fileInputValidator)
 {
     _fileInfoCollection = fileInfoCollection;
     _fileInputValidator = fileInputValidator;
 }
        async static Task <PacketSerialized> GetFileList(PacketValue packet)
        {
            FileInfoCollection files = await DatabaseManager.GetFileList();

            return(new PacketSerialized(protocol: packet.Protocol, serializedData: StreamUtil.SerializeObject(files)));
        }