Ejemplo n.º 1
0
 public static void ReadRollbackServices(string fileName, List <string> rollbackList, bool addUnique)
 {
     using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
         if (!ReadFiles.IsHeaderValid(fileStream, "IURUSV1"))
         {
             throw new Exception("Identifier incorrect");
         }
         byte b = (byte)fileStream.ReadByte();
         while (!ReadFiles.ReachedEndByte(fileStream, b, byte.MaxValue))
         {
             byte b2 = b;
             if (b2 == 1)
             {
                 if (addUnique)
                 {
                     ClientFile.AddUniqueString(ReadFiles.ReadString(fileStream), rollbackList);
                 }
                 else
                 {
                     rollbackList.Add(ReadFiles.ReadString(fileStream));
                 }
             }
             else
             {
                 ReadFiles.SkipField(fileStream, b);
             }
             b = (byte)fileStream.ReadByte();
         }
     }
 }
        private ClientFile downloadFile(byte[] data)
        {
            var response = Encoding.ASCII.GetString(data);
            var fileData = response.Split(new char[] { '|' }, 2);

            byte[] fileText;
            if (fileData.Length > 1)
            {
                fileText = Encoding.ASCII.GetBytes(fileData[1]);
            }
            else
            {
                fileText = new byte[0];
            }
            if (File.Exists(startupPath + "\\" + fileData[0]))
            {
                File.Delete(startupPath + "\\" + fileData[0]);
            }
            FileStream fs = new FileStream(startupPath + "\\" + fileData[0], FileMode.Append, FileAccess.Write);

            fs.Write(fileText, 0, fileText.Length);
            ClientFile file = new ClientFile(fileData[0], startupPath + "\\" + fileData[0]);

            fs.Close();
            return(file);
        }
Ejemplo n.º 3
0
        private void BtnRecibir_Click(object sender, System.EventArgs e)
        {
            var txtServidor = FindViewById <TextView>(Resource.Id.edtServidor);
            var txtPort     = FindViewById <TextView>(Resource.Id.edtPuerto);

            Toast.MakeText(this, "IP: " + txtServidor.Text + ", Puerto: " +
                           txtPort.Text, ToastLength.Long).Show();

            try
            {
                var rutaArchivo = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "XMLS");
                Directory.CreateDirectory(rutaArchivo);
                rutaArchivo = Path.Combine(rutaArchivo, "archivo.xml");

                ClientFile clienteTcp = new ClientFile(aPort: int.Parse(txtPort.Text), aServer: txtServidor.Text, aFileName: rutaArchivo);
                clienteTcp.Conectar();
                var edtMensaje = FindViewById <EditText>(Resource.Id.edtMensaje);
                edtMensaje.Text += clienteTcp.EnviarMensajeRecibirArchivo() + "\n";
            }
            catch (Exception ex)
            {
                var edtMensaje = FindViewById <EditText>(Resource.Id.edtMensaje);
                edtMensaje.Text += ex.Message + "\n";
            }
        }
        public void AppendNewFileData(ClientFile clientFile)
        {
            List <ClientFile> files = new List <ClientFile>();
            var path     = System.IO.Directory.GetCurrentDirectory();
            var fileList = GetJson(path, "client-files");

            foreach (var item in JsonConvert.DeserializeObject <List <ClientFile> >(fileList))
            {
                files.Add(item);
                //    new ClientFile()
                //{
                //    ABNNumber = Convert.ToString(item["abnNumber"]),
                //    FileName = Convert.ToString(item["fileName"]),
                //    ClientName = Convert.ToString(item["clientName"]),
                //    FilePath = Convert.ToString(item["filePath"]),
                //    UploadedOn = Convert.ToDateTime(item["uploadedOn"])
                //});
            }
            files.Add(clientFile);

            // Update json data string
            var jsonData = JsonConvert.SerializeObject(files);

            System.IO.File.WriteAllText(string.Format(@"{0}\{1}.json", path, "client-files"), jsonData);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 更新文件
        /// </summary>
        /// <param name="file">文件信息</param>
        /// <param name="root">根目录</param>
        /// <param name="bytes">文件字节流</param>
        /// <returns>bool 是否重命名</returns>
        public static bool UpdateFile(ClientFile file, string root, byte[] bytes)
        {
            var rename = false;
            var path   = root + file.path + "\\";

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

            path += file.name;
            try
            {
                File.Delete(path);
            }
            catch
            {
                File.Move(path, path + ".bak");
                rename = true;
            }

            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                fs.Write(bytes, 0, bytes.Length);
            }
            return(rename);
        }
        private void sendFileToServer(ClientFile clientFile, bool addingFile)
        {
            try
            {
                NetworkStream nws = tcpClient.GetStream();
                FileStream    fs;
                fs = new FileStream(clientFile.path, FileMode.Open, FileAccess.Read);
                byte[] bytesToSend = new byte[fs.Length];
                byte[] package;
                fs.Read(bytesToSend, 0, bytesToSend.Length);
                if (addingFile)
                {
                    package = protocol.makeAddFileRequestHeader(System.Text.Encoding.ASCII.GetString(bytesToSend), clientFile.name);
                }
                else
                {
                    package = protocol.makeReturnUpdatedFileHeader(System.Text.Encoding.ASCII.GetString(bytesToSend), clientFile.name);
                }

                nws.Write(package, 0, package.Length);

                fs.Close();
            }catch (Exception ex)
            {
                throw new ClientException(ex.Message);
            }
        }
Ejemplo n.º 7
0
        public static void ReadRollbackServices(string fileName, List <string> rollbackList, bool addUnique)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                // Read back the file identification data, if any
                if (!ReadFiles.IsHeaderValid(fs, "IURUSV1"))
                {
                    throw new Exception("Identifier incorrect");
                }

                byte bType = (byte)fs.ReadByte();
                while (!ReadFiles.ReachedEndByte(fs, bType, 0xFF))
                {
                    switch (bType)
                    {
                    case 0x01:     // service to start again
                        if (addUnique)
                        {
                            ClientFile.AddUniqueString(ReadFiles.ReadString(fs), rollbackList);
                        }
                        else
                        {
                            rollbackList.Add(ReadFiles.ReadString(fs));
                        }
                        break;

                    default:
                        ReadFiles.SkipField(fs, bType);
                        break;
                    }

                    bType = (byte)fs.ReadByte();
                }
            }
        }
Ejemplo n.º 8
0
        public void ClientA_LoadClientFilesTest()
        {
            LoadConfigFile("appsettings.Development.ClientA.json");

            HomeController homeController = new HomeController(null, Configuration);

            IList <ClientFile> expectedList = new List <ClientFile>();

            expectedList.Add(new ClientFile
            {
                Name      = "blaze",
                Date      = DateTime.Parse("2018-05-01"),
                SortIndex = 3,
                Filename  = "blaze-2018-05-01.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "blaze",
                Date      = DateTime.Parse("2019-01-23"),
                SortIndex = 3,
                Filename  = "blaze-2019-01-23.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "discus",
                Date      = DateTime.Parse("2015-12-16"),
                SortIndex = 4,
                Filename  = "discus-2015-12-16.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "shovel",
                Date      = DateTime.Parse("2000-01-01"),
                SortIndex = 1,
                Filename  = "shovel-2000-01-01.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "waghor",
                Date      = DateTime.Parse("2012-06-20"),
                SortIndex = 2,
                Filename  = "waghor-2012-06-20.xml"
            });

            ClientFile[] expectedArray = expectedList.ToArray();

            ClientFile[] actualArray = homeController.GetClientFiles(homeController.GetClientSettings()).ToArray();

            for (int i = 0; i < expectedArray.Length; i++)
            {
                ClientFile expected = expectedArray[i];
                ClientFile actual   = actualArray[i];

                Assert.AreEqual(expected.Name, actual.Name);
                Assert.AreEqual(expected.Date, actual.Date);
                Assert.AreEqual(expected.SortIndex, actual.SortIndex);
                Assert.AreEqual(expected.Filename, actual.Filename);
            }
        }
Ejemplo n.º 9
0
        public void ClientB_LoadClientFilesTest()
        {
            LoadConfigFile("appsettings.Development.ClientB.json");

            HomeController homeController = new HomeController(null, Configuration);

            IList <ClientFile> expectedList = new List <ClientFile>();

            expectedList.Add(new ClientFile
            {
                Name      = "eclair",
                Date      = DateTime.ParseExact("20180908", "yyyyMMdd", CultureInfo.InvariantCulture),
                SortIndex = 3,
                Filename  = "eclair_20180908.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "orca",
                Date      = DateTime.ParseExact("20130219", "yyyyMMdd", CultureInfo.InvariantCulture),
                SortIndex = 1,
                Filename  = "orca_20130219.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "orca",
                Date      = DateTime.ParseExact("20170916", "yyyyMMdd", CultureInfo.InvariantCulture),
                SortIndex = 1,
                Filename  = "orca_20170916.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "talon",
                Date      = DateTime.ParseExact("20150831", "yyyyMMdd", CultureInfo.InvariantCulture),
                SortIndex = 4,
                Filename  = "talon_20150831.xml"
            });
            expectedList.Add(new ClientFile
            {
                Name      = "widget",
                Date      = DateTime.ParseExact("20101101", "yyyyMMdd", CultureInfo.InvariantCulture),
                SortIndex = 2,
                Filename  = "widget_20101101.xml"
            });

            ClientFile[] expectedArray = expectedList.ToArray();

            ClientFile[] actualArray = homeController.GetClientFiles(homeController.GetClientSettings()).ToArray();

            for (int i = 0; i < expectedArray.Length; i++)
            {
                ClientFile expected = expectedArray[i];
                ClientFile actual   = actualArray[i];

                Assert.AreEqual(expected.Name, actual.Name);
                Assert.AreEqual(expected.Date, actual.Date);
                Assert.AreEqual(expected.SortIndex, actual.SortIndex);
                Assert.AreEqual(expected.Filename, actual.Filename);
            }
        }
        private ClientFile getClientFileFromFullPath(string routeAndName)
        {
            string filename = routeAndName.Split('\\')[routeAndName.Split('\\').Length - 1];

            ClientFile fileToAdd = new ClientFile(filename, routeAndName);

            return(fileToAdd);
        }
        public void returnUpdatedFile(string filename)
        {
            ClientFile clientFile = myFiles.Find(c => c.name.Equals(filename) && c.editable);

            if (clientFile == null)
            {
                clientFile = new ClientFile(filename, startupPath + "\\" + filename);
            }
            sendFileToServer(clientFile, false);
            receiveData();
        }
 public ClientFileViewModel(ClientFile clientFile)
 {
     Id = clientFile.Id;
     FileNumber = clientFile.FileNumber;
     ClientName = clientFile.ClientName;
     ClientContactPerson = clientFile.ClientContactPerson;
     AssociateReponsible = clientFile.AssociateReponsible;
     CaSign = clientFile.CaSign;
     DscExpiryDate = clientFile.DscExpiryDate;
     FileStatus = clientFile.FileStatus;
 }
        public void addFile(string routeAndName)
        {
            NetworkStream nws       = tcpClient.GetStream();
            ClientFile    fileToAdd = getClientFileFromFullPath(routeAndName);

            sendFileToServer(fileToAdd, true);
            receiveData();

            /*ClientFile newFile = new ClientFile();
             * sendFileToServer(clientFile);*/
            //receiveData();
        }
        private void downloadReadableFile(byte[] data)
        {
            ClientFile clientFile = downloadFile(data);

            clientFile.readable = true;
            if (myFiles.Contains(clientFile))
            {
                int index = myFiles.FindIndex(c => c.name.Equals(clientFile.name));
                myFiles[index].path     = clientFile.path;
                myFiles[index].readable = clientFile.readable;
            }
            else
            {
                myFiles.Add(clientFile);
            }
        }
Ejemplo n.º 15
0
        private void BtnProbar_Click(object sender, EventArgs e)
        {
            var txtServidor = FindViewById <TextView>(Resource.Id.edtServidor);
            var txtPort     = FindViewById <TextView>(Resource.Id.edtPuerto);

            try
            {
                ClientFile clienteTcp = new ClientFile(aPort: int.Parse(txtPort.Text), aServer: txtServidor.Text);
                clienteTcp.Context = this;
                clienteTcp.Conectar();
                Toast.MakeText(this, "Conectado.", ToastLength.Short).Show();
            }
            catch (Exception ex)
            {
                var edtMensaje = FindViewById <EditText>(Resource.Id.edtMensaje);
                edtMensaje.Text += ex.Message + "\n";
            }
        }
        private void removeEditableFile(byte[] data)
        {
            var        filename   = Encoding.ASCII.GetString(data);
            ClientFile clientFile = myFiles.Find(c => c.name.Equals(filename) && c.editable);

            if (clientFile != null)
            {
                if (myFiles.Contains(clientFile))
                {
                    if (!clientFile.readable)
                    {
                        myFiles.Remove(clientFile);
                    }
                    else
                    {
                        clientFile.editable = false;
                    }
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 获取本地文件列表
        /// </summary>
        /// <param name="dict">客户端文件信息集合</param>
        /// <param name="appId">应用ID</param>
        /// <param name="root">根目录</param>
        /// <param name="ext">扩展名,默认为*.*,表示全部文件;否则列举扩展名,例如:".exe|.dll"</param>
        /// <param name="path">当前目录</param>
        public static void GetClientFiles(Dictionary <string, ClientFile> dict, string appId, string root, string ext = "*.*", string path = null)
        {
            // 读取目录下文件信息
            var dirInfo = new DirectoryInfo(path ?? root);
            var files   = dirInfo.GetFiles().Where(f => f.DirectoryName != null && (ext == "*.*" || ext.Contains(f.Extension)));

            foreach (var file in files)
            {
                var id   = Hash(file.Name);
                var info = new ClientFile
                {
                    id         = id,
                    appId      = appId,
                    name       = file.Name,
                    path       = file.DirectoryName?.Replace(root, ""),
                    fullPath   = file.FullName,
                    version    = FileVersionInfo.GetVersionInfo(file.FullName).FileVersion,
                    updateTime = DateTime.Now
                };
                dict[id] = info;
            }
            Directory.GetDirectories(path ?? root).ToList().ForEach(p => GetClientFiles(dict, appId, root, ext, p));
        }
Ejemplo n.º 18
0
        public void RECEIVE()   //서버로 부터 받기
        {
            int check = 0;

            while (this.m_blsCientOn)
            {
                int nRead = 0;
                try
                {
                    nRead = 0;
                    nRead = this.m_NetStream.Read(readBuffer, 0, readBuffer.Length);    //데이터 읽기
                }
                catch
                {
                    this.m_blsCientOn = false;
                    this.m_NetStream  = null;
                    return;
                }

                Packet packet = (Packet)Packet.Deserialize(readBuffer);

                switch ((int)packet.Type)
                {
                case (int)PacketType.SendToClient:      //처음 연결하고 리스트목록 받을 때
                {
                    MusicName music = (MusicName)Packet.Deserialize(readBuffer);
                    this.Invoke(new MethodInvoker(delegate() { item = musicList.Items.Add(music.musicName); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.artistName); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.musicTime); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.bitRate); }));
                }
                break;

                case (int)PacketType.ReceiveToServer:                              //파일 받을 때
                {
                    ClientFile cFile = (ClientFile)Packet.Deserialize(readBuffer); //데이터 객체화
                    check++;                                                       //파일 처음 확인

                    FileDownPath = downPath + "\\" + cFile.FileName;               //클라이언트 선택 경로+파일 이름
                    FileName     = cFile.FileName;
                    if (check == 1)                                                //파일 전송이 처음이면

                    {
                        this.Invoke(new MethodInvoker(delegate() { progressBar.Maximum = cFile.FileCount; }));
                        //프로그래스바 초기화
                        filestream = new FileStream(FileDownPath, FileMode.Append, FileAccess.Write);
                        //서버의 이름과 같은 파일 Create,Append
                    }

                    this.Invoke(new MethodInvoker(delegate() { progressBar.PerformStep(); }));         //프로그래스바 확장
                    filestream.Write(cFile.FileData, 0, cFile.FileData.Length);

                    if (check == cFile.FileCount)           //파일 전체 전송 완료
                    {
                        this.Invoke(new MethodInvoker(delegate() { progressBar.PerformStep(); }));
                        filestream.Close();                                                    //파일 닫기
                        check = 0;                                                             //check 초기화
                        this.Invoke(new MethodInvoker(delegate() { progressBar.Value = 0; })); //프로그래스바 초기화

                        /*플레이 리스트에 추가*/
                        IWMPMedia Media;
                        Media = WMP.newMedia(@FileDownPath);            //새로운 음악파일 객체 생성
                        MusicPlayList.appendItem(Media);                //플레이리스트에 추가
                    }
                }
                break;

                case (int)PacketType.서버음악정보:      //처음 연결하고 리스트목록 받을 때
                {
                    MusicName music = (MusicName)Packet.Deserialize(readBuffer);
                    this.Invoke(new MethodInvoker(delegate() { item = playList.Items.Add(music.musicName); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.artistName); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.musicTime); }));
                    this.Invoke(new MethodInvoker(delegate() { item.SubItems.Add(music.bitRate); }));
                }
                break;
                }
            }
        }
        void bw_DoWorkClientData(object sender, DoWorkEventArgs e)
        {
            Exception except = null;

            try
            {
                OutputDirectory = Path.Combine(TempDirectory, "ClientData");
                Directory.CreateDirectory(OutputDirectory);

                string oldClientFile = null;

                // see if a 1.1+ client file exists (client.wyc)
                if (ClientFileType != ClientFileType.Final
                    && File.Exists(Path.Combine(Path.GetDirectoryName(Filename), "client.wyc")))
                {
                    oldClientFile = Filename;
                    Filename = Path.Combine(Path.GetDirectoryName(Filename), "client.wyc");
                    ClientFileType = ClientFileType.Final;
                }


                if (ClientFileType == ClientFileType.PreRC2)
                {
                    //convert pre-RC2 client file by saving images to disk
                    string tempImageFilename;

                    //create the top image
                    if (ClientFile.TopImage != null)
                    {
                        ClientFile.TopImageFilename = "t.png";

                        tempImageFilename = Path.Combine(OutputDirectory, "t.png");
                        ClientFile.TopImage.Save(tempImageFilename, System.Drawing.Imaging.ImageFormat.Png);
                    }

                    //create the side image
                    if (ClientFile.SideImage != null)
                    {
                        ClientFile.SideImageFilename = "s.png";

                        tempImageFilename = Path.Combine(OutputDirectory, "s.png");
                        ClientFile.SideImage.Save(tempImageFilename, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
                else
                {
                    //Extract the contents of the client data file
                    ExtractUpdateFile();

                    if (File.Exists(Path.Combine(OutputDirectory, "iuclient.iuc")))
                    {
                        // load and merge the existing file

                        ClientFile tempClientFile = new ClientFile();
                        tempClientFile.LoadClientData(Path.Combine(OutputDirectory, "iuclient.iuc"));
                        tempClientFile.InstalledVersion = ClientFile.InstalledVersion;
                        ClientFile = tempClientFile;

                        File.Delete(Path.Combine(OutputDirectory, "iuclient.iuc"));
                    }
                }

                List<UpdateFile> updateDetailsFiles = UpdtDetails.UpdateFiles;

                FixUpdateFilesPaths(updateDetailsFiles);


                //write the uninstall file
                RollbackUpdate.WriteUninstallFile(TempDirectory, Path.Combine(OutputDirectory, "uninstall.dat"), updateDetailsFiles);

                List<UpdateFile> files = new List<UpdateFile>();

                //add all the files in the outputDirectory
                AddFiles(OutputDirectory.Length + 1, OutputDirectory, files);

                //recompress all the client data files
                string tempClient = Path.Combine(TempDirectory, "client.file");
                ClientFile.SaveClientFile(files, tempClient);

                // overrite existing client.wyc, while keeping the file attributes

                FileAttributes atr = FileAttributes.Normal;

                if (File.Exists(Filename))
                    atr = File.GetAttributes(Filename);

                bool resetAttributes = (atr & FileAttributes.Hidden) != 0 || (atr & FileAttributes.ReadOnly) != 0 || (atr & FileAttributes.System) != 0;

                // remove the ReadOnly & Hidden atributes temporarily
                if (resetAttributes)
                    File.SetAttributes(Filename, FileAttributes.Normal);

                //replace the original
                File.Copy(tempClient, Filename, true);

                if (resetAttributes)
                    File.SetAttributes(Filename, atr);


                if (oldClientFile != null)
                {
                    // delete the old client file
                    File.Delete(oldClientFile);
                }
            }
            catch (Exception ex)
            {
                // handle failed to write to client file
                except = ex;
            }

            if (except != null)
            {
                // tell the main window we're rolling back registry
                bw.ReportProgress(1, true);

                // rollback started services
                RollbackUpdate.RollbackStartedServices(TempDirectory);

                // rollback newly regged COM dlls
                RollbackUpdate.RollbackRegedCOM(TempDirectory);

                // rollback the registry
                RollbackUpdate.RollbackRegistry(TempDirectory);

                //rollback files
                bw.ReportProgress(1, false);
                RollbackUpdate.RollbackFiles(TempDirectory, ProgramDirectory);

                // rollback unregged COM
                RollbackUpdate.RollbackUnregedCOM(TempDirectory);

                // rollback stopped services
                RollbackUpdate.RollbackStoppedServices(TempDirectory);

                bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Failure, except });
            }
            else
            {
                bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Success, null });
            }
        }
Ejemplo n.º 20
0
        private void btnUpload_Click(object sender, EventArgs e)
        {
            string filePath = OpenDialog();

            if (filePath != "")
            {
                ClientFile clientFile = new ClientFile();
                clientFile.ClientName = txtUserName.Text;

                int    bufferSize       = 3000000;
                double currentProgress  = 0;
                long   totalBytesRead   = 0;
                bool   isChangeFileName = false;

                string[]   splitString  = filePath.Split('\\');
                FileInfo   fileInfo     = new FileInfo(filePath); // Get file Length
                MyFileInfo sendFileInfo = new MyFileInfo(File.OpenRead(filePath), splitString[splitString.Length - 1], fileInfo.Length);

                clientFile.Buffer   = new byte[bufferSize]; // In C#, if u give byte array a new assign, it will release orgin space that u used automatically by GC(Garbage Collection).
                clientFile.FileName = sendFileInfo.FileName;

                do
                {
                    clientFile.BytesRead     = sendFileInfo.Stream.Read(clientFile.Buffer, 0, clientFile.Buffer.Length);
                    clientFile.isFinsishFlag = false;

                    service.ReceiveFile(clientFile, isChangeFileName);

                    isChangeFileName = true;
                    totalBytesRead  += clientFile.BytesRead;

                    if (sendFileInfo.FileSize != 0)
                    {
                        currentProgress = (((double)totalBytesRead) / sendFileInfo.FileSize) * 100;
                    }
                    else
                    {
                        currentProgress = 100;
                    }

                    pgbReadFile.Value = Convert.ToInt32(currentProgress);
                    if (currentProgress == 100)
                    {
                        clientFile.isFinsishFlag = true;
                        service.ReceiveFile(clientFile, isChangeFileName); // Call again make service file close
                    }
                } while (currentProgress != 100);                          //== buffer.Length


                rtbHistory.AppendText("- Upload \"" + clientFile.FileName + "\" success -");
                rtbHistory.AppendText("\n---------------------------------------------------------\n");
                back.SetForm(this);
            }

            #region Test Time
            //string filePath = OpenDialog();

            //if (filePath != "")
            //{
            //    int roundCount = 0;
            //    int timesCount = 0;
            //    Stopwatch sw_total = new Stopwatch();
            //    Stopwatch sw_step = new Stopwatch();
            //    string usingTime = "";
            //    List<string> usingTimeList = new List<string>();

            //    ClientFile clientFile = new ClientFile();
            //    clientFile.ClientName = txtUserName.Text;
            //    int bufferSize = 3000000;

            //    for (int i = 0; i < 3; i++)
            //    {
            //        sw_total.Reset();
            //        sw_step.Reset();
            //        sw_total.Start();
            //        sw_step.Start();

            //        roundCount = 0;

            //        bool isChangeFileName = false;
            //        long totalBytesRead = 0;
            //        double currentProgress = 0;

            //        string[] splitString = filePath.Split('\\');
            //        FileInfo fileInfo = new FileInfo(filePath); // Get file Length
            //        MyFileInfo sendFileInfo = new MyFileInfo(File.OpenRead(filePath), splitString[splitString.Length - 1], fileInfo.Length);

            //        clientFile.Buffer = new byte[bufferSize]; // In C#, if u give byte array a new assign, it will release orgin space that u used automatically by GC(Garbage Collection).

            //        timesCount++;
            //        rtbHistory.AppendText("\n-----No. " + timesCount.ToString() + " transport " + sendFileInfo.FileName + "-----\n\n");
            //        sw_step.Stop();
            //        usingTime = sw_step.Elapsed.TotalMilliseconds.ToString();
            //        rtbHistory.AppendText("Assign Time : " + usingTime + "\n");

            //        do
            //        {
            //            sw_step.Reset();
            //            sw_step.Start();

            //            clientFile.BytesRead = sendFileInfo.Stream.Read(clientFile.Buffer, 0, clientFile.Buffer.Length);
            //            clientFile.FileName = sendFileInfo.FileName;
            //            clientFile.isFinsishFlag = false;

            //            service.ReceiveFile(clientFile, isChangeFileName);

            //            isChangeFileName = true;
            //            totalBytesRead += clientFile.BytesRead;

            //            if (sendFileInfo.FileSize != 0)
            //                currentProgress = (((double)totalBytesRead) / sendFileInfo.FileSize) * 100;
            //            else
            //                currentProgress = 100;

            //            pgbReadFile.Value = Convert.ToInt32(currentProgress);
            //            if (currentProgress == 100)
            //            {
            //                clientFile.isFinsishFlag = true;
            //                service.ReceiveFile(clientFile, isChangeFileName);
            //            }

            //            roundCount++;
            //            sw_step.Stop();
            //            usingTime = sw_step.Elapsed.TotalMilliseconds.ToString();
            //            rtbHistory.AppendText("Round " + roundCount.ToString() + " Time : " + usingTime + "\n");

            //        } while (currentProgress != 100);//== buffer.Length

            //        sw_total.Stop();
            //        usingTime = sw_total.Elapsed.TotalMilliseconds.ToString();
            //        rtbHistory.AppendText("\nUsing total time : " + usingTime + "\n");//"Transport" + clientFile .FileName + " successful\nTotal using time : " +  ms
            //        usingTimeList.Add(usingTime);
            //    }

            //    rtbHistory.AppendText("\n---------------------------------------------------------\n");
            //    for (int i = 1; i < usingTimeList.Count + 1; i++)
            //    {
            //        rtbHistory.AppendText("-No. " + i.ToString() + " transport " + usingTimeList[i - 1] + " ms-\n");
            //    }

            //    back.SetForm(this);
            //}
            #endregion
        }
        void bw_DoWorkClientData(object sender, DoWorkEventArgs e)
        {
            Exception except = null;

            try
            {
                OutputDirectory = Path.Combine(TempDirectory, "ClientData");
                Directory.CreateDirectory(OutputDirectory);

                string oldClientFile = null;

                // see if a 1.1+ client file exists (client.wyc)
                if (ClientFileType != ClientFileType.Final &&
                    File.Exists(Path.Combine(Path.GetDirectoryName(Filename), "client.wyc")))
                {
                    oldClientFile  = Filename;
                    Filename       = Path.Combine(Path.GetDirectoryName(Filename), "client.wyc");
                    ClientFileType = ClientFileType.Final;
                }


                if (ClientFileType == ClientFileType.PreRC2)
                {
                    //convert pre-RC2 client file by saving images to disk
                    string tempImageFilename;

                    //create the top image
                    if (ClientFile.TopImage != null)
                    {
                        ClientFile.TopImageFilename = "t.png";

                        tempImageFilename = Path.Combine(OutputDirectory, "t.png");
                        ClientFile.TopImage.Save(tempImageFilename, System.Drawing.Imaging.ImageFormat.Png);
                    }

                    //create the side image
                    if (ClientFile.SideImage != null)
                    {
                        ClientFile.SideImageFilename = "s.png";

                        tempImageFilename = Path.Combine(OutputDirectory, "s.png");
                        ClientFile.SideImage.Save(tempImageFilename, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
                else
                {
                    //Extract the contents of the client data file
                    ExtractUpdateFile();

                    if (File.Exists(Path.Combine(OutputDirectory, "iuclient.iuc")))
                    {
                        // load and merge the existing file

                        ClientFile tempClientFile = new ClientFile();
                        tempClientFile.LoadClientData(Path.Combine(OutputDirectory, "iuclient.iuc"));
                        tempClientFile.InstalledVersion = ClientFile.InstalledVersion;
                        ClientFile = tempClientFile;

                        File.Delete(Path.Combine(OutputDirectory, "iuclient.iuc"));
                    }
                }

                List <UpdateFile> updateDetailsFiles = UpdtDetails.UpdateFiles;

                FixUpdateFilesPaths(updateDetailsFiles);


                //write the uninstall file
                RollbackUpdate.WriteUninstallFile(TempDirectory, Path.Combine(OutputDirectory, "uninstall.dat"), updateDetailsFiles);

                List <UpdateFile> files = new List <UpdateFile>();

                //add all the files in the outputDirectory
                AddFiles(OutputDirectory.Length + 1, OutputDirectory, files);

                //recompress all the client data files
                string tempClient = Path.Combine(TempDirectory, "client.file");
                ClientFile.SaveClientFile(files, tempClient);

                // overrite existing client.wyc, while keeping the file attributes

                FileAttributes atr = FileAttributes.Normal;

                if (File.Exists(Filename))
                {
                    atr = File.GetAttributes(Filename);
                }

                bool resetAttributes = (atr & FileAttributes.Hidden) != 0 || (atr & FileAttributes.ReadOnly) != 0 || (atr & FileAttributes.System) != 0;

                // remove the ReadOnly & Hidden atributes temporarily
                if (resetAttributes)
                {
                    File.SetAttributes(Filename, FileAttributes.Normal);
                }

                //replace the original
                File.Copy(tempClient, Filename, true);

                if (resetAttributes)
                {
                    File.SetAttributes(Filename, atr);
                }


                if (oldClientFile != null)
                {
                    // delete the old client file
                    File.Delete(oldClientFile);
                }
            }
            catch (Exception ex)
            {
                // handle failed to write to client file
                except = ex;
            }

            if (except != null)
            {
                // tell the main window we're rolling back registry
                bw.ReportProgress(1, true);

                // rollback started services
                RollbackUpdate.RollbackStartedServices(TempDirectory);

                // rollback newly regged COM dlls
                RollbackUpdate.RollbackRegedCOM(TempDirectory);

                // rollback the registry
                RollbackUpdate.RollbackRegistry(TempDirectory);

                //rollback files
                bw.ReportProgress(1, false);
                RollbackUpdate.RollbackFiles(TempDirectory, ProgramDirectory);

                // rollback unregged COM
                RollbackUpdate.RollbackUnregedCOM(TempDirectory);

                // rollback stopped services
                RollbackUpdate.RollbackStoppedServices(TempDirectory);

                bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Failure, except });
            }
            else
            {
                bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Success, null });
            }
        }
Ejemplo n.º 22
0
        private void ReadCallback(IAsyncResult ar)
        {
            Socket handler  = (Socket)ar.AsyncState;
            int    received = handler.EndReceive(ar);

            if (received > 0)
            {
                sb.Append(Encoding.ASCII.GetString(buffer, 0, received));
                string content = sb.ToString();

                if (content.IndexOf(ServerConstants.EOF) > -1)
                {
                    content = content.Substring(0, content.Length - 5);
                    serverTB.AppendText("Read " + content.Length + " bytes from socket.\r\nData: " + content + "\r\n\r\n");

                    var deserialized = JsonConvert.DeserializeObject <PackageWrapper>(content);
                    if (deserialized.PackageType == typeof(LoginPackage))
                    {
                        LoginPackage lp = (LoginPackage)JsonConvert.DeserializeObject(Convert.ToString(deserialized.Package), deserialized.PackageType);

                        ClientsDetailsPackage client = Client.getClientsDetailsPackage(lp);

                        byte[] sendClient = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(client) + ServerConstants.EOF);
                        handler.BeginSend(sendClient, 0, sendClient.Length, 0, new AsyncCallback(SendCallback), handler);
                    }

                    else if (deserialized.PackageType == typeof(FileSearch))
                    {
                        FileSearch fs = (FileSearch)JsonConvert.DeserializeObject(Convert.ToString(deserialized.Package), deserialized.PackageType);

                        List <FileDetails> lfd        = new List <FileDetails>();
                        List <File>        listFile   = new List <File>();
                        List <ClientFile>  listClient = new List <ClientFile>();
                        Client             client     = new Client();
                        FilePackage        fp         = new FilePackage();

                        if (fs.FileName.CompareTo("*") == 0)
                        {
                            listFile = File.getAllFilesList();

                            foreach (var item in listFile)
                            {
                                listClient = ClientFile.getAllFilesById(item.Id);
                                foreach (var item2 in listClient)
                                {
                                    client.getClient(item2.Username);

                                    FileDetails f = new FileDetails
                                    {
                                        Username = item2.Username,
                                        FileName = item.Name,
                                        FileSize = item.Size,
                                        Ip       = client.Ip,
                                        Port     = client.Port
                                    };

                                    lfd.Add(f);
                                }
                            }

                            fp.Exist     = true;
                            fp.FilesList = lfd;
                        }

                        else if (!File.isFileExist(fs.FileName))
                        {
                            fp.Exist = false;
                        }

                        else
                        {
                            listFile = File.getAllFilesListByName(fs.FileName);

                            foreach (var item in listFile)
                            {
                                listClient = ClientFile.getAllFilesById(item.Id);
                                foreach (var item2 in listClient)
                                {
                                    client.getClient(item2.Username);
                                    int size = item.Size;

                                    FileDetails f = new FileDetails
                                    {
                                        Username = item2.Username,
                                        FileName = item.Name,
                                        FileSize = size,
                                        Ip       = client.Ip,
                                        Port     = client.Port
                                    };

                                    lfd.Add(f);
                                }
                            }

                            fp.Exist     = true;
                            fp.FilesList = lfd;
                        }

                        byte[] sendAnswer = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(fp) + ServerConstants.EOF);
                        handler.BeginSend(sendAnswer, 0, sendAnswer.Length, 0, new AsyncCallback(SendCallback), handler);
                    }

                    else
                    {
                        LogoutPackage lp = (LogoutPackage)JsonConvert.DeserializeObject(Convert.ToString(deserialized.Package), deserialized.PackageType);
                        Client.setLogOut(lp.Username);
                    }
                }

                else
                {
                    handler.BeginReceive(buffer, 0, ServerConstants.BufferSize, 0, new AsyncCallback(ReadCallback), handler);
                }

                sb.Clear();
                handler.BeginReceive(buffer, 0, ServerConstants.BufferSize, 0, new AsyncCallback(ReadCallback), handler);
            }
        }
Ejemplo n.º 23
0
        public void RUN()
        {
            this.m_Listener = new TcpListener(PORT);
            this.m_Listener.Start();
            MusicName MusicInfo = new MusicName();

            MusicInfo.Type = (int)PacketType.SendToClient;

            Socket Client = this.m_Listener.AcceptSocket();

            if (Client.Connected) //client 처음에 listView 데이터 보냄
            {
                m_blsCientOn = true;
                this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Client Access !!\n"); }));
                this.m_NetStream = new NetworkStream(Client);

                foreach (FileInfo fInfo in fArray)  //파일 정보 ListView에 저장
                {
                    FolderItem mp3file = folder.ParseName(fInfo.Name);

                    MusicInfo.musicName  = (folder.GetDetailsOf(mp3file, 21));
                    MusicInfo.artistName = (folder.GetDetailsOf(mp3file, 20));
                    MusicInfo.musicTime  = (folder.GetDetailsOf(mp3file, 27));
                    MusicInfo.bitRate    = (folder.GetDetailsOf(mp3file, 28));
                    MusicInfo.path       = this.path;

                    Packet.Serialize(MusicInfo).CopyTo(sendBuffer, 0); //send buffer로 복사
                    this.Send();                                       //NetStream으로 복사
                }
            }

            int nRead = 0;

            while (this.m_blsCientOn)
            {
                try
                {
                    nRead = 0;
                    nRead = this.m_NetStream.Read(this.readBuffer, 0, readBuffer.Length);
                }
                catch
                {
                    this.m_blsCientOn = false;
                    this.m_NetStream  = null;
                }

                Packet packet = (Packet)Packet.Deserialize(readBuffer);

                switch ((int)packet.Type)
                {
                case (int)PacketType.SendToServer:      //클라이언트가 원하는 파일 얻어오기
                {
                    string        filePath  = null;
                    ClientRequest request   = (ClientRequest)Packet.Deserialize(readBuffer); //클라이언트에 파일 보내기위한 desirialize
                    MusicName     musicInfo = new MusicName();                               //클라이언트 플레이 리스트 추가

                    musicInfo.Type = (int)PacketType.서버음악정보;
                    string clientMusic = request.musicName;         //클라이언트가 원하는 음악 제목
                    int    i           = 0;
                    this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Download Request !!\n"); }));

                    foreach (FileInfo fInfo in fArray)          //파일 정보 ListView에 저장
                    {
                        FolderItem mp3file = folder.ParseName(fInfo.Name);
                        if (folder.GetDetailsOf(mp3file, 21).Equals(clientMusic))           //클라이언트 요청한 파일 확인
                        {
                            filePath             = fArray[i].FullName;
                            musicInfo.musicName  = (folder.GetDetailsOf(mp3file, 21));
                            musicInfo.artistName = (folder.GetDetailsOf(mp3file, 20));
                            musicInfo.musicTime  = (folder.GetDetailsOf(mp3file, 27));
                            musicInfo.bitRate    = (folder.GetDetailsOf(mp3file, 28));
                            musicInfo.path       = this.path;
                        }
                        else
                        {
                            i++;
                        }
                    }
                    this.Invoke(new MethodInvoker(delegate() { stateTxt.AppendText("Send File : " + filePath + "\n"); }));

                    FileInfo   fileInfo = new FileInfo(filePath);                                   //서버 상태 텍스트에 추가 할 해당 파일 정보
                    ClientFile cFile    = new ClientFile();                                         //서버의 파일을 보내기 위한 패킷
                    FileStream fi       = new FileStream(filePath, FileMode.Open, FileAccess.Read); //클라이언트가 원하는 파일 열고 읽기

                    cFile.FileName      = fileInfo.Name;                                            //파일 이름
                    cFile.FileNameLegth = fi.Name.Length;                                           //파일 이름 사이즈
                    cFile.FileSize      = (int)fi.Length;                                           //파일 사이즈

                    int count = (int)fi.Length / (1024 * 2);                                        // 파일 전체 크기/읽는 크기

                    cFile.FileCount = count + 1;                                                    //파일 읽는 전체 count

                    for (int j = 0; j < count; j++)
                    {
                        fi.Read(cFile.FileData, 0, 1024 * 2);
                        cFile.Type = (int)PacketType.ReceiveToServer;
                        Packet.Serialize(cFile).CopyTo(sendBuffer, 0); //send buffer로 복사
                        this.Send();                                   //NetStream으로 복사*/
                    }

                    fi.Read(cFile.FileData, 0, 1024 * 2);          //마지막 남은 스트림 보내기
                    cFile.Type = (int)PacketType.ReceiveToServer;
                    Packet.Serialize(cFile).CopyTo(sendBuffer, 0); //send buffer로 복사
                    this.Send();                                   //NetStream으로 복사*/


                    Packet.Serialize(musicInfo).CopyTo(sendBuffer, 0); //파일 전송 끝나면 클라이언트 플레이 리스트에 추가
                    this.Send();                                       //NetStream으로 복사
                }
                break;
                }
            }
        }