private string FormContentDbColumn(PresentationInfo presInfo) { string result = null; for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { // 1 вариант content //result += String.Format("<div class='slide-block'>" + // "<h3>Слайд {0}</h3><!-- slide-title -->" + // "<div class='all-sl-img'>" + // "<img src='/files/{1}/268/{2}' alt='' />" + // "</div><!-- all-sl-img -->" + // "<div class='all-sl-txt'>{3}</div><!-- all-sl-txt -->" + // "</div><!-- slide-block -->", // (index + 1), presInfo.DbId, presInfo.SlidersInfo[index].ImageNameClientAverage, presInfo.SlidersInfo[index].Text); // 2 вариант content result += String.Format("<div class='trans'>" + "<p>Слайд {0}</p><!-- trans -->" + "<img src='/files/{1}/268/{2}' />" + "<p class='papo4ka'>{3}</p><!-- all-sl-txt -->" + "<div class='clearfix'></div>" + "</div><!-- trans -->", (index + 1), presInfo.DbId, presInfo.SlidersInfo[index].ImageNameClientAverage, presInfo.SlidersInfo[index].Text); } return(result); }
private string FormContentDbColumn(PresentationInfo presInfo) { string result = null; for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { // 1 вариант content //result += String.Format("<div class='slide-block'>" + // "<h3>Слайд {0}</h3><!-- slide-title -->" + // "<div class='all-sl-img'>" + // "<img src='/files/{1}/268/{2}' alt='' />" + // "</div><!-- all-sl-img -->" + // "<div class='all-sl-txt'>{3}</div><!-- all-sl-txt -->" + // "</div><!-- slide-block -->", // (index + 1), presInfo.DbId, presInfo.SlidersInfo[index].ImageNameClientAverage, presInfo.SlidersInfo[index].Text); // 2 вариант content result += String.Format("<div class='trans'>" + "<p>Слайд {0}</p><!-- trans -->" + "<img src='/files/{1}/268/{2}' />" + "<p class='papo4ka'>{3}</p><!-- all-sl-txt -->" + "<div class='clearfix'></div>" + "</div><!-- trans -->", (index + 1), presInfo.DbId, presInfo.SlidersInfo[index].ImageNameClientAverage, presInfo.SlidersInfo[index].Text); } return result; }
public SlideInfo(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("presInfo"); } _PresentationInfo = presInfo; }
/// <summary> /// Выложить данные на сервер /// </summary> /// <param name="presInfo">Информация о презентации</param> public override void PutDataOnServer(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("информация о презентации должна быть заполнена"); } // Тут важен порядок. Сперва в main, потом в конкретную таблицу, т.к. при добавлении в main определфется Id презентации PutDataToMainTable(presInfo); PutDataToConcretePresentationTable(presInfo); }
private string FormatIframeBDColumn(PresentationInfo presInfo) { string result = null; foreach (string imageName in presInfo.SlidersInfo.Select(pI => pI.ImageNameServerBig)) { if (!String.IsNullOrEmpty(imageName)) result += String.Format("<img src=\"/{0}/{1}/500/{2}\" class=\"slide\"/>", FTP.AverageAndBigImageServerDir, presInfo.DbId, imageName); } return result; }
private void PutDataToConcretePresentationTable(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("presInfo"); } #region Создаю конкретную таблицу, если она еще не создана try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"CREATE TABLE IF NOT EXISTS `{0}` ( `id` MEDIUMINT NOT NULL AUTO_INCREMENT, `url_news` VARCHAR(200) NOT NULL, `title` VARCHAR(200) NULL, `nazvanie` VARCHAR(200) NOT NULL, `slider` TEXT NULL, `url_dowload` TEXT(1000) NOT NULL, `size` FLOAT NOT NULL, `content` TEXT NULL, `iframe` INT NOT NULL, `random` TEXT NULL, `poxpres` TEXT NULL, PRIMARY KEY (id) ) CHARSET={1}", SecurityElement.Escape(presInfo.Categorie.ToString()), TABLE_CHARSET); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время создания таблицы '{0}' произошла ошибка: {1}", presInfo.NameAsTranslit, ex.Message)); } #endregion try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(new System.Globalization.CultureInfo("en-GB"), @" INSERT INTO `{8}` (`url_news`, `title`, `nazvanie`, `slider`, `url_dowload`, `size`, `content`, `iframe`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', {5:0.00}, '{6}', '{7}') ", SecurityElement.Escape(presInfo.UrlNews), SecurityElement.Escape(presInfo.Title), SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(FormatIframeBDColumn(presInfo)), SecurityElement.Escape(presInfo.UrlDownload), Convert.ToSingle(presInfo.FileSize / 1024 / 1024, System.Globalization.CultureInfo.InvariantCulture), SecurityElement.Escape(FormContentDbColumn(presInfo)), presInfo.DbId, SecurityElement.Escape(presInfo.Categorie.ToString())); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время заполнения таблицы 'main' презентацией '{0}' произошла ошибка: {1}", presInfo.Name, ex.Message)); } }
private string FormatIframeBDColumn(PresentationInfo presInfo) { string result = null; foreach (string imageName in presInfo.SlidersInfo.Select(pI => pI.ImageNameServerBig)) { if (!String.IsNullOrEmpty(imageName)) { result += String.Format("<img src=\"/{0}/{1}/500/{2}\" class=\"slide\"/>", FTP.AverageAndBigImageServerDir, presInfo.DbId, imageName); } } return(result); }
private string FormContentDbColumn(PresentationInfo presInfo) { string result = null; for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { string className = index == 0 ? "es" : "as"; result += String.Format("<tr>" + "<td class='{0}' colspan='2'>Слайд №{1}</td>" + "</tr>" + "<tr>" + "<td class='sludes'><img src='/{2}/{3}/225/{4}' /></td>" + " <td class='textaes'>{5}</td>" + "</tr>", className, (index + 1), FTP.AverageAndBigImageServerDir, presInfo.DbId, presInfo.SlidersInfo[index].ImageNameServerAverage, presInfo.SlidersInfo[index].Text); } return(result); }
private void ZipFileOrDirectory(string path, PresentationInfo presInfo) { string tempCompressPath = Path.Combine(Directory.GetCurrentDirectory(), _PresentationDir, COMPRESS_TEMP_RELATIVE_DIR); try { if (!Directory.Exists(tempCompressPath)) { Directory.CreateDirectory(tempCompressPath); } tempCompressPath = Path.Combine(tempCompressPath, Guid.NewGuid().ToString()); if (!Directory.Exists(tempCompressPath)) { Directory.CreateDirectory(tempCompressPath); } if (Path.HasExtension(path)) { File.Copy(path, Path.Combine(tempCompressPath, Path.GetFileName(path))); } else { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(path, tempCompressPath); } string compressedPresentationAbsoluteLocation = Path.Combine(Directory.GetCurrentDirectory(), _PresentationDir, Guid.NewGuid().ToString() + ".zip"); new ICSharpCode.SharpZipLib.Zip.FastZip().CreateZip(compressedPresentationAbsoluteLocation, tempCompressPath, true, null, null); presInfo.ZipPresentationAbsoluteLocation = compressedPresentationAbsoluteLocation; } catch (Exception ex) { throw new ApplicationException(String.Format("Во время создания архива с презентацией произошла ошибка: {0}", ex.Message)); } finally { Directory.Delete(tempCompressPath, true); } }
/// <summary> /// Создать файл презентации /// </summary> /// <param name="ppFilePath">Полный путь к файлу с презентацией</param> /// <param name="pptFiledbId">id презентации в БД</param> /// <param name="archivePath">Полный путь к архиву, содержащему презентацию ()</param> public PPTFile(string ppFilePath, long pptFiledbId, string archivePath = null) { Microsoft.Office.Interop.PowerPoint._Application powerPointApp = new Microsoft.Office.Interop.PowerPoint.Application(); Microsoft.Office.Interop.PowerPoint.Presentations ppPresentations = powerPointApp.Presentations; _Presentation = ppPresentations.Open(ppFilePath, MsoTriState.msoCTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); if (archivePath == null) { _PresentationInfo = new PresentationInfo(ppFilePath) { SlidersInfo = new List <SlideInfo>(), DbId = pptFiledbId } } ; else { _PresentationInfo = new PresentationInfo(archivePath) { SlidersInfo = new List <SlideInfo>(), DbId = pptFiledbId } }; }
/// <summary> /// Выложить картинки на FTP /// </summary> /// <param name="presInfo">Информация о презентации</param> public void UploadImages(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("presentation info is not set"); } for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { SlideInfo slideInfo = presInfo.SlidersInfo[index]; //if (!String.IsNullOrEmpty(slideInfo.ImageNameServerSmall)) //{ // UploadImage(slideInfo.ImageNameClientSmall, String.Format("{0}/{1}", SmallImageServerDir, slideInfo.ImageNameServerSmall)); //} CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString())); if (!String.IsNullOrEmpty(slideInfo.ImageNameClientAverage)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "268")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "268"), slideInfo.ImageNameClientAverage), String.Format("{0}/{1}/268/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientAverage)); } if (!String.IsNullOrEmpty(slideInfo.ImageNameClientBig)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "653")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "653"), slideInfo.ImageNameClientBig), String.Format("{0}/{1}/653/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientBig)); } if (UploadImageCompleteCallback != null) { UploadImageCompleteCallback(this, new UploadImageCompliteInfo { TotalImagesCount = presInfo.SlidersInfo.Count, CurrentImageNumber = index + 1 }); } } try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("ftp://{0}/{1}/{2}/{3}", _FTPHost, Path.Combine(_UploadImagesBaseDir, FilesServerDir), presInfo.DbId, presInfo.UrlNews + ".zip")); request.UseBinary = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_UserName, _UserPassword); Stream requestStream = request.GetRequestStream(); using (FileStream sourse = new FileStream(presInfo.ZipPresentationAbsoluteLocation, FileMode.Open)) { int count = 0; int lenght = 0; byte[] buffer = new byte[4096]; while ((count = sourse.Read(buffer, 0, 4096)) != 0) { lenght += count; if (OnUploadPresentationBlockCallbak != null) { OnUploadPresentationBlockCallbak(this, new UploadPresentationBlockInfo { PercentProgress = (int)(lenght * 100 / sourse.Length) }); } requestStream.Write(buffer, 0, count); } requestStream.Close(); } File.Delete(presInfo.ZipPresentationAbsoluteLocation); } catch (Exception ex) { throw new Exception(String.Format("Во время загрузки файла с презентацией {0} на сервер, возникла ошибка: {1}", presInfo.ServerFileName, ex.Message)); } }
private void PutDataToMainTable(PresentationInfo presInfo) { if (presInfo == null) throw new ArgumentNullException("presInfo"); #region Создание таблицы main, если это необходимо try { { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"CREATE TABLE IF NOT EXISTS `{0}` ( `id` MEDIUMINT NOT NULL, `url_news` VARCHAR(300) NOT NULL, `nazvanie` VARCHAR(300) NULL, `category` VARCHAR(300) NOT NULL, `iframe` MEDIUMTEXT NULL, `url_dowload` TEXT(1000) NOT NULL, `lastSmallImageIndex` INT NULL, UNIQUE KEY (lastSmallImageIndex, id) ) CHARSET={1}", SecurityElement.Escape(_MAIN_TABLE_NAME), TABLE_CHARSET); command.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception(String.Format("Во время создания таблицы 'main' произошла ошибка: {1}", ex.Message)); } #endregion #region Получаю данные из таблицы, необходимые для доформирования информации о презентации #region Получаю информацию о предыдущей презентации try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format("SELECT * FROM `{0}` ORDER BY id DESC LIMIT 1", _MAIN_TABLE_NAME); var reader = command.ExecuteReader(); int lastPresentationId = 0, lastSmallImageIndex = 0, lastAverageImageIndex = 0, lastBigImageIndex = 0; if (reader.HasRows) { reader.Read(); Int32.TryParse(reader.GetString("lastSmallImageIndex"), out lastSmallImageIndex); Int32.TryParse(reader.GetString("id"), out lastPresentationId); } reader.Close(); presInfo.DbId = ++lastPresentationId; presInfo.SlidersInfo.ForEach(info => { if (!String.IsNullOrEmpty(info.ImageNameClientBig)) info.ImageNameServerBig = ++lastBigImageIndex + ".jpg"; if (!String.IsNullOrEmpty(info.ImageNameClientAverage)) info.ImageNameServerAverage = ++lastAverageImageIndex + ".jpg"; if (!String.IsNullOrEmpty(info.ImageNameClientSmall)) info.ImageNameServerSmall = ++lastSmallImageIndex + ".png"; }); presInfo.LastImageSmallIndex = lastSmallImageIndex; } catch (Exception ex) { throw new Exception(String.Format("При получении данных из таблицы {0}, необходимых для формирования информации по экспорту новой презентации, произошла ошибка: {1}", _MAIN_TABLE_NAME, ex.Message)); } #endregion #region Формирую уникальный url_news try { int coincidenceCount = 0; string newNameAsTranslit; bool isNeedNextLoop = true; do { if (coincidenceCount == 0) newNameAsTranslit = presInfo.NameAsTranslit; else newNameAsTranslit = presInfo.NameAsTranslit + coincidenceCount; MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format("SELECT id FROM {0} WHERE url_news='{1}'", _MAIN_TABLE_NAME, newNameAsTranslit); using (var reader = command.ExecuteReader()) { if (reader.HasRows) coincidenceCount++; else isNeedNextLoop = false; } } while (isNeedNextLoop); presInfo.NameAsTranslit = newNameAsTranslit; } catch (Exception ex) { throw new Exception(String.Format("При формировании уникального url_new произошла ошибка: {0}", ex.Message)); } #endregion #endregion try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"INSERT INTO `{7}` (`id`, `url_news`, `nazvanie`, `category`, `iframe`, `url_dowload`, `lastSmallImageIndex`) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", presInfo.DbId, SecurityElement.Escape(presInfo.UrlNews), SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(presInfo.Categorie.ToString().Unidecode()), SecurityElement.Escape(FormatIframeBDColumn(presInfo)), SecurityElement.Escape(presInfo.UrlDownload), presInfo.LastImageSmallIndex, SecurityElement.Escape(_MAIN_TABLE_NAME)); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время заполнения таблицы 'main' презентацией '{0}' произошла ошибка: {1}", presInfo.Name, ex.Message)); } }
private void ZipFileOrDirectory(string path, PresentationInfo presInfo) { string tempCompressPath = Path.Combine(Directory.GetCurrentDirectory(), _PresentationDir, COMPRESS_TEMP_RELATIVE_DIR); try { if (!Directory.Exists(tempCompressPath)) Directory.CreateDirectory(tempCompressPath); tempCompressPath = Path.Combine(tempCompressPath, Guid.NewGuid().ToString()); if (!Directory.Exists(tempCompressPath)) Directory.CreateDirectory(tempCompressPath); if (Path.HasExtension(path)) File.Copy(path, Path.Combine(tempCompressPath, Path.GetFileName(path))); else Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(path, tempCompressPath); string compressedPresentationAbsoluteLocation = Path.Combine(Directory.GetCurrentDirectory(), _PresentationDir, Guid.NewGuid().ToString() + ".zip"); new ICSharpCode.SharpZipLib.Zip.FastZip().CreateZip(compressedPresentationAbsoluteLocation, tempCompressPath, true, null, null); presInfo.ZipPresentationAbsoluteLocation = compressedPresentationAbsoluteLocation; } catch (Exception ex) { throw new ApplicationException(String.Format("Во время создания архива с презентацией произошла ошибка: {0}", ex.Message)); } finally { Directory.Delete(tempCompressPath, true); } }
/// <summary> /// Выложить данные на сервер /// </summary> /// <param name="presInfo">Информация о презентации</param> public override void PutDataOnServer(PresentationInfo presInfo) { if (presInfo == null) throw new ArgumentNullException("информация о презентации должна быть заполнена"); // Тут важен порядок. Сперва в main, потом в конкретную таблицу, т.к. при добавлении в main определфется Id презентации PutDataToMainTable(presInfo); PutDataToConcretePresentationTable(presInfo); }
/// <summary> /// Создать файл презентации /// </summary> /// <param name="ppFilePath">Полный путь к файлу с презентацией</param> /// <param name="pptFiledbId">id презентации в БД</param> /// <param name="archivePath">Полный путь к архиву, содержащему презентацию ()</param> public PPTFile(string ppFilePath, long pptFiledbId, string archivePath = null) { Microsoft.Office.Interop.PowerPoint._Application powerPointApp = new Microsoft.Office.Interop.PowerPoint.Application(); Microsoft.Office.Interop.PowerPoint.Presentations ppPresentations = powerPointApp.Presentations; _Presentation = ppPresentations.Open(ppFilePath, MsoTriState.msoCTrue, MsoTriState.msoFalse, MsoTriState.msoFalse); if (archivePath == null) _PresentationInfo = new PresentationInfo(ppFilePath) { SlidersInfo = new List<SlideInfo>(), DbId = pptFiledbId }; else _PresentationInfo = new PresentationInfo(archivePath) { SlidersInfo = new List<SlideInfo>(), DbId = pptFiledbId }; }
private string FormContentDbColumn(PresentationInfo presInfo) { string result = null; for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { string className = index == 0 ? "es" : "as"; result += String.Format("<tr>" + "<td class='{0}' colspan='2'>Слайд №{1}</td>" + "</tr>" + "<tr>" + "<td class='sludes'><img src='/{2}/{3}/225/{4}' /></td>" + " <td class='textaes'>{5}</td>" + "</tr>", className, (index + 1), FTP.AverageAndBigImageServerDir, presInfo.DbId, presInfo.SlidersInfo[index].ImageNameServerAverage, presInfo.SlidersInfo[index].Text); } return result; }
private void PutDataToConcretePresentationTable(PresentationInfo presInfo) { if (presInfo == null) throw new ArgumentNullException("presInfo"); #region Создаю конкретную таблицу, если она еще не создана try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"CREATE TABLE IF NOT EXISTS `{0}` ( `id` MEDIUMINT NOT NULL AUTO_INCREMENT, `url_news` VARCHAR(200) NOT NULL, `title` VARCHAR(200) NULL, `nazvanie` VARCHAR(200) NOT NULL, `slider` TEXT NULL, `url_dowload` TEXT(1000) NOT NULL, `size` FLOAT NOT NULL, `content` TEXT NULL, `iframe` INT NOT NULL, `random` TEXT NULL, `poxpres` TEXT NULL, PRIMARY KEY (id) ) CHARSET={1}", SecurityElement.Escape(presInfo.Categorie.ToString()), TABLE_CHARSET); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время создания таблицы '{0}' произошла ошибка: {1}", presInfo.NameAsTranslit, ex.Message)); } #endregion try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(new System.Globalization.CultureInfo("en-GB"), @" INSERT INTO `{8}` (`url_news`, `title`, `nazvanie`, `slider`, `url_dowload`, `size`, `content`, `iframe`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', {5:0.00}, '{6}', '{7}') ", SecurityElement.Escape(presInfo.UrlNews), SecurityElement.Escape(presInfo.Title), SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(FormatIframeBDColumn(presInfo)), SecurityElement.Escape(presInfo.UrlDownload), Convert.ToSingle(presInfo.FileSize / 1024 / 1024, System.Globalization.CultureInfo.InvariantCulture), SecurityElement.Escape(FormContentDbColumn(presInfo)), presInfo.DbId, SecurityElement.Escape(presInfo.Categorie.ToString())); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время заполнения таблицы 'main' презентацией '{0}' произошла ошибка: {1}", presInfo.Name, ex.Message)); } }
public SlideInfo(PresentationInfo presInfo) { if (presInfo == null) throw new ArgumentNullException("presInfo"); _PresentationInfo = presInfo; }
public abstract void PutDataOnServer(PresentationInfo presInfo);
public override void PutDataOnServer(PresentationInfo presInfo) { #region Заполнение основной таблицы try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(new System.Globalization.CultureInfo("en-GB"), @" UPDATE `{6}` SET `naz`='{0}', `title`='{1}', `size`='{2:0.00}', `slides`='{3}', `content`='{4}', `login`='{5}', `url`='{8}', `cat`='{9}', `like`='0', `count`='1' WHERE `id`='{7}' ", SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(presInfo.Title), Convert.ToSingle(presInfo.FileSize / 1024 / 1024, System.Globalization.CultureInfo.InvariantCulture), SecurityElement.Escape(presInfo.SlidersInfo.Count.ToString()), SecurityElement.Escape(FormContentDbColumn(presInfo)), SecurityElement.Escape(presInfo.Login), SecurityElement.Escape(_MainTableName), SecurityElement.Escape(presInfo.DbId.ToString()), SecurityElement.Escape(presInfo.UrlNews), SecurityElement.Escape(presInfo.Categorie.Key != "NA" ? presInfo.Categorie.Key : null)); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время заполнения основной таблицы 'презентации '{0}' произошла непредвиденная ошибка: {1}", _MainTableName, ex.Message)); } #endregion #region Заполнение таблицы категории if (presInfo.Categorie.Key != "NA") { CreateCategoryTable(presInfo.Categorie.Key); try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(new System.Globalization.CultureInfo("en-GB"), @" INSERT INTO `{6}` (`naz`, `title`, `size`, `slides`, `content`, `login`, `url`, `id`, `like`, `count`) VALUES('{0}', '{1}', '{2:0.00}', '{3}', '{4}', '{5}', '{8}', '{7}', '0', '1') ", SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(presInfo.Title), Convert.ToSingle(presInfo.FileSize / 1024 / 1024, System.Globalization.CultureInfo.InvariantCulture), SecurityElement.Escape(presInfo.SlidersInfo.Count.ToString()), SecurityElement.Escape(FormContentDbColumn(presInfo)), SecurityElement.Escape(presInfo.Login), SecurityElement.Escape(presInfo.Categorie.Key), // Table name SecurityElement.Escape(presInfo.DbId.ToString()), SecurityElement.Escape(presInfo.UrlNews)); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception( String.Format( "Во время заполнения таблицы категории презентации '{0}' произошла непредвиденная ошибка: {1}", presInfo.Categorie.Key, ex.Message)); } } #endregion }
/// <summary> /// Выложить картинки на FTP /// </summary> /// <param name="presInfo">Информация о презентации</param> public void UploadImages(PresentationInfo presInfo) { if (presInfo == null) throw new ArgumentNullException("presentation info is not set"); for (int index = 0; index < presInfo.SlidersInfo.Count; index++) { SlideInfo slideInfo = presInfo.SlidersInfo[index]; //if (!String.IsNullOrEmpty(slideInfo.ImageNameServerSmall)) //{ // UploadImage(slideInfo.ImageNameClientSmall, String.Format("{0}/{1}", SmallImageServerDir, slideInfo.ImageNameServerSmall)); //} CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString())); if (!String.IsNullOrEmpty(slideInfo.ImageNameClientAverage)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "268")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "268"), slideInfo.ImageNameClientAverage), String.Format("{0}/{1}/268/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientAverage)); } if (!String.IsNullOrEmpty(slideInfo.ImageNameClientBig)) { CreateFtpFolder(Path.Combine(_UploadImagesBaseDir, FilesServerDir, presInfo.DbId.ToString(), "653")); UploadImage( Path.Combine(SlideInfo.GetLocalImageDirectoryAbsolutePath(presInfo.DbId, "653"), slideInfo.ImageNameClientBig), String.Format("{0}/{1}/653/{2}", FilesServerDir, presInfo.DbId, slideInfo.ImageNameClientBig)); } if (UploadImageCompleteCallback != null) UploadImageCompleteCallback(this, new UploadImageCompliteInfo { TotalImagesCount = presInfo.SlidersInfo.Count, CurrentImageNumber = index + 1 }); } try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("ftp://{0}/{1}/{2}/{3}", _FTPHost, Path.Combine(_UploadImagesBaseDir, FilesServerDir), presInfo.DbId, presInfo.UrlNews + ".zip")); request.UseBinary = true; request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_UserName, _UserPassword); Stream requestStream = request.GetRequestStream(); using (FileStream sourse = new FileStream(presInfo.ZipPresentationAbsoluteLocation, FileMode.Open)) { int count = 0; int lenght = 0; byte[] buffer = new byte[4096]; while ((count = sourse.Read(buffer, 0, 4096)) != 0) { lenght += count; if (OnUploadPresentationBlockCallbak != null) OnUploadPresentationBlockCallbak(this, new UploadPresentationBlockInfo { PercentProgress = (int)(lenght * 100 / sourse.Length) }); requestStream.Write(buffer, 0, count); } requestStream.Close(); } File.Delete(presInfo.ZipPresentationAbsoluteLocation); } catch (Exception ex) { throw new Exception(String.Format("Во время загрузки файла с презентацией {0} на сервер, возникла ошибка: {1}", presInfo.ServerFileName, ex.Message)); } }
private void PutDataToMainTable(PresentationInfo presInfo) { if (presInfo == null) { throw new ArgumentNullException("presInfo"); } #region Создание таблицы main, если это необходимо try { { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"CREATE TABLE IF NOT EXISTS `{0}` ( `id` MEDIUMINT NOT NULL, `url_news` VARCHAR(300) NOT NULL, `nazvanie` VARCHAR(300) NULL, `category` VARCHAR(300) NOT NULL, `iframe` MEDIUMTEXT NULL, `url_dowload` TEXT(1000) NOT NULL, `lastSmallImageIndex` INT NULL, UNIQUE KEY (lastSmallImageIndex, id) ) CHARSET={1}", SecurityElement.Escape(_MAIN_TABLE_NAME), TABLE_CHARSET); command.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception(String.Format("Во время создания таблицы 'main' произошла ошибка: {1}", ex.Message)); } #endregion #region Получаю данные из таблицы, необходимые для доформирования информации о презентации #region Получаю информацию о предыдущей презентации try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format("SELECT * FROM `{0}` ORDER BY id DESC LIMIT 1", _MAIN_TABLE_NAME); var reader = command.ExecuteReader(); int lastPresentationId = 0, lastSmallImageIndex = 0, lastAverageImageIndex = 0, lastBigImageIndex = 0; if (reader.HasRows) { reader.Read(); Int32.TryParse(reader.GetString("lastSmallImageIndex"), out lastSmallImageIndex); Int32.TryParse(reader.GetString("id"), out lastPresentationId); } reader.Close(); presInfo.DbId = ++lastPresentationId; presInfo.SlidersInfo.ForEach(info => { if (!String.IsNullOrEmpty(info.ImageNameClientBig)) { info.ImageNameServerBig = ++lastBigImageIndex + ".jpg"; } if (!String.IsNullOrEmpty(info.ImageNameClientAverage)) { info.ImageNameServerAverage = ++lastAverageImageIndex + ".jpg"; } if (!String.IsNullOrEmpty(info.ImageNameClientSmall)) { info.ImageNameServerSmall = ++lastSmallImageIndex + ".png"; } }); presInfo.LastImageSmallIndex = lastSmallImageIndex; } catch (Exception ex) { throw new Exception(String.Format("При получении данных из таблицы {0}, необходимых для формирования информации по экспорту новой презентации, произошла ошибка: {1}", _MAIN_TABLE_NAME, ex.Message)); } #endregion #region Формирую уникальный url_news try { int coincidenceCount = 0; string newNameAsTranslit; bool isNeedNextLoop = true; do { if (coincidenceCount == 0) { newNameAsTranslit = presInfo.NameAsTranslit; } else { newNameAsTranslit = presInfo.NameAsTranslit + coincidenceCount; } MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format("SELECT id FROM {0} WHERE url_news='{1}'", _MAIN_TABLE_NAME, newNameAsTranslit); using (var reader = command.ExecuteReader()) { if (reader.HasRows) { coincidenceCount++; } else { isNeedNextLoop = false; } } } while (isNeedNextLoop); presInfo.NameAsTranslit = newNameAsTranslit; } catch (Exception ex) { throw new Exception(String.Format("При формировании уникального url_new произошла ошибка: {0}", ex.Message)); } #endregion #endregion try { MySqlCommand command = _MySqlConnection.CreateCommand(); command.CommandText = String.Format(@"INSERT INTO `{7}` (`id`, `url_news`, `nazvanie`, `category`, `iframe`, `url_dowload`, `lastSmallImageIndex`) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}')", presInfo.DbId, SecurityElement.Escape(presInfo.UrlNews), SecurityElement.Escape(presInfo.Name), SecurityElement.Escape(presInfo.Categorie.ToString().Unidecode()), SecurityElement.Escape(FormatIframeBDColumn(presInfo)), SecurityElement.Escape(presInfo.UrlDownload), presInfo.LastImageSmallIndex, SecurityElement.Escape(_MAIN_TABLE_NAME)); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(String.Format("Во время заполнения таблицы 'main' презентацией '{0}' произошла ошибка: {1}", presInfo.Name, ex.Message)); } }
/// <summary> /// Изъять информацию из презентации /// </summary> /// <param name="ppFilePath">Полный путь к презентации</param> /// <returns>Информация о презентации</returns> public PresentationInfo ExtractInfo(string ppFilePath, ILastInsertedPPTInfoId pptidInfo) { PresentationInfo presInfo = null; long pptCurrentFileId = pptidInfo.GetCurrentPresentationIndex(); if (SupportedArchiveFormats.Contains(Path.GetExtension(ppFilePath))) { ExtractArchive(ppFilePath); List <string> allDirectories = Directory.GetDirectories(_ExtractDir).ToList(); allDirectories.Add(_ExtractDir); bool isFileFound = false; foreach (string dir in allDirectories) { foreach (string filePath in Directory.GetFiles(dir)) { if (SupportedPowerPointFileFormats.Contains(Path.GetExtension(filePath))) { PPTFile pptFile = new PPTFile(filePath, pptCurrentFileId, ppFilePath); if (ParseSlideCompleteCallback != null) { pptFile.ParseSlideComplite += ParseSlideCompleteCallback; } presInfo = pptFile.ParsePreesentation(); isFileFound = true; if (ParseSlideCompleteCallback != null) { pptFile.ParseSlideComplite -= ParseSlideCompleteCallback; } FileInfo archiveInfo = new FileInfo(ppFilePath); presInfo.FileSize = archiveInfo.Length; break; } } } if (!isFileFound) { _IsErrorExists = true; throw new Exception(String.Format("Файл презентации в архиве не найден\nАрхив был распакован в папку: {0}\nПри следующем запуске программы архив будет удален из временного хранилища", _ExtractDir)); } ZipFileOrDirectory(_ExtractDir, presInfo); } else { PPTFile pptFile = new PPTFile(ppFilePath, pptCurrentFileId); if (ParseSlideCompleteCallback != null) { pptFile.ParseSlideComplite += ParseSlideCompleteCallback; } presInfo = pptFile.ParsePreesentation(); if (ParseSlideCompleteCallback != null) { pptFile.ParseSlideComplite -= ParseSlideCompleteCallback; } FileInfo fileInfo = new FileInfo(ppFilePath); presInfo.FileSize = fileInfo.Length; ZipFileOrDirectory(ppFilePath, presInfo); } return(presInfo); }
private void worker_DoWork(object sender, DoWorkEventArgs e) { WorkerArgument argument = (WorkerArgument)e.Argument; var progressStatus = new ParseProgressStatus { PresentationControl = argument.PresentationControl }; MySQLPresentationTable abstractpresTable = null; PresentationInfo presInfo = null; try { #region Парсинг презентации ((BackgroundWorker)sender).ReportProgress(0, new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Начало парсинга презентации", IsOnlyMessage = true }); using (PPTFiles pptFiles = new PPTFiles()) { #region Получаюданные настройки соединения с БД string dbRemoteHost = null, dbName = null, dbUser = null, dbPassword = null; try { XDocument xmlDBDoc = XDocument.Load("Lib\\FCashProfile.tss"); var XdbRemoteHost = xmlDBDoc.Root.Element(XName.Get("ExportDBInfo")).Element(XName.Get("DBRemoteHost")); dbRemoteHost = XdbRemoteHost.Value; var XdbName = xmlDBDoc.Root.Element(XName.Get("ExportDBInfo")).Element(XName.Get("DBName")); dbName = XdbName.Value; var XdbUser = xmlDBDoc.Root.Element(XName.Get("ExportDBInfo")).Element(XName.Get("DBUser")); dbUser = XdbUser.Value; var XdbPassword = xmlDBDoc.Root.Element(XName.Get("ExportDBInfo")).Element(XName.Get("DBPassword")); dbPassword = XdbPassword.Value; } catch (Exception ex) { throw new Exception( String.Format("Не получилось получить конфигурационные данные из файла конфигурации: {0}", ex.Message)); } //if (!String.IsNullOrEmpty(argument.UrlNews)) // presInfo.UrlNews = argument.UrlNews; if (String.IsNullOrEmpty(dbRemoteHost) || String.IsNullOrEmpty(dbName) || String.IsNullOrEmpty(dbUser)) { throw new Exception( "У вас не заполнена конфигурация соединения с базой данных для экспорта\nПожалуйста заполните ее через настройки"); } MySQLPresentationTable presTable = new MySQLPresentationTable(dbRemoteHost, dbName, dbUser, dbPassword); abstractpresTable = presTable; #endregion pptFiles.ParseSlideCompleteCallback += (object pptFile, SlideCompleteParsingInfo slideParsingInfo) => { ((BackgroundWorker)sender).ReportProgress( (int)((decimal)slideParsingInfo.SlideCurrentNumber / (decimal)slideParsingInfo.SlideTotalNumber * 100), new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Обработка слайдов" }); }; presTable.CreateTable(); presInfo = pptFiles.ExtractInfo(argument.PresentationFullPath, presTable); presInfo.Name = argument.PresentationName; presInfo.Title = argument.PresentationTitle; presInfo.Login = argument.Login; presInfo.Categorie = ((KeyValuePair <string, string>)argument.SelectedItem); } #endregion #region Заливка информации по презентации в БД { ((BackgroundWorker)sender).ReportProgress(0, new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Обновление данных на сервере", IsOnlyMessage = true }); abstractpresTable.PutDataOnServer(presInfo); } #endregion #region Отправка на FTP try { ((BackgroundWorker)sender).ReportProgress(0, new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Подготовка к отправке файлов на FTP", IsOnlyMessage = true }); XDocument xmlFtpDoc = XDocument.Load("Lib\\FCashProfile.tss"); var ftpHost = xmlFtpDoc.Root.Element(XName.Get("ExportFtpInfo")).Element(XName.Get("Host")); var ftpUserName = xmlFtpDoc.Root.Element(XName.Get("ExportFtpInfo")).Element(XName.Get("UserName")); var ftpUserPassword = xmlFtpDoc.Root.Element(XName.Get("ExportFtpInfo")).Element(XName.Get("UserPassword")); var ftpImagesDir = xmlFtpDoc.Root.Element(XName.Get("ExportFtpInfo")).Element(XName.Get("ImagesDir")); FTP ftp = new FTP(ftpHost.Value, ftpUserName.Value, ftpUserPassword.Value, ftpImagesDir.Value); ftp.UploadImageCompleteCallback += (object ftpSender, UploadImageCompliteInfo completeInfo) => { ((BackgroundWorker)sender).ReportProgress( (int)((decimal)completeInfo.CurrentImageNumber / (decimal)completeInfo.TotalImagesCount * 100), new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Загрузка изображений на FTP" }); }; ftp.OnUploadPresentationBlockCallbak += (object ftpSender, UploadPresentationBlockInfo blockInfo) => { ((BackgroundWorker)sender).ReportProgress(blockInfo.PercentProgress, new ParseProgressStatus { PresentationControl = argument.PresentationControl, Message = "Загрузка презентации" }); }; List <string> imageNames = new List <string>(); foreach (var slideInfo in presInfo.SlidersInfo) { if (!String.IsNullOrEmpty(slideInfo.ImageNameClientSmall)) { imageNames.Add(slideInfo.ImageNameClientSmall); } if (!String.IsNullOrEmpty(slideInfo.ImageNameClientAverage)) { imageNames.Add(slideInfo.ImageNameClientAverage); } if (!String.IsNullOrEmpty(slideInfo.ImageNameClientBig)) { imageNames.Add(slideInfo.ImageNameClientBig); } } ftp.UploadImages(presInfo); } catch (Exception ex) { throw new Exception(String.Format("Во время отправки изображений на FTP возникла ошибка: {0}", ex.Message)); } #endregion } catch (Exception ex) { lock (_exceptionLoger) { _exceptionLoger.WriteLog(string.Format(Environment.NewLine + Environment.NewLine + "[{0}] Во время обработки презентации [{1}] произошла ошибка.\r\n Ошибка: {2} \r\nСтек вызова: {3}", DateTime.Now, argument.PresentationName, ex.Message, ex.StackTrace)); } // Удаляю пустую подготовленную строчку для презентации из таблицы if (presInfo != null) { try { abstractpresTable.DeleteFromMainTable((ulong)presInfo.DbId); } catch (Exception ex2) { lock (_exceptionLoger) { _exceptionLoger.WriteLog(string.Format(Environment.NewLine + Environment.NewLine + "[{0}] Во время обработки презентации [{1}] произошла ошибка.\r\n Ошибка: {2} \r\nСтек вызова: {3}", DateTime.Now, argument.PresentationName, ex2.Message, ex2.StackTrace)); } } } progressStatus.IsError = true; } finally { e.Result = progressStatus; } }