/// <summary> /// Проверка наличия в БД новых версий файлов и заполнение коллекции именами и версиями этих файлов /// </summary> public void GetFileList() { SqlConnection cnn = MiscFunction.OpenConnection(_connectionString); const string sqlStr = "SELECT idFile, version, name, DATALENGTH(binaryData) AS fileSize FROM Srv_ProgramFile"; var cmd = new SqlCommand(sqlStr, cnn); SqlDataReader sdr = cmd.ExecuteReader(); int version = sdr.GetOrdinal("version"); int fileName = sdr.GetOrdinal("name"); int fileSize = sdr.GetOrdinal("fileSize"); var clientVersionManager = new ClientVersionManager(_xmlFileName); FilesForUpdate.Clear(); while (sdr.Read()) { var fileInfo = new FileInfo(sdr.GetString(fileName), clientVersionManager.GetVersion(sdr.GetString(fileName)), sdr.GetInt32(version), sdr.GetInt32(fileSize)); if (_downloadAllFiles || fileInfo.NeedUpdate) { FilesForUpdate.Add(fileInfo); } } sdr.Close(); cnn.Close(); }
/// <summary> /// Загрузка файла в БД /// </summary> /// <param name="fileName">Полный путь и имя файла для загрузки в БД</param> public void Upload(String fullFileName) { SqlConnection CN = MiscFunction.OpenConnection(_connectionString); RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create(); String fileName = MiscFunction.GetFileName(fullFileName); FileStream fs = new System.IO.FileStream(fullFileName, FileMode.Open, FileAccess.Read); Byte[] imageData = new Byte[fs.Length]; fs.Read(imageData, 0, Convert.ToInt32(fs.Length)); //SHA-1 byte[] hashValue; hashValue = myRIPEMD160.ComputeHash(fs); string result = BitConverter.ToString(hashValue).Replace("-", String.Empty); //System.IO.File.WriteAllText("C:\\Users\\Марсель\\Documents\\Uploader\\Updater\\bin\\Debug\\TestFile2.txt", result); fs.Close(); String strSQL; if (!ChekExists(CN, fileName)) {//INSERT strSQL = "INSERT INTO Srv_ProgramFile (version, name, author, binaryData, Date, hashCode) " + "VALUES (1, @name, @autor, @binaryData, @Date, @hashCode)"; } else {//UPDATE strSQL = "UPDATE Srv_ProgramFile SET version=version+1, name=@name, author=@autor, binaryData=@binaryData " + "WHERE name=@name"; } SqlCommand cmd = new SqlCommand(strSQL, CN) { CommandTimeout = 60 }; cmd.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 128)).Value = fileName; cmd.Parameters.Add(new SqlParameter("@autor", SqlDbType.NVarChar, 50)).Value = System.Security.Principal.WindowsIdentity.GetCurrent().Name; cmd.Parameters.Add(new SqlParameter("@binaryData", SqlDbType.Image)).Value = imageData; cmd.Parameters.Add("@Date", DateTime.Now.Date); cmd.Parameters.Add("@hashCode", SqlDbType.NVarChar, 50).Value = result; cmd.ExecuteNonQuery(); CN.Close(); }
/// <summary> /// Загрузка файла из БД и сохранение под другим именем /// </summary> /// <param name="fileName">Файл для загрузки из БД</param> /// <param name="fullFileName">Полный путь и имя файла для сохранения</param> private void Download(String fileName, String fullFileName, DownloadProgress progress) { SqlConnection connection = MiscFunction.OpenConnection(_connectionString); var strSql = "SELECT binaryData FROM Srv_ProgramFile WHERE name = '" + MiscFunction.GetFileName(fileName) + "'"; var cmd = new SqlCommand(strSql, connection); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); reader.Read(); var fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write); var writer = new BinaryWriter(fs); int startIndex = 0; const int bufferSize = 1000; var outByte = new byte[bufferSize]; long retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize); while (retval == bufferSize) { writer.Write(outByte); writer.Flush(); startIndex += bufferSize; retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize); progress.InicrementDownloadedSize((int)retval); } writer.Write(outByte, 0, (int)retval); writer.Flush(); writer.Close(); fs.Close(); reader.Close(); connection.Close(); }
private void _cmdInLoad_Click(object sender, EventArgs e) { String connString; connString = ConfigurationSettings.AppSettings["ConnectionString"]; String versionStorageName; versionStorageName = ConfigurationSettings.AppSettings["VersionStorage"]; SqlConnection cnn = MiscFunction.OpenConnection(connString); const string sqlStr = "SELECT idFile, version, name, DATALENGTH(binaryData) AS fileSize FROM Srv_ProgramFile"; var cmd = new SqlCommand(sqlStr, cnn); SqlDataReader sdr = cmd.ExecuteReader(); int version = sdr.GetOrdinal("version"); int fileName = sdr.GetOrdinal("name"); int fileSize = sdr.GetOrdinal("fileSize"); var clientVersionManager = new ClientVersionManager(versionStorageName); FilesForLoad.Clear(); while (sdr.Read()) { var fileInfo = new FileInfo(sdr.GetString(fileName), clientVersionManager.GetVersion(sdr.GetString(fileName)), sdr.GetInt32(version), sdr.GetInt32(fileSize)); if (fileInfo.NeedUpdate) { FilesForLoad.Add(fileInfo); } } sdr.Close(); cnn.Close(); //Вывод в таблицу информации при загрузке файлов из БД using (SqlDataAdapter a = new SqlDataAdapter("SELECT version, name, Date FROM Srv_ProgramFile", cnn)) { SqlCommandBuilder cb = new SqlCommandBuilder(a); DataSet ds = new DataSet(); a.Fill(ds, "Srv_ProgramFile"); dataGridView1.DataSource = ds.Tables[0]; } #region Процесс загрузки try { var filesManager = new FilesManager(connString); var CVManager = new ClientVersionManager(versionStorageName); long totalSize = 0; FilesForLoad.ForEach(fileInfo => totalSize += fileInfo.FileSize); var progressForm = new frmProgress((int)totalSize); progressForm.Show(); progressForm.BringToFront(); var downloadProgress = new DownloadProgress(totalSize); downloadProgress.ProgressChanged += (senders, ex) => progressForm.Tick(ex.ChangeSize, string.Format("{0,3:#.#}/{1,3:#.#} MБ ({2})", (decimal)downloadProgress.DownloadedSize / BytesInMegabyte, (decimal)downloadProgress.TotalSize / BytesInMegabyte, downloadProgress.CurrentFileName)); foreach (FileInfo fileInfo in FilesForLoad) { try { downloadProgress.SetCurrentFileName(fileInfo.FileName); filesManager.Download(fileInfo.FileName, downloadProgress); CVManager.SetVersion(fileInfo.FileName, fileInfo.ServerVersion); } catch (Exception) { progressForm.Fail(); throw; } } progressForm.Close(); } catch (Exception exception) { string _errorMessage = string.Format("Ошибка. {0}{1}{2}", exception.Message, Environment.NewLine, exception.StackTrace); MessageBox.Show("Ошибка запуска приложения:\r\n", _errorMessage); } }