コード例 #1
0
 public override DataRow[] GetLikeSources(PriceSource source)
 {
     return(dtSources.Select(String.Format("({0} = '{1}') and ({2} = '{3}') and (ISNULL({4}, '') = '{5}') and (ISNULL({6}, '') = '{7}')",
                                           SourcesTableColumns.colPricePath, source.PricePath,
                                           SourcesTableColumns.colPriceMask, source.PriceMask,
                                           SourcesTableColumns.colHTTPLogin, source.HttpLogin,
                                           SourcesTableColumns.colHTTPPassword, source.HttpPassword)));
 }
コード例 #2
0
 /// <summary>
 /// Проверяет, истек ли интервал, спустя который нужно обращаться к источнику
 /// </summary>
 /// <returns>
 /// true - интервал истек, нужно обратиться
 /// false - интервал еще не истек, не нужно обращаться
 /// </returns>
 public bool IsReadyForDownload(PriceSource source)
 {
     // downloadInterval - в секундах
     if (FailedSources.Contains(source.PriceItemId))
     {
         FailedSources.Remove(source.PriceItemId);
         return(true);
     }
     return(source.IsReadyForDownload());
 }
コード例 #3
0
 public override DataRow[] GetLikeSources(PriceSource source)
 {
     if (String.IsNullOrEmpty(source.PriceMask))
     {
         return(dtSources.Select(String.Format("({0} = {1}) and ({2} is null)",
                                               SourcesTableColumns.colFirmCode, source.FirmCode,
                                               SourcesTableColumns.colPriceMask)));
     }
     return(dtSources.Select(String.Format("({0} = {1}) and ({2} = '{3}')",
                                           SourcesTableColumns.colFirmCode, source.FirmCode,
                                           SourcesTableColumns.colPriceMask, source.PriceMask)));
 }
コード例 #4
0
        protected override void GetFileFromSource(PriceSource source)
        {
            try {
                var pricePath = source.PricePath;
                if (!pricePath.StartsWith(@"http://", StringComparison.OrdinalIgnoreCase))
                {
                    pricePath = @"http://" + pricePath;
                }

                var httpFileName  = source.PriceMask;
                var priceDateTime = source.PriceDateTime;

                if (pricePath[pricePath.Length - 1].ToString() != "/")
                {
                    pricePath += "/";
                }
                var httpUrl           = pricePath + httpFileName;
                var fileLastWriteTime = GetFileDateTime(httpUrl, source.HttpLogin, source.HttpPassword);
                var downloadInterval  = Settings.Default.FileDownloadInterval;
#if DEBUG
                downloadInterval  = -1;
                fileLastWriteTime = DateTime.Now;
#endif
                if ((fileLastWriteTime.CompareTo(priceDateTime) > 0) &&
                    (DateTime.Now.Subtract(fileLastWriteTime).TotalMinutes > downloadInterval))
                {
                    var downFileName = DownHandlerPath + httpFileName;
                    GetFile(httpUrl, downFileName, source.HttpLogin, source.HttpPassword);
                    CurrFileName  = downFileName;
                    CurrPriceDate = fileLastWriteTime;
                }
            }
            catch (Exception e) {
                throw new HttpSourceHandlerException(e);
            }
        }
コード例 #5
0
        protected override void GetFileFromSource(PriceSource source)
        {
            try {
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("Try get file from LAN source. FirmCode = {0}, PriceItemId = {1}", source.FirmCode, source.PriceItemId);
                }
                var pricePath = Path.Combine(Settings.Default.FTPOptBoxPath, source.FirmCode.ToString().PadLeft(3, '0'));
                var files     = Directory.GetFiles(pricePath, source.PriceMask);

                //Сортированный список файлов из директории, подходящих по маске, файл со старшей датой будет первым
                var sortedFileList = new SortedList <DateTime, string>();

                foreach (var file in files)
                {
                    var fileLastWriteTime = File.GetLastWriteTime(file);
                    if (_logger.IsDebugEnabled)
                    {
                        _logger.DebugFormat("File: {0}. LastWriteTime: {1}", file, fileLastWriteTime);
                    }
                    if (DateTime.Now.Subtract(fileLastWriteTime).TotalMinutes > Settings.Default.FileDownloadInterval)
                    {
                        sortedFileList.Add(fileLastWriteTime, file);
                    }
                }
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("SortedList count items {0}", sortedFileList.Count);
                }
                //Если в списке есть файлы, то берем первый и скачиваем
                if (sortedFileList.Count == 0)
                {
                    return;
                }

                var downloadedFileName      = sortedFileList.Values[0];
                var downloadedLastWriteTime = sortedFileList.Keys[0];
                var newFile = DownHandlerPath + Path.GetFileName(downloadedFileName);
                if (_logger.IsDebugEnabled)
                {
                    _logger.DebugFormat("Path: {0}", newFile);
                }
                if (File.Exists(newFile))
                {
                    FileHelper.ClearReadOnly(newFile);
                    File.Delete(newFile);
                }
                FileHelper.ClearReadOnly(downloadedFileName);
                _downloadedFile = downloadedFileName;
                try {
                    if (_logger.IsDebugEnabled)
                    {
                        _logger.DebugFormat("Copying from {0} to {1}", downloadedFileName, newFile);
                    }
                    File.Copy(downloadedFileName, newFile);
                    CurrFileName  = newFile;
                    CurrPriceDate = downloadedLastWriteTime;
                }
                catch (IOException e) {
                    var errorCode       = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    var errorAlreadyWas = ErrorPriceLogging.ErrorMessages.ContainsKey(source.PriceItemId) &&
                                          ErrorPriceLogging.ErrorMessages.ContainsValue(e.ToString());
                    // Проверяем, если это ошибка совместного доступа  к файлу, и эта ошибка уже происходила для этого файла
                    if ((errorCode == 32) && errorAlreadyWas)
                    {
                        throw;
                    }
                    else if ((errorCode == 32) && !errorAlreadyWas)
                    {
                        // Если для данного файла ошибка еще не происходила, добавляем ее в словарь
                        ErrorPriceLogging.ErrorMessages.Add(CurrPriceItemId, e.ToString());
                    }
                }
                // Если дошли сюда, значит файл успешно забран и можно удалить
                // сообщения об ошибках для этого файла
                if (ErrorPriceLogging.ErrorMessages.ContainsKey(CurrPriceItemId))
                {
                    ErrorPriceLogging.ErrorMessages.Remove(CurrPriceItemId);
                }
            }
            catch (Exception e) {
                throw new LanSourceHandlerException(e);
            }
        }
コード例 #6
0
        public override void ProcessData()
        {
            //набор строк похожих источников
            FillSourcesTable();
            while (dtSources.Rows.Count > 0)
            {
                DataRow[] drLS          = null;
                var       currentSource = dtSources.Rows[0];
                var       priceSource   = new PriceSource(currentSource);
                if (!IsReadyForDownload(priceSource))
                {
                    currentSource.Delete();
                    dtSources.AcceptChanges();
                    continue;
                }
                try {
                    drLS = GetLikeSources(priceSource);
                    try {
                        CurrFileName = String.Empty;
                        GetFileFromSource(priceSource);
                        priceSource.UpdateLastCheck();
                    }
                    catch (PathSourceHandlerException pathException) {
                        FailedSources.Add(priceSource.PriceItemId);
                        DownloadLogEntity.Log(priceSource.SourceTypeId, priceSource.PriceItemId, pathException.ToString(), pathException.ErrorMessage);
                    }
                    catch (Exception e) {
                        FailedSources.Add(priceSource.PriceItemId);
                        DownloadLogEntity.Log(priceSource.SourceTypeId, priceSource.PriceItemId, e.ToString());
                    }

                    if (!String.IsNullOrEmpty(CurrFileName))
                    {
                        var correctArchive = FileHelper.ProcessArchiveIfNeeded(CurrFileName, ExtrDirSuffix, priceSource.ArchivePassword);
                        foreach (var drS in drLS)
                        {
                            SetCurrentPriceCode(drS);
                            string extractFile = null;
                            try {
                                if (!correctArchive)
                                {
                                    throw new PricePreprocessingException("Не удалось распаковать файл '" + Path.GetFileName(CurrFileName) + "'. Файл поврежден", CurrFileName);
                                }

                                if (!ProcessPriceFile(CurrFileName, out extractFile, priceSource.SourceTypeId))
                                {
                                    throw new PricePreprocessingException("Не удалось обработать файл '" + Path.GetFileName(CurrFileName) + "'", CurrFileName);
                                }

                                LogDownloadedPrice(priceSource.SourceTypeId, Path.GetFileName(CurrFileName), extractFile);
                                FileProcessed();
                            }
                            catch (PricePreprocessingException e) {
                                LogDownloaderFail(priceSource.SourceTypeId, e.Message, e.FileName);
                                FileProcessed();
                            }
                            catch (Exception e) {
                                LogDownloaderFail(priceSource.SourceTypeId, e.Message, extractFile);
                            }
                            finally {
                                drS.Delete();
                            }
                        }
                        Cleanup();
                    }
                    else
                    {
                        foreach (var drDel in drLS)
                        {
                            drDel.Delete();
                        }
                    }
                }
                catch (Exception ex) {
                    var error = String.Empty;
                    if (drLS != null && drLS.Length > 1)
                    {
                        error += String.Join(", ", drLS.Select(r => r[SourcesTableColumns.colPriceCode].ToString()).ToArray());
                        drLS.Each(r => FileHelper.Safe(r.Delete));
                        error = "Источники : " + error;
                    }
                    else
                    {
                        error = String.Format("Источник : {0}", currentSource[SourcesTableColumns.colPriceCode]);
                        FileHelper.Safe(currentSource.Delete);
                    }
                    Log(ex, error);
                }
                finally {
                    FileHelper.Safe(() => dtSources.AcceptChanges());
                }
            }
        }
コード例 #7
0
 /// <summary>
 /// Получить прайс-листы, у которых истоники совпадают с первым в списке
 /// </summary>
 public abstract DataRow[] GetLikeSources(PriceSource currentSource);
コード例 #8
0
 /// <summary>
 /// Получает файл из источника, взятого из таблицы первым
 /// </summary>
 protected abstract void GetFileFromSource(PriceSource row);