Пример #1
0
        public void MarcRecord_FM_1()
        {
            MarcRecord record = _GetRecord();

            Assert.AreEqual("Иванов", record.FM(700, 'a'));
            Assert.AreEqual("Первое примечание", record.FM(300));
        }
Пример #2
0
        private static int _GetYear
        (
            [NotNull] MarcRecord record
        )
        {
            string result = record.FM(210, 'd');

            if (string.IsNullOrEmpty(result))
            {
                result = record.FM(461, 'h');
            }
            if (string.IsNullOrEmpty(result))
            {
                result = record.FM(461, 'z');
            }
            if (string.IsNullOrEmpty(result))
            {
                result = record.FM(934);
            }
            if (string.IsNullOrEmpty(result))
            {
                return(0);
            }

            Match match = Regex.Match(result, @"\d{4}");

            if (match.Success)
            {
                result = match.Value;
            }
            return(result.SafeToInt32());
        }
Пример #3
0
        private void _barcodeBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }

            _browser.DocumentText = string.Empty;
            _lines = null;

            string barcode = _barcodeBox.Text.Trim();

            if (string.IsNullOrEmpty(barcode))
            {
                return;
            }

            _barcodeBox.Clear();

            try
            {
                string connectionString = CM.AppSettings["connectionString"];
                using (IrbisConnection connection = new IrbisConnection(connectionString))
                {
                    MarcRecord record = connection.SearchReadOneRecord("\"IN={0}\"", barcode);
                    if (ReferenceEquals(record, null))
                    {
                        _browser.DocumentText = "Не найдена книга";
                        _barcodeBox.Focus();
                        return;
                    }

                    string formatted = connection.FormatRecord("@", record.Mfn);
                    _browser.DocumentText = formatted;

                    string firstLine = record.FM(906), secondLine = record.FM(908);
                    if (string.IsNullOrEmpty(firstLine))
                    {
                        _browser.DocumentText = "Не введен систематический шифр (поле 906)";
                        _barcodeBox.Focus();
                        return;
                    }
                    if (string.IsNullOrEmpty(secondLine))
                    {
                        _browser.DocumentText = "Не введен авторский знак (поле 908)";
                        _barcodeBox.Focus();
                        return;
                    }

                    _lines = new[] { firstLine, secondLine };
                }
            }
            catch (Exception exception)
            {
                _browser.DocumentText = exception.ToString();
            }
        }
Пример #4
0
        private static string GetYear
        (
            [NotNull] MarcRecord record
        )
        {
            Code.NotNull(record, "record");

            string result = record.FM("210", 'd')
                            ?? record.FM("934");

            return(result);
        }
Пример #5
0
        static void ProcessRecord
        (
            [NotNull] MarcRecord record
        )
        {
            string worklist = record.FM(920);

            if (worklist != "PAZK" && worklist != "SPEC")
            {
                return;
            }

            int count = record.FM(999).SafeToInt32();

            string     formatted = formatter.FormatRecord(record);
            List <int> words     = new List <int>();

            foreach (Match match in regex.Matches(formatted))
            {
                string word = match.Value.ToUpperInvariant();
                if (word.Length >= 3 && !stopwords.IsStopWord(word))
                {
                    int id;
                    if (!dictionary.TryGetValue(word, out id))
                    {
                        id = ++lastId;
                        dictionary.Add(word, id);
                    }

                    if (!words.Contains(id))
                    {
                        words.Add(id);
                    }
                }
            }

            if (words.Count != 0)
            {
                goodRecords++;
                if (words.Count > longest)
                {
                    longest = words.Count;
                }
                BookData data = new BookData
                {
                    Count = count,
                    Mfn   = record.Mfn,
                    Words = words.ToArray()
                };
                data.SaveToStream(writer);
            }
        }
Пример #6
0
        static void ProcessNumber
        (
            string number
        )
        {
            int[] found = irbis.ExactSearch(string.Format
                                            (
                                                "IN={0}",
                                                number
                                            ));
            if (found.Length == 0)
            {
                return;
            }
            int mfn = found[0];

            irbis.ReadRecord(mfn);
            NativeRecord native      = irbis.GetRecord();
            MarcRecord   record      = native.ToMarcRecord();
            string       description = irbis.FormatRecord(mfn);
            int          count       = record.FM(999).SafeToInt32();

            Console.WriteLine
            (
                "{0}\t{1}\t{2}",
                number,
                count,
                description
            );
        }
Пример #7
0
        public static MagazineInfo FromRecord
        (
            MarcRecord record
        )
        {
            int marsCode = NumericUtility.ParseInt32(CM.AppSettings["mars-code"]);
            int marsFlag = NumericUtility.ParseInt32(CM.AppSettings["mars-flag"]);

            MagazineInfo result = new MagazineInfo
            {
                Title    = record.FM(200, 'a'),
                Index    = record.FM(903),
                MarsCode = record.FM(marsCode),
                Flag     = record.FM(marsFlag),
                Mfn      = record.Mfn
            };

            return(result);
        }
Пример #8
0
        private static string GetPrice
        (
            [NotNull] VisitInfo debt,
            [NotNull] MarcRecord bookRecord
        )
        {
            Code.NotNull(debt, "debt");

            string inventory = debt.Inventory;
            string barcode   = debt.Barcode;

            RecordField[] fields = bookRecord.Fields
                                   .GetField("910");

            string result = null;

            foreach (RecordField field in fields)
            {
                ExemplarInfo exemplar = ExemplarInfo.Parse(field);

                if (!string.IsNullOrEmpty(inventory))
                {
                    if (exemplar.Number.SameString(inventory))
                    {
                        if (!string.IsNullOrEmpty(barcode))
                        {
                            if (exemplar.Barcode.SameString(barcode))
                            {
                                result = exemplar.Price;
                                break;
                            }
                        }
                        else
                        {
                            result = exemplar.Price;
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                result = bookRecord.FM("10", 'd');
            }

            return(result);
        }
Пример #9
0
        static void ProcessRecord
        (
            MarcRecord record
        )
        {
            string countText = record.FM(999);

            if (!string.IsNullOrEmpty(countText))
            {
                int count;
                if (int.TryParse(countText, out count))
                {
                    list.Add(new Pair <int, int>(record.Mfn, count));
                }
            }
        }
Пример #10
0
        static void ProcessRecord
        (
            [NotNull] MarcRecord record
        )
        {
            string index = record.FM(903);

            if (string.IsNullOrEmpty(index))
            {
                return;
            }

            if (_indexes.ContainsKey(index))
            {
                Console.WriteLine("Repeating index: {0}", index);
                return;
            }

            _indexes.Add(index, false);

            string description = _GetDescription(record);

            if (string.IsNullOrEmpty(description))
            {
                return;
            }

            description = description.Limit(500);

            IrbisData data = new IrbisData
            {
                Index       = index.Limit(32),
                Description = description,
                Heading     = _GetHeading(record),
                Title       = _GetTitle(record),
                Author      = _GetAuthors(record),
                Count       = _GetExemplars(record),
                Year        = _GetYear(record),
                Link        = _GetLink(record),
                Type        = _GetType(record)
            };

            _database.Insert(data);
            Console.WriteLine("[{0}] {1}", record.Mfn, data.Description);
        }
Пример #11
0
        static void ProcessRecord
        (
            [NotNull] MarcRecord record
        )
        {
            string index = record.FM(903);

            if (string.IsNullOrEmpty(index))
            {
                return;
            }

            string description = _irbisConnection.FormatRecord("@sbrief_istu", record.Mfn);

            //string description = _GetDescription(record);

            if (string.IsNullOrEmpty(description))
            {
                return;
            }

            description = description.Limit(500);

            IrbisData data = new IrbisData
            {
                Index       = index.Limit(32),
                Description = description,
                Heading     = _GetHeading(record),
                Title       = _GetTitle(record),
                Author      = _GetAuthors(record),
                Count       = _GetExemplars(record),
                Year        = _GetYear(record),
                Link        = _GetLink(record),
                Type        = _GetType(record)
            };

            _database.Insert(data);
            Console.WriteLine("[{0}] {1}", record.Mfn, data.Description);
        }
Пример #12
0
        private void _HandleRfid
        (
            string rfid
        )
        {
            _currentRecord   = null;
            _currentExemplar = null;
            _SetHtml(string.Empty);

            _logBox.Output.WriteLine
            (
                "Считана метка: {0}",
                rfid
            );

            string prefix = CM.AppSettings["prefix"];

            MarcRecord[] found = _client.SearchRead
                                 (
                "\"{0}{1}\"",
                prefix,
                rfid
                                 );
            if (found.Length == 0)
            {
                _SetHtml
                (
                    "Не найдена метка {0}",
                    rfid
                );
                return;
            }
            if (found.Length != 1)
            {
                _SetHtml
                (
                    "Много записей для метки {0}",
                    rfid
                );
                return;
            }

            MarcRecord record = found[0];

            RecordField[] fields = record.Fields
                                   .GetField(910)
                                   .GetField('h', rfid);

            if (fields.Length == 0)
            {
                _SetHtml
                (
                    "Не найдено поле с меткой {0}",
                    rfid
                );
                return;
            }
            if (fields.Length != 1)
            {
                _SetHtml
                (
                    "Много полей с меткой {0}",
                    rfid
                );
                return;
            }

            ExemplarInfo exemplar = ExemplarInfo.Parse(fields[0]);

            exemplar.UserData = fields[0];

            StringBuilder diagnosis = new StringBuilder();

            diagnosis.AppendFormat
            (
                "{0} =&gt; <b>{1}</b><br/>",
                rfid,
                exemplar.Number
            );
            if (!string.IsNullOrEmpty(exemplar.RealPlace))
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Экземпляр уже был проверен "
                    + "в фонде</font> <b>{0}</b> ({1})<br/>",
                    exemplar.RealPlace,
                    exemplar.CheckedDate
                );
            }
            if (exemplar.Status != "0")
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Неверный статус "
                    + "экземпляра: </font><b>{0}</b><br/>",
                    exemplar.Status
                );
            }
            if (!exemplar.Place.SameString(CurrentFond))
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Неверное место хранения "
                    + "экземпляра: </font><b>{0}</b><br/>",
                    exemplar.Place
                );
            }
            string currentShelf = CurrentShelf;

            if (!string.IsNullOrEmpty(currentShelf))
            {
                string[] items = currentShelf
                                 .Split(',', ';')
                                 .Select(item => item.Trim())
                                 .NonEmptyLines()
                                 .Select(item => item.ToUpperInvariant())
                                 .ToArray();

                string shelf = record.FM(906);
                if (string.IsNullOrEmpty(shelf))
                {
                    diagnosis.AppendFormat
                    (
                        "<font color='red'>Для книги не указан "
                        + "расстановочный шифр</font><br/>"
                    );
                }
                else if (items.Length != 0)
                {
                    shelf = shelf.ToUpperInvariant();
                    bool good = false;
                    foreach (string item in items)
                    {
                        if (shelf.StartsWith(item))
                        {
                            good = true;
                            break;
                        }
                    }
                    if (!good)
                    {
                        diagnosis.AppendFormat
                        (
                            "<font color='red'>Неверный шифр: "
                            + "</font><b>{0}</b><br/>",
                            shelf
                        );
                    }
                }
            }
            string fromNumber = FromNumber,
                   toNumber   = ToNumber;

            if (!string.IsNullOrEmpty(fromNumber) &&
                !string.IsNullOrEmpty(toNumber))
            {
                string number = exemplar.Number;
                if (!string.IsNullOrEmpty(number))
                {
                    NumberText fn = fromNumber,
                               tn = toNumber,
                               n  = number;
                    if (fn > n || tn < n)
                    {
                        diagnosis.AppendFormat
                        (
                            "<font color='red'>Номер за пределами "
                            + "интервала</font>: <b>{0}</b><br/>",
                            number
                        );
                    }
                }
            }
            diagnosis.AppendLine("<br/>");

            string cardFormat       = CM.AppSettings["card-format"];
            string briefDescription = _client.FormatRecord
                                      (
                cardFormat,
                record.Mfn
                                      ).Trim();

            diagnosis.Append(briefDescription);
            record.UserData = briefDescription;

            _SetHtml
            (
                "{0}",
                diagnosis.ToString()
            );

            _currentRecord   = record;
            _currentExemplar = exemplar;

            //if (_emulation != null)
            //{
            //    _okButton_Click
            //        (
            //            this,
            //            EventArgs.Empty
            //        );
            //}
        }
Пример #13
0
        private static void ProcessRecord
        (
            int mfn
        )
        {
            connection.Database = MainDatabase;
            MarcRecord mainRecord = connection.ReadRecord(mfn);
            string     linkValue  = mainRecord.FM(LinkTag);

            connection.Database = BackupDatabase;
            MarcRecord backupRecord = connection.SearchReadOneRecord
                                      (
                "\"{0}{1}\"",
                LinkPrefix,
                linkValue
                                      );

            if (ReferenceEquals(backupRecord, null))
            {
                Console.WriteLine
                (
                    "Не нашлось парной записи для MFN={0} ({1}{2})",
                    mfn,
                    LinkPrefix,
                    linkValue
                );
                Console.WriteLine(new string('=', 70));
                return;
            }

            Console.WriteLine("MFN={0}", mfn);
            RevisionInfo[] revisions = RevisionInfo.Parse(mainRecord)
                                       .Where(rev => rev.Name != "avd")
                                       .ToArray();
            if (revisions.Length == 0)
            {
                Console.WriteLine("Запись без ревизий!");
                Console.WriteLine(new string('=', 70));
                return;
            }

            RevisionInfo lastRevision = revisions.Last();
            DateTime     lastEdit     = IrbisDate.ConvertStringToDate(lastRevision.Date);

            Console.WriteLine
            (
                "Последнее редактирование: {0} {1:d}",
                lastRevision.Name,
                lastEdit
            );
            if (lastEdit > ThresholdDate)
            {
                Console.WriteLine("Запись редактировалась, надо восстанавливать вручную");
                Console.WriteLine(new string('=', 70));
                return;
            }

            if (CompareRecords(mainRecord, backupRecord))
            {
                Console.WriteLine("Нет различий между MAIN и BACKUP");
                goto DONE;
            }

            if (DoRestore)
            {
                RecordField[] residuaryFields = mainRecord.Fields
                                                .Where(field => field.Tag.OneOf(ResiduaryTags))
                                                .Select(field => field.Clone())
                                                .ToArray();
                RecordField[] backupFields = backupRecord.Fields
                                             .Where(field => !field.Tag.OneOf(ResiduaryTags))
                                             .Select(field => field.Clone())
                                             .ToArray();
                mainRecord.Fields.Clear();
                mainRecord.Fields.AddRange(backupFields);
                mainRecord.Fields.AddRange(residuaryFields);
                Console.WriteLine
                (
                    "Сформирована новая версия записи: {0} новых и {1} старых полей",
                    residuaryFields.Length,
                    backupFields.Length
                );
                connection.WriteRecord(mainRecord);
            }

DONE:
            Console.WriteLine(new string('=', 70));
            Console.WriteLine();
        }
Пример #14
0
        static EffectiveStat ProcessBook
        (
            [NotNull] MarcRecord record,
            [NotNull] string ksu
        )
        {
            Code.NotNull(record, "record");

            BookInfo book = new BookInfo(_provider, record);

            ExemplarInfo[] selected = book.Exemplars.Where
                                      (
                ex => ex.KsuNumber1.SameString(ksu)
                                      )
                                      .ToArray();
            Debug.Assert(selected.Length != 0, "exemplars.Length != 0");
            EffectiveStat result = new EffectiveStat
            {
                Description = _outputBooks ? book.Description : string.Empty,
                TitleCount  = 1
            };

            int totalExemplars = 0;

            foreach (ExemplarInfo exemplar in book.Exemplars)
            {
                int amount = exemplar.Amount.SafeToInt32();
                if (amount == 0)
                {
                    amount = 1;
                }

                totalExemplars += amount;
            }

            List <string> siglas = new List <string>();

            foreach (ExemplarInfo exemplar in selected)
            {
                DateTime date = IrbisDate.ConvertStringToDate(exemplar.Date);
                if (date != DateTime.MinValue)
                {
                    if (result.Date == DateTime.MinValue)
                    {
                        result.Date = date;
                    }
                    else if (date < result.Date)
                    {
                        result.Date = date;
                    }
                }

                int amount = exemplar.Amount.SafeToInt32();
                if (amount == 0)
                {
                    amount = 1;
                }

                result.ExemplarCount += amount;

                decimal price = exemplar.Price.SafeToDecimal(0);
                if (price == 0)
                {
                    price = book.Price;
                }

                siglas.Add(exemplar.Place);

                result.TotalCost += amount * price;
            }

            decimal loanCount = book.UsageCount;

            if (result.ExemplarCount != totalExemplars)
            {
                loanCount = loanCount * result.ExemplarCount / totalExemplars;
            }

            result.Bbk = record.FM(621).SafeSubstring(0, 2);

            result.LoanCount = (int)loanCount;
            result.Sigla     = string.Join(" ", siglas.Distinct()
                                           .Where(s => !string.IsNullOrEmpty(s))
                                           .Select(s => s.ToUpperInvariant()));

            return(result);
        }
Пример #15
0
        private void _fixShelfButton_Click
        (
            object sender,
            EventArgs e
        )
        {
            if (_currentRecord == null ||
                _currentExemplar == null)
            {
                XtraMessageBox.Show
                (
                    "Нечего исправлять!"
                );
                return;
            }

            string currentShelf = CurrentShelf;

            if (string.IsNullOrEmpty(currentShelf))
            {
                XtraMessageBox.Show
                (
                    "Не задан раздел!"
                );
                return;
            }

            if (currentShelf.ContainsAnySymbol
                (
                    ' ',
                    ',',
                    ';'
                ))
            {
                XtraMessageBox.Show
                (
                    "Раздел содержит недопустимые символы!"
                );
                return;
            }

            string shelf = _currentRecord.FM(906);

            if (!string.IsNullOrEmpty(shelf))
            {
                XtraMessageBox.Show
                (
                    "В записи уже установлен "
                    + "систематический шифр, "
                    + "его нельзя менять!"
                );
                return;
            }

            _currentRecord.SetField
            (
                906,
                currentShelf
            );

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            _client.WriteRecord
            (
                _currentRecord,
                false,
                true
            );
            stopwatch.Stop();
            _logBox.Output.WriteLine
            (
                "Исправлен раздел для метки {0}: {1} ({2})",
                _currentExemplar.Barcode,
                _currentRecord.UserData,
                stopwatch.Elapsed
            );

            _SetHtml(string.Empty);

            _currentRecord   = null;
            _currentExemplar = null;
        }
Пример #16
0
        private void _HandleNumber
        (
            [CanBeNull] string number
        )
        {
            _currentRecord   = null;
            _currentExemplar = null;
            _SetHtml(string.Empty);

            if (string.IsNullOrEmpty(number))
            {
                return;
            }

            _logBox.Output.WriteLine
            (
                "Введен номер: {0}",
                number
            );

            string prefix = CM.AppSettings["prefix"];

            int[] found = _client.Search
                          (
                "\"{0}{1}\"",
                prefix,
                number
                          );
            if (found.Length == 0)
            {
                _SetHtml
                (
                    "Не найден номер {0}",
                    number
                );
                return;
            }
            if (found.Length != 1)
            {
                _SetHtml
                (
                    "Много записей для номера {0}",
                    number
                );
                return;
            }

            MarcRecord record = _client.ReadRecord(found[0]);

            RecordField[] fields = record.Fields
                                   .GetField(910)
                                   .GetField('b', number);

            if (fields.Length == 0)
            {
                _SetHtml
                (
                    "Не найдено поле с номером {0}",
                    number
                );
                return;
            }
            if (fields.Length != 1)
            {
                _SetHtml
                (
                    "Много полей с номером {0}",
                    number
                );
                return;
            }

            ExemplarInfo exemplar = ExemplarInfo.Parse(fields[0]);

            StringBuilder diagnosis = new StringBuilder();

            diagnosis.AppendFormat
            (
                "<b>{0}</b><br/>",
                number
            );
            if (!string.IsNullOrEmpty(exemplar.RealPlace))
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Экземпляр уже был проверен "
                    + "в фонде</font> <b>{0}</b> ({1})<br/>",
                    exemplar.RealPlace,
                    exemplar.CheckedDate
                );
            }
            if (exemplar.Status != "0")
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Неверный статус "
                    + "экземпляра: </font><b>{0}</b><br/>",
                    exemplar.Status
                );
            }
            if (!exemplar.Place.SameString(CurrentFond))
            {
                diagnosis.AppendFormat
                (
                    "<font color='red'>Неверное место хранения "
                    + "экземпляра: </font><b>{0}</b><br/>",
                    exemplar.Place
                );
            }
            string currentShelf = CurrentShelf;

            if (!string.IsNullOrEmpty(currentShelf))
            {
                string[] items = currentShelf
                                 .Split(',', ';')
                                 .Select(item => item.Trim())
                                 .NonEmptyLines()
                                 .Select(item => item.ToUpperInvariant())
                                 .ToArray();

                string shelf = record.FM(906);
                if (string.IsNullOrEmpty(shelf))
                {
                    diagnosis.AppendFormat
                    (
                        "<font color='red'>Для книги не указан "
                        + "расстановочный шифр</font><br/>"
                    );
                }
                else if (items.Length != 0)
                {
                    shelf = shelf.ToUpperInvariant();
                    bool good = false;
                    foreach (string item in items)
                    {
                        if (shelf.StartsWith(item))
                        {
                            good = true;
                            break;
                        }
                    }
                    if (!good)
                    {
                        diagnosis.AppendFormat
                        (
                            "<font color='red'>Неверный шифр: "
                            + "</font><b>{0}</b><br/>",
                            shelf
                        );
                    }
                }
            }

            string currentCollection = CurrentCollection;

            if (!string.IsNullOrEmpty(currentCollection))
            {
                string collection = exemplar.Collection;
                if (currentCollection != collection)
                {
                    if (string.IsNullOrEmpty(collection))
                    {
                        diagnosis.AppendFormat
                        (
                            "<font color='red'>Для книги не указана "
                            + "коллекция"
                        );
                    }
                    else
                    {
                        diagnosis.AppendFormat
                        (
                            "<font color='red'>Неверная коллекция: "
                            + "</font><b>{0}</b><br/>",
                            collection
                        );
                    }
                }
            }

            diagnosis.AppendLine("<br/>");

            string cardFormat       = CM.AppSettings["card-format"];
            string briefDescription = _client.FormatRecord
                                      (
                cardFormat,
                record.Mfn
                                      ).Trim();

            diagnosis.Append(briefDescription);
            record.UserData = briefDescription;

            _SetHtml
            (
                "{0}",
                diagnosis.ToString()
            );

            _currentRecord   = record;
            _currentExemplar = exemplar;
        }
Пример #17
0
        static bool ProcessRecord
        (
            MarcRecord record
        )
        {
            string article = record.FM(1);

            if (string.IsNullOrEmpty(article))
            {
                WriteLogLine("Запись без идентификатора, пропускаем ее");
                return(false);
            }

            WriteLog("[{0}] СТАТЬЯ {1}: ", RecordCount, article);

            string code    = GetCode(record, "code");
            string year    = GetCode(record, "year");
            string volume  = GetCode(record, "to");
            string number  = GetCode(record, "no") ?? GetCode(record, "vy");
            string chapter = GetCode(record, "ch");

            if (string.IsNullOrEmpty(code))
            {
                WriteLog("Нет поля code, пропускаем запись ");
                return(false);
            }
            if (string.IsNullOrEmpty(year))
            {
                WriteLog("Нет поля year, пропускаем запись ");
                return(false);
            }
            if (string.IsNullOrEmpty(number))
            {
                WriteLog("Нет поля number, пропускаем запись ");
                return(false);
            }

            MagazineInfo magazine;

            if (!Magazines.TryGetValue(code, out magazine))
            {
                WriteLog("Журнал с неизвестным кодом {0}, пропускаем ", code);
                return(true);
            }

            if (magazine.Flag != "1")
            {
                WriteLog("Журнал не помечен как импортируемый, пропускаем ");
                return(true);
            }

            if ((string.CompareOrdinal(year, MinYear) < 0) ||
                (string.CompareOrdinal(year, MaxYear) > 0))
            {
                WriteLog
                (
                    "Год {0} не входит в диапазон {1}-{2}, пропускаем ",
                    year,
                    MinYear,
                    MaxYear
                );
                return(true);
            } // if

            string issueIndex = magazine.Index + "/" + year;

            if (!string.IsNullOrEmpty(volume))
            {
                issueIndex += ("/" + volume);
            }
            issueIndex += ("/" + number);
            if (!string.IsNullOrEmpty(chapter))
            {
                issueIndex += ("/" + chapter);
            }

            if (CurrentIssue != issueIndex)
            {
                WriteLog
                (
                    "ЖУРНАЛ {0} {1}/{2} ",
                    magazine.Title,
                    year,
                    number
                );

                int[] previousArticles = new int[0];

                lock (SyncRoot)
                {
                    try
                    {
                        previousArticles = Client.Search
                                           (
                            "\"II={0}\"",
                            issueIndex
                                           );
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                }
                if (previousArticles.Length != 0)
                {
                    if (WhenAlreadyExists == "skip")
                    {
                        WriteLog
                        (
                            "Найдено {0} предыдущих версий статей, пропускаем{1}",
                            previousArticles.Length,
                            Environment.NewLine
                        );
                        return(false);
                    }
                    if (WhenAlreadyExists == "delete")
                    {
                        WriteLog
                        (
                            "Найдено {0} предыдущих версий статей, удаляем... ",
                            previousArticles.Length
                        );
                        lock (SyncRoot)
                        {
                            Client.DeleteRecords
                            (
                                Client.Database,
                                previousArticles
                            );
                        }
                        WriteLog("удалено" + Environment.NewLine);
                    }
                    else
                    {
                        throw new ApplicationException
                              (
                                  string.Format
                                  (
                                      "Неизвестное управляющее слово {0}",
                                      WhenAlreadyExists
                                  )
                              );
                    }
                } // if

                MarcRecord issueRecord = null;

                lock (SyncRoot)
                {
                    try
                    {
                        issueRecord = Client.SearchReadOneRecord
                                      (
                            "\"I={0}\"",
                            issueIndex
                                      );
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                        return(true);
                    }
                }
                if (issueRecord == null)
                {
                    WriteLog("Нет записи I={0}, создаем ее... ", issueIndex);
                    issueRecord = new MarcRecord();
                    issueRecord
                    .SetField(920, "NJ")
                    .SetField(933, magazine.Index)
                    .SetField(903, issueIndex)
                    .SetField(934, year)
                    .SetField(936, number)
                    .SetField(300, "Запись создана при импорте статей МАРС");
                    if (!string.IsNullOrEmpty(volume))
                    {
                        issueRecord.SetField(935, volume);
                    }
                    lock (SyncRoot)
                    {
                        //Buffer.Append(issueRecord);
                        Client.WriteRecord(issueRecord, false, true);
                        RecordCount++;
                    }
                    WriteLog("создана ");
                } // if

                CurrentIssue = issueIndex;
            } // if

            RecordTask recordTask = new RecordTask
            {
                CurrentIssue = CurrentIssue,
                Magazine     = magazine,
                Record       = record
            };

            Queue.QueueTask
            (
                DoFormat,
                recordTask
            );
            WriteLog("=> в очередь ");

            return(true);
        }
Пример #18
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine
                (
                    "RecordDumper <connection-string> "
                    + "<search-expression> <output-file>"
                );

                return;
            }

            string connectionString = args[0];
            string searchExpression = args[1];
            string outputFileName   = args[2];

            try
            {
                JObject config
                    = JsonUtility.ReadObjectFromFile("dumperConfig.json");
                int   etalonTag   = config["etalonTag"].Value <int>();
                int[] excludeTags = config["excludeTags"]
                                    .Values <int>().ToArray();
                string[] excludePages = config["excludePages"]
                                        .Values <string>().ToArray();

                using (IrbisProvider provider = ProviderManager
                                                .GetAndConfigureProvider(connectionString))
                    using (StreamWriter writer = TextWriterUtility.Create
                                                 (
                               outputFileName,
                               IrbisEncoding.Utf8
                                                 ))
                    {
                        FileSpecification specification = new FileSpecification
                                                          (
                            IrbisPath.MasterFile,
                            provider.Database,
                            "WS31.OPT"
                                                          );
                        IrbisOpt opt = IrbisOpt.LoadFromServer
                                       (
                            provider,
                            specification
                                       );
                        if (ReferenceEquals(opt, null))
                        {
                            throw new IrbisException("Can't load OPT file!");
                        }

                        int[] found = provider.Search(searchExpression);
                        Console.WriteLine("Found: {0}", found.Length);

                        foreach (int mfn in found)
                        {
                            MarcRecord record = provider.ReadRecord(mfn);
                            if (ReferenceEquals(record, null))
                            {
                                continue;
                            }
                            string title = record.FM(etalonTag);
                            if (string.IsNullOrEmpty(title))
                            {
                                continue;
                            }

                            string wsName = opt.SelectWorksheet(opt.GetWorksheet(record));
                            if (string.IsNullOrEmpty(wsName))
                            {
                                continue;
                            }
                            specification = new FileSpecification
                                            (
                                IrbisPath.MasterFile,
                                provider.Database,
                                wsName + ".ws"
                                            );
                            WsFile worksheet = WsFile.ReadFromServer
                                               (
                                provider,
                                specification
                                               );
                            if (ReferenceEquals(worksheet, null))
                            {
                                continue;
                            }

                            Console.WriteLine("MFN={0}: {1}", mfn, title);
                            writer.WriteLine("<h3>{0}</h3>", title);

                            string description = provider.FormatRecord(record, "@");
                            writer.WriteLine(description);

                            RecordField[] fields = record.Fields
                                                   .Where(field => !field.Tag.OneOf(excludeTags))
                                                   .ToArray();

                            writer.WriteLine
                            (
                                "<table border=\"1\" "
                                + "cellpadding=\"3\" "
                                + "cellspacing=\"0\" "
                                + ">"
                            );
                            writer.WriteLine
                            (
                                "<tr bgcolor=\"black\">"
                                + "<th style=\"color:white;text-align:left;\">Поле</th>"
                                + "<th style=\"color:white;text-align:left;\">Подполе</th>"
                                + "<th style=\"color:white;text-align:left;\">Значение</th>"
                                + "</tr>"
                            );
                            foreach (WorksheetPage page in worksheet.Pages)
                            {
                                if (page.Name.OneOf(excludePages))
                                {
                                    continue;
                                }

                                int[] tags = page.Items
                                             .Select(item => item.Tag)
                                             .Select(NumericUtility.ParseInt32)
                                             .ToArray();
                                if (!fields.Any(field => field.Tag.OneOf(tags)))
                                {
                                    continue;
                                }
                                writer.WriteLine
                                (
                                    "<tr><td colspan=\"3\"><b>Вкладка «{0}»</b></td></tr>",
                                    page.Name
                                );

                                foreach (WorksheetItem item in page.Items)
                                {
                                    if (string.IsNullOrEmpty(item.Tag))
                                    {
                                        continue;
                                    }

                                    int tag = NumericUtility.ParseInt32(item.Tag);
                                    if (tag <= 0)
                                    {
                                        continue;
                                    }

                                    RecordField[] itemFields = fields.GetField(tag);
                                    for (int i = 0; i < itemFields.Length; i++)
                                    {
                                        RecordField field = itemFields[i];
                                        title = item.Title;
                                        title = StringUtility.Sparse(title);
                                        if (i != 0)
                                        {
                                            title = string.Format
                                                    (
                                                "(повторение {0})",
                                                i + 1
                                                    );
                                        }
                                        int rowspan = 1;
                                        if (string.IsNullOrEmpty(field.Value))
                                        {
                                            rowspan = 1 + field.SubFields.Count;
                                        }
                                        writer.WriteLine
                                        (
                                            "<tr><td rowspan=\"{0}\" \"width=\"{1}\"><b>{2}</b></td><td colspan=\"2\"><b>{3}</b></td></tr>",
                                            rowspan,
                                            FirstWidth,
                                            field.Tag,
                                            HtmlText.Encode(title)
                                        );

                                        if (!string.IsNullOrEmpty(field.Value))
                                        {
                                            writer.WriteLine
                                            (
                                                "<tr><td colspan=\"2\">&nbsp;</td><td>{0}</td></tr>",
                                                HtmlText.Encode(field.Value)
                                            );
                                        }

                                        if (item.EditMode == "5")
                                        {
                                            string inputInfo = item.InputInfo
                                                               .ThrowIfNull("item.InputInfo");

                                            // Поле с подполями
                                            specification = new FileSpecification
                                                            (
                                                IrbisPath.MasterFile,
                                                provider.Database,
                                                inputInfo
                                                            );
                                            WssFile wss = WssFile.ReadFromServer
                                                          (
                                                provider,
                                                specification
                                                          );
                                            if (ReferenceEquals(wss, null))
                                            {
                                                Console.WriteLine
                                                (
                                                    "Can't load: " + inputInfo
                                                );
                                            }
                                            else
                                            {
                                                foreach (WorksheetItem line in wss.Items)
                                                {
                                                    char     code     = line.Tag.FirstChar();
                                                    SubField subField = field.GetFirstSubField(code);
                                                    if (!ReferenceEquals(subField, null))
                                                    {
                                                        writer.WriteLine
                                                        (
                                                            "<tr>"
                                                            + "<td width=\"{0}\"><b>{1}</b>: {2}</td>"
                                                            + "<td width=\"{3}\">{4}</td></tr>",
                                                            SecondWidth,
                                                            CharUtility.ToUpperInvariant(code),
                                                            HtmlText.Encode(line.Title),
                                                            ThirdWidth,
                                                            HtmlText.Encode(subField.Value)
                                                        );
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            writer.WriteLine("</table>");
                        }
                    }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }